dagre-d3.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.dagreD3 = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /**
  3. * @license
  4. * Copyright (c) 2012-2013 Chris Pettitt
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. module.exports = {
  25. graphlib: require("./lib/graphlib"),
  26. dagre: require("./lib/dagre"),
  27. intersect: require("./lib/intersect"),
  28. render: require("./lib/render"),
  29. util: require("./lib/util"),
  30. version: require("./lib/version")
  31. };
  32. },{"./lib/dagre":8,"./lib/graphlib":9,"./lib/intersect":10,"./lib/render":25,"./lib/util":27,"./lib/version":28}],2:[function(require,module,exports){
  33. var util = require("./util");
  34. module.exports = {
  35. "default": normal,
  36. "normal": normal,
  37. "vee": vee,
  38. "undirected": undirected
  39. };
  40. function normal(parent, id, edge, type) {
  41. var marker = parent.append("marker")
  42. .attr("id", id)
  43. .attr("viewBox", "0 0 10 10")
  44. .attr("refX", 9)
  45. .attr("refY", 5)
  46. .attr("markerUnits", "strokeWidth")
  47. .attr("markerWidth", 8)
  48. .attr("markerHeight", 6)
  49. .attr("orient", "auto");
  50. var path = marker.append("path")
  51. .attr("d", "M 0 0 L 10 5 L 0 10 z")
  52. .style("stroke-width", 1)
  53. .style("stroke-dasharray", "1,0");
  54. util.applyStyle(path, edge[type + "Style"]);
  55. if (edge[type + "Class"]) {
  56. path.attr("class", edge[type + "Class"]);
  57. }
  58. }
  59. function vee(parent, id, edge, type) {
  60. var marker = parent.append("marker")
  61. .attr("id", id)
  62. .attr("viewBox", "0 0 10 10")
  63. .attr("refX", 9)
  64. .attr("refY", 5)
  65. .attr("markerUnits", "strokeWidth")
  66. .attr("markerWidth", 8)
  67. .attr("markerHeight", 6)
  68. .attr("orient", "auto");
  69. var path = marker.append("path")
  70. .attr("d", "M 0 0 L 10 5 L 0 10 L 4 5 z")
  71. .style("stroke-width", 1)
  72. .style("stroke-dasharray", "1,0");
  73. util.applyStyle(path, edge[type + "Style"]);
  74. if (edge[type + "Class"]) {
  75. path.attr("class", edge[type + "Class"]);
  76. }
  77. }
  78. function undirected(parent, id, edge, type) {
  79. var marker = parent.append("marker")
  80. .attr("id", id)
  81. .attr("viewBox", "0 0 10 10")
  82. .attr("refX", 9)
  83. .attr("refY", 5)
  84. .attr("markerUnits", "strokeWidth")
  85. .attr("markerWidth", 8)
  86. .attr("markerHeight", 6)
  87. .attr("orient", "auto");
  88. var path = marker.append("path")
  89. .attr("d", "M 0 5 L 10 5")
  90. .style("stroke-width", 1)
  91. .style("stroke-dasharray", "1,0");
  92. util.applyStyle(path, edge[type + "Style"]);
  93. if (edge[type + "Class"]) {
  94. path.attr("class", edge[type + "Class"]);
  95. }
  96. }
  97. },{"./util":27}],3:[function(require,module,exports){
  98. var util = require("./util"),
  99. d3 = require("./d3"),
  100. addLabel = require("./label/add-label");
  101. module.exports = createClusters;
  102. function createClusters(selection, g) {
  103. var clusters = g.nodes().filter(function(v) { return util.isSubgraph(g, v); }),
  104. svgClusters = selection.selectAll("g.cluster")
  105. .data(clusters, function(v) { return v; });
  106. svgClusters.selectAll("*").remove();
  107. svgClusters.enter()
  108. .append("g")
  109. .attr("class", "cluster")
  110. .attr("id",function(v){
  111. var node = g.node(v);
  112. return node.id;
  113. })
  114. .style("opacity", 0);
  115. svgClusters = selection.selectAll("g.cluster");
  116. util.applyTransition(svgClusters, g)
  117. .style("opacity", 1);
  118. svgClusters.each(function(v) {
  119. var node = g.node(v),
  120. thisGroup = d3.select(this);
  121. d3.select(this).append("rect");
  122. var labelGroup = thisGroup.append("g").attr("class", "label");
  123. addLabel(labelGroup, node, node.clusterLabelPos);
  124. });
  125. svgClusters.selectAll("rect").each(function(c) {
  126. var node = g.node(c);
  127. var domCluster = d3.select(this);
  128. util.applyStyle(domCluster, node.style);
  129. });
  130. util.applyTransition(svgClusters.exit(), g)
  131. .style("opacity", 0)
  132. .remove();
  133. return svgClusters;
  134. }
  135. },{"./d3":7,"./label/add-label":18,"./util":27}],4:[function(require,module,exports){
  136. "use strict";
  137. var _ = require("./lodash"),
  138. addLabel = require("./label/add-label"),
  139. util = require("./util"),
  140. d3 = require("./d3");
  141. module.exports = createEdgeLabels;
  142. function createEdgeLabels(selection, g) {
  143. var svgEdgeLabels = selection.selectAll("g.edgeLabel")
  144. .data(g.edges(), function(e) { return util.edgeToId(e); })
  145. .classed("update", true);
  146. svgEdgeLabels.selectAll("*").remove();
  147. svgEdgeLabels.enter()
  148. .append("g")
  149. .classed("edgeLabel", true)
  150. .style("opacity", 0);
  151. svgEdgeLabels = selection.selectAll("g.edgeLabel");
  152. svgEdgeLabels.each(function(e) {
  153. var edge = g.edge(e),
  154. label = addLabel(d3.select(this), g.edge(e), 0, 0).classed("label", true),
  155. bbox = label.node().getBBox();
  156. if (edge.labelId) { label.attr("id", edge.labelId); }
  157. if (!_.has(edge, "width")) { edge.width = bbox.width; }
  158. if (!_.has(edge, "height")) { edge.height = bbox.height; }
  159. });
  160. util.applyTransition(svgEdgeLabels.exit(), g)
  161. .style("opacity", 0)
  162. .remove();
  163. return svgEdgeLabels;
  164. }
  165. },{"./d3":7,"./label/add-label":18,"./lodash":21,"./util":27}],5:[function(require,module,exports){
  166. "use strict";
  167. var _ = require("./lodash"),
  168. intersectNode = require("./intersect/intersect-node"),
  169. util = require("./util"),
  170. d3 = require("./d3");
  171. module.exports = createEdgePaths;
  172. function createEdgePaths(selection, g, arrows) {
  173. var svgPaths = selection.selectAll("g.edgePath")
  174. .data(g.edges(), function(e) { return util.edgeToId(e); })
  175. .classed("update", true);
  176. enter(svgPaths, g);
  177. exit(svgPaths, g);
  178. svgPaths = selection.selectAll("g.edgePath");
  179. util.applyTransition(svgPaths, g)
  180. .style("opacity", 1);
  181. // Save DOM element in the path group, and set ID and class
  182. svgPaths.each(function(e) {
  183. var domEdge = d3.select(this);
  184. var edge = g.edge(e);
  185. edge.elem = this;
  186. if (edge.id) {
  187. domEdge.attr("id", edge.id);
  188. }
  189. util.applyClass(domEdge, edge["class"],
  190. (domEdge.classed("update") ? "update " : "") + "edgePath");
  191. });
  192. svgPaths.selectAll("path.path")
  193. .each(function(e) {
  194. var edge = g.edge(e);
  195. edge.arrowheadId = _.uniqueId("arrowhead");
  196. var domEdge = d3.select(this)
  197. .attr("marker-end", function() {
  198. return "url(" + makeFragmentRef(location.href, edge.arrowheadId) + ")";
  199. })
  200. .style("fill", "none");
  201. util.applyTransition(domEdge, g)
  202. .attr("d", function(e) { return calcPoints(g, e); });
  203. util.applyStyle(domEdge, edge.style);
  204. });
  205. svgPaths.selectAll("defs *").remove();
  206. svgPaths.selectAll("defs")
  207. .each(function(e) {
  208. var edge = g.edge(e),
  209. arrowhead = arrows[edge.arrowhead];
  210. arrowhead(d3.select(this), edge.arrowheadId, edge, "arrowhead");
  211. });
  212. return svgPaths;
  213. }
  214. function makeFragmentRef(url, fragmentId) {
  215. var baseUrl = url.split("#")[0];
  216. return baseUrl + "#" + fragmentId;
  217. }
  218. function calcPoints(g, e) {
  219. var edge = g.edge(e),
  220. tail = g.node(e.v),
  221. head = g.node(e.w),
  222. points = edge.points.slice(1, edge.points.length - 1);
  223. points.unshift(intersectNode(tail, points[0]));
  224. points.push(intersectNode(head, points[points.length - 1]));
  225. return createLine(edge, points);
  226. }
  227. function createLine(edge, points) {
  228. var line = d3.line()
  229. .x(function(d) { return d.x; })
  230. .y(function(d) { return d.y; });
  231. line.curve(edge.curve);
  232. return line(points);
  233. }
  234. function getCoords(elem) {
  235. var bbox = elem.getBBox(),
  236. matrix = elem.ownerSVGElement.getScreenCTM()
  237. .inverse()
  238. .multiply(elem.getScreenCTM())
  239. .translate(bbox.width / 2, bbox.height / 2);
  240. return { x: matrix.e, y: matrix.f };
  241. }
  242. function enter(svgPaths, g) {
  243. var svgPathsEnter = svgPaths.enter()
  244. .append("g")
  245. .attr("class", "edgePath")
  246. .style("opacity", 0);
  247. svgPathsEnter.append("path")
  248. .attr("class", "path")
  249. .attr("d", function(e) {
  250. var edge = g.edge(e),
  251. sourceElem = g.node(e.v).elem,
  252. points = _.range(edge.points.length).map(function() { return getCoords(sourceElem); });
  253. return createLine(edge, points);
  254. });
  255. svgPathsEnter.append("defs");
  256. }
  257. function exit(svgPaths, g) {
  258. var svgPathExit = svgPaths.exit();
  259. util.applyTransition(svgPathExit, g)
  260. .style("opacity", 0)
  261. .remove();
  262. util.applyTransition(svgPathExit.select("path.path"), g)
  263. .attr("d", function(e) {
  264. var source = g.node(e.v);
  265. if (source) {
  266. var points = _.range(this.getTotalLength()).map(function() { return source; });
  267. return createLine({}, points);
  268. } else {
  269. return d3.select(this).attr("d");
  270. }
  271. });
  272. }
  273. },{"./d3":7,"./intersect/intersect-node":14,"./lodash":21,"./util":27}],6:[function(require,module,exports){
  274. "use strict";
  275. var _ = require("./lodash"),
  276. addLabel = require("./label/add-label"),
  277. util = require("./util"),
  278. d3 = require("./d3");
  279. module.exports = createNodes;
  280. function createNodes(selection, g, shapes) {
  281. var simpleNodes = g.nodes().filter(function(v) { return !util.isSubgraph(g, v); });
  282. var svgNodes = selection.selectAll("g.node")
  283. .data(simpleNodes, function(v) { return v; })
  284. .classed("update", true);
  285. svgNodes.selectAll("*").remove();
  286. svgNodes.enter()
  287. .append("g")
  288. .attr("class", "node")
  289. .style("opacity", 0);
  290. svgNodes = selection.selectAll("g.node");
  291. svgNodes.each(function(v) {
  292. var node = g.node(v),
  293. thisGroup = d3.select(this);
  294. util.applyClass(thisGroup, node["class"],
  295. (thisGroup.classed("update") ? "update " : "") + "node");
  296. var labelGroup = thisGroup.append("g").attr("class", "label"),
  297. labelDom = addLabel(labelGroup, node),
  298. shape = shapes[node.shape],
  299. bbox = _.pick(labelDom.node().getBBox(), "width", "height");
  300. node.elem = this;
  301. if (node.id) { thisGroup.attr("id", node.id); }
  302. if (node.labelId) { labelGroup.attr("id", node.labelId); }
  303. if (_.has(node, "width")) { bbox.width = node.width; }
  304. if (_.has(node, "height")) { bbox.height = node.height; }
  305. bbox.width += node.paddingLeft + node.paddingRight;
  306. bbox.height += node.paddingTop + node.paddingBottom;
  307. labelGroup.attr("transform", "translate(" +
  308. ((node.paddingLeft - node.paddingRight) / 2) + "," +
  309. ((node.paddingTop - node.paddingBottom) / 2) + ")");
  310. var shapeSvg = shape(d3.select(this), bbox, node);
  311. util.applyStyle(shapeSvg, node.style);
  312. var shapeBBox = shapeSvg.node().getBBox();
  313. node.width = shapeBBox.width;
  314. node.height = shapeBBox.height;
  315. });
  316. util.applyTransition(svgNodes.exit(), g)
  317. .style("opacity", 0)
  318. .remove();
  319. return svgNodes;
  320. }
  321. },{"./d3":7,"./label/add-label":18,"./lodash":21,"./util":27}],7:[function(require,module,exports){
  322. // Stub to get D3 either via NPM or from the global object
  323. var d3;
  324. if (!d3) {
  325. if (require) {
  326. try {
  327. d3 = require("d3");
  328. }
  329. catch (e) {
  330. }
  331. }
  332. }
  333. if (!d3) {
  334. d3 = window.d3;
  335. }
  336. module.exports = d3;
  337. },{"d3":69}],8:[function(require,module,exports){
  338. /* global window */
  339. var dagre;
  340. if (require) {
  341. try {
  342. dagre = require("dagre");
  343. } catch (e) {}
  344. }
  345. if (!dagre) {
  346. dagre = window.dagre;
  347. }
  348. module.exports = dagre;
  349. },{"dagre":70}],9:[function(require,module,exports){
  350. /* global window */
  351. var graphlib;
  352. if (require) {
  353. try {
  354. graphlib = require("graphlib");
  355. } catch (e) {}
  356. }
  357. if (!graphlib) {
  358. graphlib = window.graphlib;
  359. }
  360. module.exports = graphlib;
  361. },{"graphlib":100}],10:[function(require,module,exports){
  362. module.exports = {
  363. node: require("./intersect-node"),
  364. circle: require("./intersect-circle"),
  365. ellipse: require("./intersect-ellipse"),
  366. polygon: require("./intersect-polygon"),
  367. rect: require("./intersect-rect")
  368. };
  369. },{"./intersect-circle":11,"./intersect-ellipse":12,"./intersect-node":14,"./intersect-polygon":15,"./intersect-rect":16}],11:[function(require,module,exports){
  370. var intersectEllipse = require("./intersect-ellipse");
  371. module.exports = intersectCircle;
  372. function intersectCircle(node, rx, point) {
  373. return intersectEllipse(node, rx, rx, point);
  374. }
  375. },{"./intersect-ellipse":12}],12:[function(require,module,exports){
  376. module.exports = intersectEllipse;
  377. function intersectEllipse(node, rx, ry, point) {
  378. // Formulae from: http://mathworld.wolfram.com/Ellipse-LineIntersection.html
  379. var cx = node.x;
  380. var cy = node.y;
  381. var px = cx - point.x;
  382. var py = cy - point.y;
  383. var det = Math.sqrt(rx * rx * py * py + ry * ry * px * px);
  384. var dx = Math.abs(rx * ry * px / det);
  385. if (point.x < cx) {
  386. dx = -dx;
  387. }
  388. var dy = Math.abs(rx * ry * py / det);
  389. if (point.y < cy) {
  390. dy = -dy;
  391. }
  392. return {x: cx + dx, y: cy + dy};
  393. }
  394. },{}],13:[function(require,module,exports){
  395. module.exports = intersectLine;
  396. /*
  397. * Returns the point at which two lines, p and q, intersect or returns
  398. * undefined if they do not intersect.
  399. */
  400. function intersectLine(p1, p2, q1, q2) {
  401. // Algorithm from J. Avro, (ed.) Graphics Gems, No 2, Morgan Kaufmann, 1994,
  402. // p7 and p473.
  403. var a1, a2, b1, b2, c1, c2;
  404. var r1, r2 , r3, r4;
  405. var denom, offset, num;
  406. var x, y;
  407. // Compute a1, b1, c1, where line joining points 1 and 2 is F(x,y) = a1 x +
  408. // b1 y + c1 = 0.
  409. a1 = p2.y - p1.y;
  410. b1 = p1.x - p2.x;
  411. c1 = (p2.x * p1.y) - (p1.x * p2.y);
  412. // Compute r3 and r4.
  413. r3 = ((a1 * q1.x) + (b1 * q1.y) + c1);
  414. r4 = ((a1 * q2.x) + (b1 * q2.y) + c1);
  415. // Check signs of r3 and r4. If both point 3 and point 4 lie on
  416. // same side of line 1, the line segments do not intersect.
  417. if ((r3 !== 0) && (r4 !== 0) && sameSign(r3, r4)) {
  418. return /*DONT_INTERSECT*/;
  419. }
  420. // Compute a2, b2, c2 where line joining points 3 and 4 is G(x,y) = a2 x + b2 y + c2 = 0
  421. a2 = q2.y - q1.y;
  422. b2 = q1.x - q2.x;
  423. c2 = (q2.x * q1.y) - (q1.x * q2.y);
  424. // Compute r1 and r2
  425. r1 = (a2 * p1.x) + (b2 * p1.y) + c2;
  426. r2 = (a2 * p2.x) + (b2 * p2.y) + c2;
  427. // Check signs of r1 and r2. If both point 1 and point 2 lie
  428. // on same side of second line segment, the line segments do
  429. // not intersect.
  430. if ((r1 !== 0) && (r2 !== 0) && (sameSign(r1, r2))) {
  431. return /*DONT_INTERSECT*/;
  432. }
  433. // Line segments intersect: compute intersection point.
  434. denom = (a1 * b2) - (a2 * b1);
  435. if (denom === 0) {
  436. return /*COLLINEAR*/;
  437. }
  438. offset = Math.abs(denom / 2);
  439. // The denom/2 is to get rounding instead of truncating. It
  440. // is added or subtracted to the numerator, depending upon the
  441. // sign of the numerator.
  442. num = (b1 * c2) - (b2 * c1);
  443. x = (num < 0) ? ((num - offset) / denom) : ((num + offset) / denom);
  444. num = (a2 * c1) - (a1 * c2);
  445. y = (num < 0) ? ((num - offset) / denom) : ((num + offset) / denom);
  446. return { x: x, y: y };
  447. }
  448. function sameSign(r1, r2) {
  449. return r1 * r2 > 0;
  450. }
  451. },{}],14:[function(require,module,exports){
  452. module.exports = intersectNode;
  453. function intersectNode(node, point) {
  454. return node.intersect(point);
  455. }
  456. },{}],15:[function(require,module,exports){
  457. var intersectLine = require("./intersect-line");
  458. module.exports = intersectPolygon;
  459. /*
  460. * Returns the point ({x, y}) at which the point argument intersects with the
  461. * node argument assuming that it has the shape specified by polygon.
  462. */
  463. function intersectPolygon(node, polyPoints, point) {
  464. var x1 = node.x;
  465. var y1 = node.y;
  466. var intersections = [];
  467. var minX = Number.POSITIVE_INFINITY,
  468. minY = Number.POSITIVE_INFINITY;
  469. polyPoints.forEach(function(entry) {
  470. minX = Math.min(minX, entry.x);
  471. minY = Math.min(minY, entry.y);
  472. });
  473. var left = x1 - node.width / 2 - minX;
  474. var top = y1 - node.height / 2 - minY;
  475. for (var i = 0; i < polyPoints.length; i++) {
  476. var p1 = polyPoints[i];
  477. var p2 = polyPoints[i < polyPoints.length - 1 ? i + 1 : 0];
  478. var intersect = intersectLine(node, point,
  479. {x: left + p1.x, y: top + p1.y}, {x: left + p2.x, y: top + p2.y});
  480. if (intersect) {
  481. intersections.push(intersect);
  482. }
  483. }
  484. if (!intersections.length) {
  485. console.log("NO INTERSECTION FOUND, RETURN NODE CENTER", node);
  486. return node;
  487. }
  488. if (intersections.length > 1) {
  489. // More intersections, find the one nearest to edge end point
  490. intersections.sort(function(p, q) {
  491. var pdx = p.x - point.x,
  492. pdy = p.y - point.y,
  493. distp = Math.sqrt(pdx * pdx + pdy * pdy),
  494. qdx = q.x - point.x,
  495. qdy = q.y - point.y,
  496. distq = Math.sqrt(qdx * qdx + qdy * qdy);
  497. return (distp < distq) ? -1 : (distp === distq ? 0 : 1);
  498. });
  499. }
  500. return intersections[0];
  501. }
  502. },{"./intersect-line":13}],16:[function(require,module,exports){
  503. module.exports = intersectRect;
  504. function intersectRect(node, point) {
  505. var x = node.x;
  506. var y = node.y;
  507. // Rectangle intersection algorithm from:
  508. // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
  509. var dx = point.x - x;
  510. var dy = point.y - y;
  511. var w = node.width / 2;
  512. var h = node.height / 2;
  513. var sx, sy;
  514. if (Math.abs(dy) * w > Math.abs(dx) * h) {
  515. // Intersection is top or bottom of rect.
  516. if (dy < 0) {
  517. h = -h;
  518. }
  519. sx = dy === 0 ? 0 : h * dx / dy;
  520. sy = h;
  521. } else {
  522. // Intersection is left or right of rect.
  523. if (dx < 0) {
  524. w = -w;
  525. }
  526. sx = w;
  527. sy = dx === 0 ? 0 : w * dy / dx;
  528. }
  529. return {x: x + sx, y: y + sy};
  530. }
  531. },{}],17:[function(require,module,exports){
  532. var util = require("../util");
  533. module.exports = addHtmlLabel;
  534. function addHtmlLabel(root, node) {
  535. var fo = root
  536. .append("foreignObject")
  537. .attr("width", "100000");
  538. var div = fo
  539. .append("xhtml:div");
  540. div.attr("xmlns", "http://www.w3.org/1999/xhtml");
  541. var label = node.label;
  542. switch(typeof label) {
  543. case "function":
  544. div.insert(label);
  545. break;
  546. case "object":
  547. // Currently we assume this is a DOM object.
  548. div.insert(function() { return label; });
  549. break;
  550. default: div.html(label);
  551. }
  552. util.applyStyle(div, node.labelStyle);
  553. div.style("display", "inline-block");
  554. // Fix for firefox
  555. div.style("white-space", "nowrap");
  556. var client = div.node().getBoundingClientRect();
  557. fo
  558. .attr("width", client.width)
  559. .attr("height", client.height);
  560. return fo;
  561. }
  562. },{"../util":27}],18:[function(require,module,exports){
  563. var addTextLabel = require("./add-text-label"),
  564. addHtmlLabel = require("./add-html-label"),
  565. addSVGLabel = require("./add-svg-label");
  566. module.exports = addLabel;
  567. function addLabel(root, node, location) {
  568. var label = node.label;
  569. var labelSvg = root.append("g");
  570. // Allow the label to be a string, a function that returns a DOM element, or
  571. // a DOM element itself.
  572. if (node.labelType === "svg") {
  573. addSVGLabel(labelSvg, node);
  574. } else if (typeof label !== "string" || node.labelType === "html") {
  575. addHtmlLabel(labelSvg, node);
  576. } else {
  577. addTextLabel(labelSvg, node);
  578. }
  579. var labelBBox = labelSvg.node().getBBox();
  580. var y;
  581. switch(location) {
  582. case "top":
  583. y = (-node.height / 2);
  584. break;
  585. case "bottom":
  586. y = (node.height / 2) - labelBBox.height;
  587. break;
  588. default:
  589. y = (-labelBBox.height / 2);
  590. }
  591. labelSvg.attr("transform",
  592. "translate(" + (-labelBBox.width / 2) + "," + y + ")");
  593. return labelSvg;
  594. }
  595. },{"./add-html-label":17,"./add-svg-label":19,"./add-text-label":20}],19:[function(require,module,exports){
  596. var util = require("../util");
  597. module.exports = addSVGLabel;
  598. function addSVGLabel(root, node) {
  599. var domNode = root;
  600. domNode.node().appendChild(node.label);
  601. util.applyStyle(domNode, node.labelStyle);
  602. return domNode;
  603. }
  604. },{"../util":27}],20:[function(require,module,exports){
  605. var util = require("../util");
  606. module.exports = addTextLabel;
  607. /*
  608. * Attaches a text label to the specified root. Handles escape sequences.
  609. */
  610. function addTextLabel(root, node) {
  611. var domNode = root.append("text");
  612. var lines = processEscapeSequences(node.label).split("\n");
  613. for (var i = 0; i < lines.length; i++) {
  614. domNode
  615. .append("tspan")
  616. .attr("xml:space", "preserve")
  617. .attr("dy", "1em")
  618. .attr("x", "1")
  619. .text(lines[i]);
  620. }
  621. util.applyStyle(domNode, node.labelStyle);
  622. return domNode;
  623. }
  624. function processEscapeSequences(text) {
  625. var newText = "",
  626. escaped = false,
  627. ch;
  628. for (var i = 0; i < text.length; ++i) {
  629. ch = text[i];
  630. if (escaped) {
  631. switch(ch) {
  632. case "n": newText += "\n"; break;
  633. default: newText += ch;
  634. }
  635. escaped = false;
  636. } else if (ch === "\\") {
  637. escaped = true;
  638. } else {
  639. newText += ch;
  640. }
  641. }
  642. return newText;
  643. }
  644. },{"../util":27}],21:[function(require,module,exports){
  645. /* global window */
  646. var lodash;
  647. if (require) {
  648. try {
  649. lodash = require("lodash");
  650. } catch (e) {}
  651. }
  652. if (!lodash) {
  653. lodash = window._;
  654. }
  655. module.exports = lodash;
  656. },{"lodash":123}],22:[function(require,module,exports){
  657. "use strict";
  658. var util = require("./util"),
  659. d3 = require("./d3");
  660. module.exports = positionClusters;
  661. function positionClusters(selection, g) {
  662. var created = selection.filter(function() { return !d3.select(this).classed("update"); });
  663. function translate(v) {
  664. var node = g.node(v);
  665. return "translate(" + node.x + "," + node.y + ")";
  666. }
  667. created.attr("transform", translate);
  668. util.applyTransition(selection, g)
  669. .style("opacity", 1)
  670. .attr("transform", translate);
  671. util.applyTransition(created.selectAll("rect"), g)
  672. .attr("width", function(v) { return g.node(v).width; })
  673. .attr("height", function(v) { return g.node(v).height; })
  674. .attr("x", function(v) {
  675. var node = g.node(v);
  676. return -node.width / 2;
  677. })
  678. .attr("y", function(v) {
  679. var node = g.node(v);
  680. return -node.height / 2;
  681. });
  682. }
  683. },{"./d3":7,"./util":27}],23:[function(require,module,exports){
  684. "use strict";
  685. var util = require("./util"),
  686. d3 = require("./d3"),
  687. _ = require("./lodash");
  688. module.exports = positionEdgeLabels;
  689. function positionEdgeLabels(selection, g) {
  690. var created = selection.filter(function() { return !d3.select(this).classed("update"); });
  691. function translate(e) {
  692. var edge = g.edge(e);
  693. return _.has(edge, "x") ? "translate(" + edge.x + "," + edge.y + ")" : "";
  694. }
  695. created.attr("transform", translate);
  696. util.applyTransition(selection, g)
  697. .style("opacity", 1)
  698. .attr("transform", translate);
  699. }
  700. },{"./d3":7,"./lodash":21,"./util":27}],24:[function(require,module,exports){
  701. "use strict";
  702. var util = require("./util"),
  703. d3 = require("./d3");
  704. module.exports = positionNodes;
  705. function positionNodes(selection, g) {
  706. var created = selection.filter(function() { return !d3.select(this).classed("update"); });
  707. function translate(v) {
  708. var node = g.node(v);
  709. return "translate(" + node.x + "," + node.y + ")";
  710. }
  711. created.attr("transform", translate);
  712. util.applyTransition(selection, g)
  713. .style("opacity", 1)
  714. .attr("transform", translate);
  715. }
  716. },{"./d3":7,"./util":27}],25:[function(require,module,exports){
  717. var _ = require("./lodash"),
  718. d3 = require("./d3"),
  719. layout = require("./dagre").layout;
  720. module.exports = render;
  721. // This design is based on http://bost.ocks.org/mike/chart/.
  722. function render() {
  723. var createNodes = require("./create-nodes"),
  724. createClusters = require("./create-clusters"),
  725. createEdgeLabels = require("./create-edge-labels"),
  726. createEdgePaths = require("./create-edge-paths"),
  727. positionNodes = require("./position-nodes"),
  728. positionEdgeLabels = require("./position-edge-labels"),
  729. positionClusters = require("./position-clusters"),
  730. shapes = require("./shapes"),
  731. arrows = require("./arrows");
  732. var fn = function(svg, g) {
  733. preProcessGraph(g);
  734. svg.selectAll("*").remove();
  735. var outputGroup = createOrSelectGroup(svg, "output"),
  736. clustersGroup = createOrSelectGroup(outputGroup, "clusters"),
  737. edgePathsGroup = createOrSelectGroup(outputGroup, "edgePaths"),
  738. edgeLabels = createEdgeLabels(createOrSelectGroup(outputGroup, "edgeLabels"), g),
  739. nodes = createNodes(createOrSelectGroup(outputGroup, "nodes"), g, shapes);
  740. layout(g);
  741. positionNodes(nodes, g);
  742. positionEdgeLabels(edgeLabels, g);
  743. createEdgePaths(edgePathsGroup, g, arrows);
  744. var clusters = createClusters(clustersGroup, g);
  745. positionClusters(clusters, g);
  746. postProcessGraph(g);
  747. };
  748. fn.createNodes = function(value) {
  749. if (!arguments.length) return createNodes;
  750. createNodes = value;
  751. return fn;
  752. };
  753. fn.createClusters = function(value) {
  754. if (!arguments.length) return createClusters;
  755. createClusters = value;
  756. return fn;
  757. };
  758. fn.createEdgeLabels = function(value) {
  759. if (!arguments.length) return createEdgeLabels;
  760. createEdgeLabels = value;
  761. return fn;
  762. };
  763. fn.createEdgePaths = function(value) {
  764. if (!arguments.length) return createEdgePaths;
  765. createEdgePaths = value;
  766. return fn;
  767. };
  768. fn.shapes = function(value) {
  769. if (!arguments.length) return shapes;
  770. shapes = value;
  771. return fn;
  772. };
  773. fn.arrows = function(value) {
  774. if (!arguments.length) return arrows;
  775. arrows = value;
  776. return fn;
  777. };
  778. return fn;
  779. }
  780. var NODE_DEFAULT_ATTRS = {
  781. paddingLeft: 10,
  782. paddingRight: 10,
  783. paddingTop: 10,
  784. paddingBottom: 10,
  785. rx: 0,
  786. ry: 0,
  787. shape: "rect"
  788. };
  789. var EDGE_DEFAULT_ATTRS = {
  790. arrowhead: "normal",
  791. curve: d3.curveLinear
  792. };
  793. function preProcessGraph(g) {
  794. g.nodes().forEach(function(v) {
  795. var node = g.node(v);
  796. if (!_.has(node, "label") && !g.children(v).length) { node.label = v; }
  797. if (_.has(node, "paddingX")) {
  798. _.defaults(node, {
  799. paddingLeft: node.paddingX,
  800. paddingRight: node.paddingX
  801. });
  802. }
  803. if (_.has(node, "paddingY")) {
  804. _.defaults(node, {
  805. paddingTop: node.paddingY,
  806. paddingBottom: node.paddingY
  807. });
  808. }
  809. if (_.has(node, "padding")) {
  810. _.defaults(node, {
  811. paddingLeft: node.padding,
  812. paddingRight: node.padding,
  813. paddingTop: node.padding,
  814. paddingBottom: node.padding
  815. });
  816. }
  817. _.defaults(node, NODE_DEFAULT_ATTRS);
  818. _.each(["paddingLeft", "paddingRight", "paddingTop", "paddingBottom"], function(k) {
  819. node[k] = Number(node[k]);
  820. });
  821. // Save dimensions for restore during post-processing
  822. if (_.has(node, "width")) { node._prevWidth = node.width; }
  823. if (_.has(node, "height")) { node._prevHeight = node.height; }
  824. });
  825. g.edges().forEach(function(e) {
  826. var edge = g.edge(e);
  827. if (!_.has(edge, "label")) { edge.label = ""; }
  828. _.defaults(edge, EDGE_DEFAULT_ATTRS);
  829. });
  830. }
  831. function postProcessGraph(g) {
  832. _.each(g.nodes(), function(v) {
  833. var node = g.node(v);
  834. // Restore original dimensions
  835. if (_.has(node, "_prevWidth")) {
  836. node.width = node._prevWidth;
  837. } else {
  838. delete node.width;
  839. }
  840. if (_.has(node, "_prevHeight")) {
  841. node.height = node._prevHeight;
  842. } else {
  843. delete node.height;
  844. }
  845. delete node._prevWidth;
  846. delete node._prevHeight;
  847. });
  848. }
  849. function createOrSelectGroup(root, name) {
  850. var selection = root.select("g." + name);
  851. if (selection.empty()) {
  852. selection = root.append("g").attr("class", name);
  853. }
  854. return selection;
  855. }
  856. },{"./arrows":2,"./create-clusters":3,"./create-edge-labels":4,"./create-edge-paths":5,"./create-nodes":6,"./d3":7,"./dagre":8,"./lodash":21,"./position-clusters":22,"./position-edge-labels":23,"./position-nodes":24,"./shapes":26}],26:[function(require,module,exports){
  857. "use strict";
  858. var intersectRect = require("./intersect/intersect-rect"),
  859. intersectEllipse = require("./intersect/intersect-ellipse"),
  860. intersectCircle = require("./intersect/intersect-circle"),
  861. intersectPolygon = require("./intersect/intersect-polygon");
  862. module.exports = {
  863. rect: rect,
  864. ellipse: ellipse,
  865. circle: circle,
  866. diamond: diamond
  867. };
  868. function rect(parent, bbox, node) {
  869. var shapeSvg = parent.insert("rect", ":first-child")
  870. .attr("rx", node.rx)
  871. .attr("ry", node.ry)
  872. .attr("x", -bbox.width / 2)
  873. .attr("y", -bbox.height / 2)
  874. .attr("width", bbox.width)
  875. .attr("height", bbox.height);
  876. node.intersect = function(point) {
  877. return intersectRect(node, point);
  878. };
  879. return shapeSvg;
  880. }
  881. function ellipse(parent, bbox, node) {
  882. var rx = bbox.width / 2,
  883. ry = bbox.height / 2,
  884. shapeSvg = parent.insert("ellipse", ":first-child")
  885. .attr("x", -bbox.width / 2)
  886. .attr("y", -bbox.height / 2)
  887. .attr("rx", rx)
  888. .attr("ry", ry);
  889. node.intersect = function(point) {
  890. return intersectEllipse(node, rx, ry, point);
  891. };
  892. return shapeSvg;
  893. }
  894. function circle(parent, bbox, node) {
  895. var r = Math.max(bbox.width, bbox.height) / 2,
  896. shapeSvg = parent.insert("circle", ":first-child")
  897. .attr("x", -bbox.width / 2)
  898. .attr("y", -bbox.height / 2)
  899. .attr("r", r);
  900. node.intersect = function(point) {
  901. return intersectCircle(node, r, point);
  902. };
  903. return shapeSvg;
  904. }
  905. // Circumscribe an ellipse for the bounding box with a diamond shape. I derived
  906. // the function to calculate the diamond shape from:
  907. // http://mathforum.org/kb/message.jspa?messageID=3750236
  908. function diamond(parent, bbox, node) {
  909. var w = (bbox.width * Math.SQRT2) / 2,
  910. h = (bbox.height * Math.SQRT2) / 2,
  911. points = [
  912. { x: 0, y: -h },
  913. { x: -w, y: 0 },
  914. { x: 0, y: h },
  915. { x: w, y: 0 }
  916. ],
  917. shapeSvg = parent.insert("polygon", ":first-child")
  918. .attr("points", points.map(function(p) { return p.x + "," + p.y; }).join(" "));
  919. node.intersect = function(p) {
  920. return intersectPolygon(node, points, p);
  921. };
  922. return shapeSvg;
  923. }
  924. },{"./intersect/intersect-circle":11,"./intersect/intersect-ellipse":12,"./intersect/intersect-polygon":15,"./intersect/intersect-rect":16}],27:[function(require,module,exports){
  925. var _ = require("./lodash");
  926. // Public utility functions
  927. module.exports = {
  928. isSubgraph: isSubgraph,
  929. edgeToId: edgeToId,
  930. applyStyle: applyStyle,
  931. applyClass: applyClass,
  932. applyTransition: applyTransition
  933. };
  934. /*
  935. * Returns true if the specified node in the graph is a subgraph node. A
  936. * subgraph node is one that contains other nodes.
  937. */
  938. function isSubgraph(g, v) {
  939. return !!g.children(v).length;
  940. }
  941. function edgeToId(e) {
  942. return escapeId(e.v) + ":" + escapeId(e.w) + ":" + escapeId(e.name);
  943. }
  944. var ID_DELIM = /:/g;
  945. function escapeId(str) {
  946. return str ? String(str).replace(ID_DELIM, "\\:") : "";
  947. }
  948. function applyStyle(dom, styleFn) {
  949. if (styleFn) {
  950. dom.attr("style", styleFn);
  951. }
  952. }
  953. function applyClass(dom, classFn, otherClasses) {
  954. if (classFn) {
  955. dom
  956. .attr("class", classFn)
  957. .attr("class", otherClasses + " " + dom.attr("class"));
  958. }
  959. }
  960. function applyTransition(selection, g) {
  961. var graph = g.graph();
  962. if (_.isPlainObject(graph)) {
  963. var transition = graph.transition;
  964. if (_.isFunction(transition)) {
  965. return transition(selection);
  966. }
  967. }
  968. return selection;
  969. }
  970. },{"./lodash":21}],28:[function(require,module,exports){
  971. module.exports = "0.6.1";
  972. },{}],29:[function(require,module,exports){
  973. },{}],30:[function(require,module,exports){
  974. arguments[4][29][0].apply(exports,arguments)
  975. },{"dup":29}],31:[function(require,module,exports){
  976. 'use strict'
  977. exports.byteLength = byteLength
  978. exports.toByteArray = toByteArray
  979. exports.fromByteArray = fromByteArray
  980. var lookup = []
  981. var revLookup = []
  982. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  983. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  984. for (var i = 0, len = code.length; i < len; ++i) {
  985. lookup[i] = code[i]
  986. revLookup[code.charCodeAt(i)] = i
  987. }
  988. revLookup['-'.charCodeAt(0)] = 62
  989. revLookup['_'.charCodeAt(0)] = 63
  990. function placeHoldersCount (b64) {
  991. var len = b64.length
  992. if (len % 4 > 0) {
  993. throw new Error('Invalid string. Length must be a multiple of 4')
  994. }
  995. // the number of equal signs (place holders)
  996. // if there are two placeholders, than the two characters before it
  997. // represent one byte
  998. // if there is only one, then the three characters before it represent 2 bytes
  999. // this is just a cheap hack to not do indexOf twice
  1000. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  1001. }
  1002. function byteLength (b64) {
  1003. // base64 is 4/3 + up to two characters of the original data
  1004. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  1005. }
  1006. function toByteArray (b64) {
  1007. var i, l, tmp, placeHolders, arr
  1008. var len = b64.length
  1009. placeHolders = placeHoldersCount(b64)
  1010. arr = new Arr((len * 3 / 4) - placeHolders)
  1011. // if there are placeholders, only get up to the last complete 4 chars
  1012. l = placeHolders > 0 ? len - 4 : len
  1013. var L = 0
  1014. for (i = 0; i < l; i += 4) {
  1015. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  1016. arr[L++] = (tmp >> 16) & 0xFF
  1017. arr[L++] = (tmp >> 8) & 0xFF
  1018. arr[L++] = tmp & 0xFF
  1019. }
  1020. if (placeHolders === 2) {
  1021. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  1022. arr[L++] = tmp & 0xFF
  1023. } else if (placeHolders === 1) {
  1024. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  1025. arr[L++] = (tmp >> 8) & 0xFF
  1026. arr[L++] = tmp & 0xFF
  1027. }
  1028. return arr
  1029. }
  1030. function tripletToBase64 (num) {
  1031. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  1032. }
  1033. function encodeChunk (uint8, start, end) {
  1034. var tmp
  1035. var output = []
  1036. for (var i = start; i < end; i += 3) {
  1037. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  1038. output.push(tripletToBase64(tmp))
  1039. }
  1040. return output.join('')
  1041. }
  1042. function fromByteArray (uint8) {
  1043. var tmp
  1044. var len = uint8.length
  1045. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  1046. var output = ''
  1047. var parts = []
  1048. var maxChunkLength = 16383 // must be multiple of 3
  1049. // go through the array every three bytes, we'll deal with trailing stuff later
  1050. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  1051. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  1052. }
  1053. // pad the end with zeros, but make sure to not forget the extra bytes
  1054. if (extraBytes === 1) {
  1055. tmp = uint8[len - 1]
  1056. output += lookup[tmp >> 2]
  1057. output += lookup[(tmp << 4) & 0x3F]
  1058. output += '=='
  1059. } else if (extraBytes === 2) {
  1060. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  1061. output += lookup[tmp >> 10]
  1062. output += lookup[(tmp >> 4) & 0x3F]
  1063. output += lookup[(tmp << 2) & 0x3F]
  1064. output += '='
  1065. }
  1066. parts.push(output)
  1067. return parts.join('')
  1068. }
  1069. },{}],32:[function(require,module,exports){
  1070. /*!
  1071. * The buffer module from node.js, for the browser.
  1072. *
  1073. * @author Feross Aboukhadijeh <https://feross.org>
  1074. * @license MIT
  1075. */
  1076. /* eslint-disable no-proto */
  1077. 'use strict'
  1078. var base64 = require('base64-js')
  1079. var ieee754 = require('ieee754')
  1080. exports.Buffer = Buffer
  1081. exports.SlowBuffer = SlowBuffer
  1082. exports.INSPECT_MAX_BYTES = 50
  1083. var K_MAX_LENGTH = 0x7fffffff
  1084. exports.kMaxLength = K_MAX_LENGTH
  1085. /**
  1086. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  1087. * === true Use Uint8Array implementation (fastest)
  1088. * === false Print warning and recommend using `buffer` v4.x which has an Object
  1089. * implementation (most compatible, even IE6)
  1090. *
  1091. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  1092. * Opera 11.6+, iOS 4.2+.
  1093. *
  1094. * We report that the browser does not support typed arrays if the are not subclassable
  1095. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  1096. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  1097. * for __proto__ and has a buggy typed array implementation.
  1098. */
  1099. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  1100. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  1101. typeof console.error === 'function') {
  1102. console.error(
  1103. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  1104. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  1105. )
  1106. }
  1107. function typedArraySupport () {
  1108. // Can typed array instances can be augmented?
  1109. try {
  1110. var arr = new Uint8Array(1)
  1111. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  1112. return arr.foo() === 42
  1113. } catch (e) {
  1114. return false
  1115. }
  1116. }
  1117. function createBuffer (length) {
  1118. if (length > K_MAX_LENGTH) {
  1119. throw new RangeError('Invalid typed array length')
  1120. }
  1121. // Return an augmented `Uint8Array` instance
  1122. var buf = new Uint8Array(length)
  1123. buf.__proto__ = Buffer.prototype
  1124. return buf
  1125. }
  1126. /**
  1127. * The Buffer constructor returns instances of `Uint8Array` that have their
  1128. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  1129. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  1130. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  1131. * returns a single octet.
  1132. *
  1133. * The `Uint8Array` prototype remains unmodified.
  1134. */
  1135. function Buffer (arg, encodingOrOffset, length) {
  1136. // Common case.
  1137. if (typeof arg === 'number') {
  1138. if (typeof encodingOrOffset === 'string') {
  1139. throw new Error(
  1140. 'If encoding is specified then the first argument must be a string'
  1141. )
  1142. }
  1143. return allocUnsafe(arg)
  1144. }
  1145. return from(arg, encodingOrOffset, length)
  1146. }
  1147. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  1148. if (typeof Symbol !== 'undefined' && Symbol.species &&
  1149. Buffer[Symbol.species] === Buffer) {
  1150. Object.defineProperty(Buffer, Symbol.species, {
  1151. value: null,
  1152. configurable: true,
  1153. enumerable: false,
  1154. writable: false
  1155. })
  1156. }
  1157. Buffer.poolSize = 8192 // not used by this implementation
  1158. function from (value, encodingOrOffset, length) {
  1159. if (typeof value === 'number') {
  1160. throw new TypeError('"value" argument must not be a number')
  1161. }
  1162. if (isArrayBuffer(value)) {
  1163. return fromArrayBuffer(value, encodingOrOffset, length)
  1164. }
  1165. if (typeof value === 'string') {
  1166. return fromString(value, encodingOrOffset)
  1167. }
  1168. return fromObject(value)
  1169. }
  1170. /**
  1171. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  1172. * if value is a number.
  1173. * Buffer.from(str[, encoding])
  1174. * Buffer.from(array)
  1175. * Buffer.from(buffer)
  1176. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  1177. **/
  1178. Buffer.from = function (value, encodingOrOffset, length) {
  1179. return from(value, encodingOrOffset, length)
  1180. }
  1181. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  1182. // https://github.com/feross/buffer/pull/148
  1183. Buffer.prototype.__proto__ = Uint8Array.prototype
  1184. Buffer.__proto__ = Uint8Array
  1185. function assertSize (size) {
  1186. if (typeof size !== 'number') {
  1187. throw new TypeError('"size" argument must be a number')
  1188. } else if (size < 0) {
  1189. throw new RangeError('"size" argument must not be negative')
  1190. }
  1191. }
  1192. function alloc (size, fill, encoding) {
  1193. assertSize(size)
  1194. if (size <= 0) {
  1195. return createBuffer(size)
  1196. }
  1197. if (fill !== undefined) {
  1198. // Only pay attention to encoding if it's a string. This
  1199. // prevents accidentally sending in a number that would
  1200. // be interpretted as a start offset.
  1201. return typeof encoding === 'string'
  1202. ? createBuffer(size).fill(fill, encoding)
  1203. : createBuffer(size).fill(fill)
  1204. }
  1205. return createBuffer(size)
  1206. }
  1207. /**
  1208. * Creates a new filled Buffer instance.
  1209. * alloc(size[, fill[, encoding]])
  1210. **/
  1211. Buffer.alloc = function (size, fill, encoding) {
  1212. return alloc(size, fill, encoding)
  1213. }
  1214. function allocUnsafe (size) {
  1215. assertSize(size)
  1216. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  1217. }
  1218. /**
  1219. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  1220. * */
  1221. Buffer.allocUnsafe = function (size) {
  1222. return allocUnsafe(size)
  1223. }
  1224. /**
  1225. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  1226. */
  1227. Buffer.allocUnsafeSlow = function (size) {
  1228. return allocUnsafe(size)
  1229. }
  1230. function fromString (string, encoding) {
  1231. if (typeof encoding !== 'string' || encoding === '') {
  1232. encoding = 'utf8'
  1233. }
  1234. if (!Buffer.isEncoding(encoding)) {
  1235. throw new TypeError('"encoding" must be a valid string encoding')
  1236. }
  1237. var length = byteLength(string, encoding) | 0
  1238. var buf = createBuffer(length)
  1239. var actual = buf.write(string, encoding)
  1240. if (actual !== length) {
  1241. // Writing a hex string, for example, that contains invalid characters will
  1242. // cause everything after the first invalid character to be ignored. (e.g.
  1243. // 'abxxcd' will be treated as 'ab')
  1244. buf = buf.slice(0, actual)
  1245. }
  1246. return buf
  1247. }
  1248. function fromArrayLike (array) {
  1249. var length = array.length < 0 ? 0 : checked(array.length) | 0
  1250. var buf = createBuffer(length)
  1251. for (var i = 0; i < length; i += 1) {
  1252. buf[i] = array[i] & 255
  1253. }
  1254. return buf
  1255. }
  1256. function fromArrayBuffer (array, byteOffset, length) {
  1257. if (byteOffset < 0 || array.byteLength < byteOffset) {
  1258. throw new RangeError('\'offset\' is out of bounds')
  1259. }
  1260. if (array.byteLength < byteOffset + (length || 0)) {
  1261. throw new RangeError('\'length\' is out of bounds')
  1262. }
  1263. var buf
  1264. if (byteOffset === undefined && length === undefined) {
  1265. buf = new Uint8Array(array)
  1266. } else if (length === undefined) {
  1267. buf = new Uint8Array(array, byteOffset)
  1268. } else {
  1269. buf = new Uint8Array(array, byteOffset, length)
  1270. }
  1271. // Return an augmented `Uint8Array` instance
  1272. buf.__proto__ = Buffer.prototype
  1273. return buf
  1274. }
  1275. function fromObject (obj) {
  1276. if (Buffer.isBuffer(obj)) {
  1277. var len = checked(obj.length) | 0
  1278. var buf = createBuffer(len)
  1279. if (buf.length === 0) {
  1280. return buf
  1281. }
  1282. obj.copy(buf, 0, 0, len)
  1283. return buf
  1284. }
  1285. if (obj) {
  1286. if (isArrayBufferView(obj) || 'length' in obj) {
  1287. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  1288. return createBuffer(0)
  1289. }
  1290. return fromArrayLike(obj)
  1291. }
  1292. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  1293. return fromArrayLike(obj.data)
  1294. }
  1295. }
  1296. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  1297. }
  1298. function checked (length) {
  1299. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  1300. // length is NaN (which is otherwise coerced to zero.)
  1301. if (length >= K_MAX_LENGTH) {
  1302. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  1303. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  1304. }
  1305. return length | 0
  1306. }
  1307. function SlowBuffer (length) {
  1308. if (+length != length) { // eslint-disable-line eqeqeq
  1309. length = 0
  1310. }
  1311. return Buffer.alloc(+length)
  1312. }
  1313. Buffer.isBuffer = function isBuffer (b) {
  1314. return b != null && b._isBuffer === true
  1315. }
  1316. Buffer.compare = function compare (a, b) {
  1317. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  1318. throw new TypeError('Arguments must be Buffers')
  1319. }
  1320. if (a === b) return 0
  1321. var x = a.length
  1322. var y = b.length
  1323. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  1324. if (a[i] !== b[i]) {
  1325. x = a[i]
  1326. y = b[i]
  1327. break
  1328. }
  1329. }
  1330. if (x < y) return -1
  1331. if (y < x) return 1
  1332. return 0
  1333. }
  1334. Buffer.isEncoding = function isEncoding (encoding) {
  1335. switch (String(encoding).toLowerCase()) {
  1336. case 'hex':
  1337. case 'utf8':
  1338. case 'utf-8':
  1339. case 'ascii':
  1340. case 'latin1':
  1341. case 'binary':
  1342. case 'base64':
  1343. case 'ucs2':
  1344. case 'ucs-2':
  1345. case 'utf16le':
  1346. case 'utf-16le':
  1347. return true
  1348. default:
  1349. return false
  1350. }
  1351. }
  1352. Buffer.concat = function concat (list, length) {
  1353. if (!Array.isArray(list)) {
  1354. throw new TypeError('"list" argument must be an Array of Buffers')
  1355. }
  1356. if (list.length === 0) {
  1357. return Buffer.alloc(0)
  1358. }
  1359. var i
  1360. if (length === undefined) {
  1361. length = 0
  1362. for (i = 0; i < list.length; ++i) {
  1363. length += list[i].length
  1364. }
  1365. }
  1366. var buffer = Buffer.allocUnsafe(length)
  1367. var pos = 0
  1368. for (i = 0; i < list.length; ++i) {
  1369. var buf = list[i]
  1370. if (!Buffer.isBuffer(buf)) {
  1371. throw new TypeError('"list" argument must be an Array of Buffers')
  1372. }
  1373. buf.copy(buffer, pos)
  1374. pos += buf.length
  1375. }
  1376. return buffer
  1377. }
  1378. function byteLength (string, encoding) {
  1379. if (Buffer.isBuffer(string)) {
  1380. return string.length
  1381. }
  1382. if (isArrayBufferView(string) || isArrayBuffer(string)) {
  1383. return string.byteLength
  1384. }
  1385. if (typeof string !== 'string') {
  1386. string = '' + string
  1387. }
  1388. var len = string.length
  1389. if (len === 0) return 0
  1390. // Use a for loop to avoid recursion
  1391. var loweredCase = false
  1392. for (;;) {
  1393. switch (encoding) {
  1394. case 'ascii':
  1395. case 'latin1':
  1396. case 'binary':
  1397. return len
  1398. case 'utf8':
  1399. case 'utf-8':
  1400. case undefined:
  1401. return utf8ToBytes(string).length
  1402. case 'ucs2':
  1403. case 'ucs-2':
  1404. case 'utf16le':
  1405. case 'utf-16le':
  1406. return len * 2
  1407. case 'hex':
  1408. return len >>> 1
  1409. case 'base64':
  1410. return base64ToBytes(string).length
  1411. default:
  1412. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  1413. encoding = ('' + encoding).toLowerCase()
  1414. loweredCase = true
  1415. }
  1416. }
  1417. }
  1418. Buffer.byteLength = byteLength
  1419. function slowToString (encoding, start, end) {
  1420. var loweredCase = false
  1421. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  1422. // property of a typed array.
  1423. // This behaves neither like String nor Uint8Array in that we set start/end
  1424. // to their upper/lower bounds if the value passed is out of range.
  1425. // undefined is handled specially as per ECMA-262 6th Edition,
  1426. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  1427. if (start === undefined || start < 0) {
  1428. start = 0
  1429. }
  1430. // Return early if start > this.length. Done here to prevent potential uint32
  1431. // coercion fail below.
  1432. if (start > this.length) {
  1433. return ''
  1434. }
  1435. if (end === undefined || end > this.length) {
  1436. end = this.length
  1437. }
  1438. if (end <= 0) {
  1439. return ''
  1440. }
  1441. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  1442. end >>>= 0
  1443. start >>>= 0
  1444. if (end <= start) {
  1445. return ''
  1446. }
  1447. if (!encoding) encoding = 'utf8'
  1448. while (true) {
  1449. switch (encoding) {
  1450. case 'hex':
  1451. return hexSlice(this, start, end)
  1452. case 'utf8':
  1453. case 'utf-8':
  1454. return utf8Slice(this, start, end)
  1455. case 'ascii':
  1456. return asciiSlice(this, start, end)
  1457. case 'latin1':
  1458. case 'binary':
  1459. return latin1Slice(this, start, end)
  1460. case 'base64':
  1461. return base64Slice(this, start, end)
  1462. case 'ucs2':
  1463. case 'ucs-2':
  1464. case 'utf16le':
  1465. case 'utf-16le':
  1466. return utf16leSlice(this, start, end)
  1467. default:
  1468. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1469. encoding = (encoding + '').toLowerCase()
  1470. loweredCase = true
  1471. }
  1472. }
  1473. }
  1474. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  1475. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  1476. // reliably in a browserify context because there could be multiple different
  1477. // copies of the 'buffer' package in use. This method works even for Buffer
  1478. // instances that were created from another copy of the `buffer` package.
  1479. // See: https://github.com/feross/buffer/issues/154
  1480. Buffer.prototype._isBuffer = true
  1481. function swap (b, n, m) {
  1482. var i = b[n]
  1483. b[n] = b[m]
  1484. b[m] = i
  1485. }
  1486. Buffer.prototype.swap16 = function swap16 () {
  1487. var len = this.length
  1488. if (len % 2 !== 0) {
  1489. throw new RangeError('Buffer size must be a multiple of 16-bits')
  1490. }
  1491. for (var i = 0; i < len; i += 2) {
  1492. swap(this, i, i + 1)
  1493. }
  1494. return this
  1495. }
  1496. Buffer.prototype.swap32 = function swap32 () {
  1497. var len = this.length
  1498. if (len % 4 !== 0) {
  1499. throw new RangeError('Buffer size must be a multiple of 32-bits')
  1500. }
  1501. for (var i = 0; i < len; i += 4) {
  1502. swap(this, i, i + 3)
  1503. swap(this, i + 1, i + 2)
  1504. }
  1505. return this
  1506. }
  1507. Buffer.prototype.swap64 = function swap64 () {
  1508. var len = this.length
  1509. if (len % 8 !== 0) {
  1510. throw new RangeError('Buffer size must be a multiple of 64-bits')
  1511. }
  1512. for (var i = 0; i < len; i += 8) {
  1513. swap(this, i, i + 7)
  1514. swap(this, i + 1, i + 6)
  1515. swap(this, i + 2, i + 5)
  1516. swap(this, i + 3, i + 4)
  1517. }
  1518. return this
  1519. }
  1520. Buffer.prototype.toString = function toString () {
  1521. var length = this.length
  1522. if (length === 0) return ''
  1523. if (arguments.length === 0) return utf8Slice(this, 0, length)
  1524. return slowToString.apply(this, arguments)
  1525. }
  1526. Buffer.prototype.equals = function equals (b) {
  1527. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1528. if (this === b) return true
  1529. return Buffer.compare(this, b) === 0
  1530. }
  1531. Buffer.prototype.inspect = function inspect () {
  1532. var str = ''
  1533. var max = exports.INSPECT_MAX_BYTES
  1534. if (this.length > 0) {
  1535. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  1536. if (this.length > max) str += ' ... '
  1537. }
  1538. return '<Buffer ' + str + '>'
  1539. }
  1540. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  1541. if (!Buffer.isBuffer(target)) {
  1542. throw new TypeError('Argument must be a Buffer')
  1543. }
  1544. if (start === undefined) {
  1545. start = 0
  1546. }
  1547. if (end === undefined) {
  1548. end = target ? target.length : 0
  1549. }
  1550. if (thisStart === undefined) {
  1551. thisStart = 0
  1552. }
  1553. if (thisEnd === undefined) {
  1554. thisEnd = this.length
  1555. }
  1556. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  1557. throw new RangeError('out of range index')
  1558. }
  1559. if (thisStart >= thisEnd && start >= end) {
  1560. return 0
  1561. }
  1562. if (thisStart >= thisEnd) {
  1563. return -1
  1564. }
  1565. if (start >= end) {
  1566. return 1
  1567. }
  1568. start >>>= 0
  1569. end >>>= 0
  1570. thisStart >>>= 0
  1571. thisEnd >>>= 0
  1572. if (this === target) return 0
  1573. var x = thisEnd - thisStart
  1574. var y = end - start
  1575. var len = Math.min(x, y)
  1576. var thisCopy = this.slice(thisStart, thisEnd)
  1577. var targetCopy = target.slice(start, end)
  1578. for (var i = 0; i < len; ++i) {
  1579. if (thisCopy[i] !== targetCopy[i]) {
  1580. x = thisCopy[i]
  1581. y = targetCopy[i]
  1582. break
  1583. }
  1584. }
  1585. if (x < y) return -1
  1586. if (y < x) return 1
  1587. return 0
  1588. }
  1589. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  1590. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  1591. //
  1592. // Arguments:
  1593. // - buffer - a Buffer to search
  1594. // - val - a string, Buffer, or number
  1595. // - byteOffset - an index into `buffer`; will be clamped to an int32
  1596. // - encoding - an optional encoding, relevant is val is a string
  1597. // - dir - true for indexOf, false for lastIndexOf
  1598. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  1599. // Empty buffer means no match
  1600. if (buffer.length === 0) return -1
  1601. // Normalize byteOffset
  1602. if (typeof byteOffset === 'string') {
  1603. encoding = byteOffset
  1604. byteOffset = 0
  1605. } else if (byteOffset > 0x7fffffff) {
  1606. byteOffset = 0x7fffffff
  1607. } else if (byteOffset < -0x80000000) {
  1608. byteOffset = -0x80000000
  1609. }
  1610. byteOffset = +byteOffset // Coerce to Number.
  1611. if (numberIsNaN(byteOffset)) {
  1612. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  1613. byteOffset = dir ? 0 : (buffer.length - 1)
  1614. }
  1615. // Normalize byteOffset: negative offsets start from the end of the buffer
  1616. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  1617. if (byteOffset >= buffer.length) {
  1618. if (dir) return -1
  1619. else byteOffset = buffer.length - 1
  1620. } else if (byteOffset < 0) {
  1621. if (dir) byteOffset = 0
  1622. else return -1
  1623. }
  1624. // Normalize val
  1625. if (typeof val === 'string') {
  1626. val = Buffer.from(val, encoding)
  1627. }
  1628. // Finally, search either indexOf (if dir is true) or lastIndexOf
  1629. if (Buffer.isBuffer(val)) {
  1630. // Special case: looking for empty string/buffer always fails
  1631. if (val.length === 0) {
  1632. return -1
  1633. }
  1634. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  1635. } else if (typeof val === 'number') {
  1636. val = val & 0xFF // Search for a byte value [0-255]
  1637. if (typeof Uint8Array.prototype.indexOf === 'function') {
  1638. if (dir) {
  1639. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  1640. } else {
  1641. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  1642. }
  1643. }
  1644. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  1645. }
  1646. throw new TypeError('val must be string, number or Buffer')
  1647. }
  1648. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  1649. var indexSize = 1
  1650. var arrLength = arr.length
  1651. var valLength = val.length
  1652. if (encoding !== undefined) {
  1653. encoding = String(encoding).toLowerCase()
  1654. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  1655. encoding === 'utf16le' || encoding === 'utf-16le') {
  1656. if (arr.length < 2 || val.length < 2) {
  1657. return -1
  1658. }
  1659. indexSize = 2
  1660. arrLength /= 2
  1661. valLength /= 2
  1662. byteOffset /= 2
  1663. }
  1664. }
  1665. function read (buf, i) {
  1666. if (indexSize === 1) {
  1667. return buf[i]
  1668. } else {
  1669. return buf.readUInt16BE(i * indexSize)
  1670. }
  1671. }
  1672. var i
  1673. if (dir) {
  1674. var foundIndex = -1
  1675. for (i = byteOffset; i < arrLength; i++) {
  1676. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  1677. if (foundIndex === -1) foundIndex = i
  1678. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  1679. } else {
  1680. if (foundIndex !== -1) i -= i - foundIndex
  1681. foundIndex = -1
  1682. }
  1683. }
  1684. } else {
  1685. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  1686. for (i = byteOffset; i >= 0; i--) {
  1687. var found = true
  1688. for (var j = 0; j < valLength; j++) {
  1689. if (read(arr, i + j) !== read(val, j)) {
  1690. found = false
  1691. break
  1692. }
  1693. }
  1694. if (found) return i
  1695. }
  1696. }
  1697. return -1
  1698. }
  1699. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  1700. return this.indexOf(val, byteOffset, encoding) !== -1
  1701. }
  1702. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  1703. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  1704. }
  1705. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  1706. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  1707. }
  1708. function hexWrite (buf, string, offset, length) {
  1709. offset = Number(offset) || 0
  1710. var remaining = buf.length - offset
  1711. if (!length) {
  1712. length = remaining
  1713. } else {
  1714. length = Number(length)
  1715. if (length > remaining) {
  1716. length = remaining
  1717. }
  1718. }
  1719. // must be an even number of digits
  1720. var strLen = string.length
  1721. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  1722. if (length > strLen / 2) {
  1723. length = strLen / 2
  1724. }
  1725. for (var i = 0; i < length; ++i) {
  1726. var parsed = parseInt(string.substr(i * 2, 2), 16)
  1727. if (numberIsNaN(parsed)) return i
  1728. buf[offset + i] = parsed
  1729. }
  1730. return i
  1731. }
  1732. function utf8Write (buf, string, offset, length) {
  1733. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  1734. }
  1735. function asciiWrite (buf, string, offset, length) {
  1736. return blitBuffer(asciiToBytes(string), buf, offset, length)
  1737. }
  1738. function latin1Write (buf, string, offset, length) {
  1739. return asciiWrite(buf, string, offset, length)
  1740. }
  1741. function base64Write (buf, string, offset, length) {
  1742. return blitBuffer(base64ToBytes(string), buf, offset, length)
  1743. }
  1744. function ucs2Write (buf, string, offset, length) {
  1745. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  1746. }
  1747. Buffer.prototype.write = function write (string, offset, length, encoding) {
  1748. // Buffer#write(string)
  1749. if (offset === undefined) {
  1750. encoding = 'utf8'
  1751. length = this.length
  1752. offset = 0
  1753. // Buffer#write(string, encoding)
  1754. } else if (length === undefined && typeof offset === 'string') {
  1755. encoding = offset
  1756. length = this.length
  1757. offset = 0
  1758. // Buffer#write(string, offset[, length][, encoding])
  1759. } else if (isFinite(offset)) {
  1760. offset = offset >>> 0
  1761. if (isFinite(length)) {
  1762. length = length >>> 0
  1763. if (encoding === undefined) encoding = 'utf8'
  1764. } else {
  1765. encoding = length
  1766. length = undefined
  1767. }
  1768. } else {
  1769. throw new Error(
  1770. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  1771. )
  1772. }
  1773. var remaining = this.length - offset
  1774. if (length === undefined || length > remaining) length = remaining
  1775. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  1776. throw new RangeError('Attempt to write outside buffer bounds')
  1777. }
  1778. if (!encoding) encoding = 'utf8'
  1779. var loweredCase = false
  1780. for (;;) {
  1781. switch (encoding) {
  1782. case 'hex':
  1783. return hexWrite(this, string, offset, length)
  1784. case 'utf8':
  1785. case 'utf-8':
  1786. return utf8Write(this, string, offset, length)
  1787. case 'ascii':
  1788. return asciiWrite(this, string, offset, length)
  1789. case 'latin1':
  1790. case 'binary':
  1791. return latin1Write(this, string, offset, length)
  1792. case 'base64':
  1793. // Warning: maxLength not taken into account in base64Write
  1794. return base64Write(this, string, offset, length)
  1795. case 'ucs2':
  1796. case 'ucs-2':
  1797. case 'utf16le':
  1798. case 'utf-16le':
  1799. return ucs2Write(this, string, offset, length)
  1800. default:
  1801. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1802. encoding = ('' + encoding).toLowerCase()
  1803. loweredCase = true
  1804. }
  1805. }
  1806. }
  1807. Buffer.prototype.toJSON = function toJSON () {
  1808. return {
  1809. type: 'Buffer',
  1810. data: Array.prototype.slice.call(this._arr || this, 0)
  1811. }
  1812. }
  1813. function base64Slice (buf, start, end) {
  1814. if (start === 0 && end === buf.length) {
  1815. return base64.fromByteArray(buf)
  1816. } else {
  1817. return base64.fromByteArray(buf.slice(start, end))
  1818. }
  1819. }
  1820. function utf8Slice (buf, start, end) {
  1821. end = Math.min(buf.length, end)
  1822. var res = []
  1823. var i = start
  1824. while (i < end) {
  1825. var firstByte = buf[i]
  1826. var codePoint = null
  1827. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1828. : (firstByte > 0xDF) ? 3
  1829. : (firstByte > 0xBF) ? 2
  1830. : 1
  1831. if (i + bytesPerSequence <= end) {
  1832. var secondByte, thirdByte, fourthByte, tempCodePoint
  1833. switch (bytesPerSequence) {
  1834. case 1:
  1835. if (firstByte < 0x80) {
  1836. codePoint = firstByte
  1837. }
  1838. break
  1839. case 2:
  1840. secondByte = buf[i + 1]
  1841. if ((secondByte & 0xC0) === 0x80) {
  1842. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1843. if (tempCodePoint > 0x7F) {
  1844. codePoint = tempCodePoint
  1845. }
  1846. }
  1847. break
  1848. case 3:
  1849. secondByte = buf[i + 1]
  1850. thirdByte = buf[i + 2]
  1851. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1852. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1853. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1854. codePoint = tempCodePoint
  1855. }
  1856. }
  1857. break
  1858. case 4:
  1859. secondByte = buf[i + 1]
  1860. thirdByte = buf[i + 2]
  1861. fourthByte = buf[i + 3]
  1862. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1863. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1864. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1865. codePoint = tempCodePoint
  1866. }
  1867. }
  1868. }
  1869. }
  1870. if (codePoint === null) {
  1871. // we did not generate a valid codePoint so insert a
  1872. // replacement char (U+FFFD) and advance only 1 byte
  1873. codePoint = 0xFFFD
  1874. bytesPerSequence = 1
  1875. } else if (codePoint > 0xFFFF) {
  1876. // encode to utf16 (surrogate pair dance)
  1877. codePoint -= 0x10000
  1878. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1879. codePoint = 0xDC00 | codePoint & 0x3FF
  1880. }
  1881. res.push(codePoint)
  1882. i += bytesPerSequence
  1883. }
  1884. return decodeCodePointsArray(res)
  1885. }
  1886. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1887. // the lowest limit is Chrome, with 0x10000 args.
  1888. // We go 1 magnitude less, for safety
  1889. var MAX_ARGUMENTS_LENGTH = 0x1000
  1890. function decodeCodePointsArray (codePoints) {
  1891. var len = codePoints.length
  1892. if (len <= MAX_ARGUMENTS_LENGTH) {
  1893. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1894. }
  1895. // Decode in chunks to avoid "call stack size exceeded".
  1896. var res = ''
  1897. var i = 0
  1898. while (i < len) {
  1899. res += String.fromCharCode.apply(
  1900. String,
  1901. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1902. )
  1903. }
  1904. return res
  1905. }
  1906. function asciiSlice (buf, start, end) {
  1907. var ret = ''
  1908. end = Math.min(buf.length, end)
  1909. for (var i = start; i < end; ++i) {
  1910. ret += String.fromCharCode(buf[i] & 0x7F)
  1911. }
  1912. return ret
  1913. }
  1914. function latin1Slice (buf, start, end) {
  1915. var ret = ''
  1916. end = Math.min(buf.length, end)
  1917. for (var i = start; i < end; ++i) {
  1918. ret += String.fromCharCode(buf[i])
  1919. }
  1920. return ret
  1921. }
  1922. function hexSlice (buf, start, end) {
  1923. var len = buf.length
  1924. if (!start || start < 0) start = 0
  1925. if (!end || end < 0 || end > len) end = len
  1926. var out = ''
  1927. for (var i = start; i < end; ++i) {
  1928. out += toHex(buf[i])
  1929. }
  1930. return out
  1931. }
  1932. function utf16leSlice (buf, start, end) {
  1933. var bytes = buf.slice(start, end)
  1934. var res = ''
  1935. for (var i = 0; i < bytes.length; i += 2) {
  1936. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  1937. }
  1938. return res
  1939. }
  1940. Buffer.prototype.slice = function slice (start, end) {
  1941. var len = this.length
  1942. start = ~~start
  1943. end = end === undefined ? len : ~~end
  1944. if (start < 0) {
  1945. start += len
  1946. if (start < 0) start = 0
  1947. } else if (start > len) {
  1948. start = len
  1949. }
  1950. if (end < 0) {
  1951. end += len
  1952. if (end < 0) end = 0
  1953. } else if (end > len) {
  1954. end = len
  1955. }
  1956. if (end < start) end = start
  1957. var newBuf = this.subarray(start, end)
  1958. // Return an augmented `Uint8Array` instance
  1959. newBuf.__proto__ = Buffer.prototype
  1960. return newBuf
  1961. }
  1962. /*
  1963. * Need to make sure that buffer isn't trying to write out of bounds.
  1964. */
  1965. function checkOffset (offset, ext, length) {
  1966. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1967. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1968. }
  1969. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1970. offset = offset >>> 0
  1971. byteLength = byteLength >>> 0
  1972. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1973. var val = this[offset]
  1974. var mul = 1
  1975. var i = 0
  1976. while (++i < byteLength && (mul *= 0x100)) {
  1977. val += this[offset + i] * mul
  1978. }
  1979. return val
  1980. }
  1981. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1982. offset = offset >>> 0
  1983. byteLength = byteLength >>> 0
  1984. if (!noAssert) {
  1985. checkOffset(offset, byteLength, this.length)
  1986. }
  1987. var val = this[offset + --byteLength]
  1988. var mul = 1
  1989. while (byteLength > 0 && (mul *= 0x100)) {
  1990. val += this[offset + --byteLength] * mul
  1991. }
  1992. return val
  1993. }
  1994. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1995. offset = offset >>> 0
  1996. if (!noAssert) checkOffset(offset, 1, this.length)
  1997. return this[offset]
  1998. }
  1999. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  2000. offset = offset >>> 0
  2001. if (!noAssert) checkOffset(offset, 2, this.length)
  2002. return this[offset] | (this[offset + 1] << 8)
  2003. }
  2004. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  2005. offset = offset >>> 0
  2006. if (!noAssert) checkOffset(offset, 2, this.length)
  2007. return (this[offset] << 8) | this[offset + 1]
  2008. }
  2009. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  2010. offset = offset >>> 0
  2011. if (!noAssert) checkOffset(offset, 4, this.length)
  2012. return ((this[offset]) |
  2013. (this[offset + 1] << 8) |
  2014. (this[offset + 2] << 16)) +
  2015. (this[offset + 3] * 0x1000000)
  2016. }
  2017. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  2018. offset = offset >>> 0
  2019. if (!noAssert) checkOffset(offset, 4, this.length)
  2020. return (this[offset] * 0x1000000) +
  2021. ((this[offset + 1] << 16) |
  2022. (this[offset + 2] << 8) |
  2023. this[offset + 3])
  2024. }
  2025. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  2026. offset = offset >>> 0
  2027. byteLength = byteLength >>> 0
  2028. if (!noAssert) checkOffset(offset, byteLength, this.length)
  2029. var val = this[offset]
  2030. var mul = 1
  2031. var i = 0
  2032. while (++i < byteLength && (mul *= 0x100)) {
  2033. val += this[offset + i] * mul
  2034. }
  2035. mul *= 0x80
  2036. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  2037. return val
  2038. }
  2039. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  2040. offset = offset >>> 0
  2041. byteLength = byteLength >>> 0
  2042. if (!noAssert) checkOffset(offset, byteLength, this.length)
  2043. var i = byteLength
  2044. var mul = 1
  2045. var val = this[offset + --i]
  2046. while (i > 0 && (mul *= 0x100)) {
  2047. val += this[offset + --i] * mul
  2048. }
  2049. mul *= 0x80
  2050. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  2051. return val
  2052. }
  2053. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  2054. offset = offset >>> 0
  2055. if (!noAssert) checkOffset(offset, 1, this.length)
  2056. if (!(this[offset] & 0x80)) return (this[offset])
  2057. return ((0xff - this[offset] + 1) * -1)
  2058. }
  2059. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  2060. offset = offset >>> 0
  2061. if (!noAssert) checkOffset(offset, 2, this.length)
  2062. var val = this[offset] | (this[offset + 1] << 8)
  2063. return (val & 0x8000) ? val | 0xFFFF0000 : val
  2064. }
  2065. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  2066. offset = offset >>> 0
  2067. if (!noAssert) checkOffset(offset, 2, this.length)
  2068. var val = this[offset + 1] | (this[offset] << 8)
  2069. return (val & 0x8000) ? val | 0xFFFF0000 : val
  2070. }
  2071. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  2072. offset = offset >>> 0
  2073. if (!noAssert) checkOffset(offset, 4, this.length)
  2074. return (this[offset]) |
  2075. (this[offset + 1] << 8) |
  2076. (this[offset + 2] << 16) |
  2077. (this[offset + 3] << 24)
  2078. }
  2079. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  2080. offset = offset >>> 0
  2081. if (!noAssert) checkOffset(offset, 4, this.length)
  2082. return (this[offset] << 24) |
  2083. (this[offset + 1] << 16) |
  2084. (this[offset + 2] << 8) |
  2085. (this[offset + 3])
  2086. }
  2087. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  2088. offset = offset >>> 0
  2089. if (!noAssert) checkOffset(offset, 4, this.length)
  2090. return ieee754.read(this, offset, true, 23, 4)
  2091. }
  2092. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  2093. offset = offset >>> 0
  2094. if (!noAssert) checkOffset(offset, 4, this.length)
  2095. return ieee754.read(this, offset, false, 23, 4)
  2096. }
  2097. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  2098. offset = offset >>> 0
  2099. if (!noAssert) checkOffset(offset, 8, this.length)
  2100. return ieee754.read(this, offset, true, 52, 8)
  2101. }
  2102. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  2103. offset = offset >>> 0
  2104. if (!noAssert) checkOffset(offset, 8, this.length)
  2105. return ieee754.read(this, offset, false, 52, 8)
  2106. }
  2107. function checkInt (buf, value, offset, ext, max, min) {
  2108. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  2109. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  2110. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2111. }
  2112. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  2113. value = +value
  2114. offset = offset >>> 0
  2115. byteLength = byteLength >>> 0
  2116. if (!noAssert) {
  2117. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  2118. checkInt(this, value, offset, byteLength, maxBytes, 0)
  2119. }
  2120. var mul = 1
  2121. var i = 0
  2122. this[offset] = value & 0xFF
  2123. while (++i < byteLength && (mul *= 0x100)) {
  2124. this[offset + i] = (value / mul) & 0xFF
  2125. }
  2126. return offset + byteLength
  2127. }
  2128. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  2129. value = +value
  2130. offset = offset >>> 0
  2131. byteLength = byteLength >>> 0
  2132. if (!noAssert) {
  2133. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  2134. checkInt(this, value, offset, byteLength, maxBytes, 0)
  2135. }
  2136. var i = byteLength - 1
  2137. var mul = 1
  2138. this[offset + i] = value & 0xFF
  2139. while (--i >= 0 && (mul *= 0x100)) {
  2140. this[offset + i] = (value / mul) & 0xFF
  2141. }
  2142. return offset + byteLength
  2143. }
  2144. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  2145. value = +value
  2146. offset = offset >>> 0
  2147. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  2148. this[offset] = (value & 0xff)
  2149. return offset + 1
  2150. }
  2151. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  2152. value = +value
  2153. offset = offset >>> 0
  2154. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  2155. this[offset] = (value & 0xff)
  2156. this[offset + 1] = (value >>> 8)
  2157. return offset + 2
  2158. }
  2159. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  2160. value = +value
  2161. offset = offset >>> 0
  2162. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  2163. this[offset] = (value >>> 8)
  2164. this[offset + 1] = (value & 0xff)
  2165. return offset + 2
  2166. }
  2167. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  2168. value = +value
  2169. offset = offset >>> 0
  2170. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  2171. this[offset + 3] = (value >>> 24)
  2172. this[offset + 2] = (value >>> 16)
  2173. this[offset + 1] = (value >>> 8)
  2174. this[offset] = (value & 0xff)
  2175. return offset + 4
  2176. }
  2177. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  2178. value = +value
  2179. offset = offset >>> 0
  2180. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  2181. this[offset] = (value >>> 24)
  2182. this[offset + 1] = (value >>> 16)
  2183. this[offset + 2] = (value >>> 8)
  2184. this[offset + 3] = (value & 0xff)
  2185. return offset + 4
  2186. }
  2187. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  2188. value = +value
  2189. offset = offset >>> 0
  2190. if (!noAssert) {
  2191. var limit = Math.pow(2, (8 * byteLength) - 1)
  2192. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  2193. }
  2194. var i = 0
  2195. var mul = 1
  2196. var sub = 0
  2197. this[offset] = value & 0xFF
  2198. while (++i < byteLength && (mul *= 0x100)) {
  2199. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  2200. sub = 1
  2201. }
  2202. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  2203. }
  2204. return offset + byteLength
  2205. }
  2206. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  2207. value = +value
  2208. offset = offset >>> 0
  2209. if (!noAssert) {
  2210. var limit = Math.pow(2, (8 * byteLength) - 1)
  2211. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  2212. }
  2213. var i = byteLength - 1
  2214. var mul = 1
  2215. var sub = 0
  2216. this[offset + i] = value & 0xFF
  2217. while (--i >= 0 && (mul *= 0x100)) {
  2218. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  2219. sub = 1
  2220. }
  2221. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  2222. }
  2223. return offset + byteLength
  2224. }
  2225. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  2226. value = +value
  2227. offset = offset >>> 0
  2228. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  2229. if (value < 0) value = 0xff + value + 1
  2230. this[offset] = (value & 0xff)
  2231. return offset + 1
  2232. }
  2233. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  2234. value = +value
  2235. offset = offset >>> 0
  2236. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  2237. this[offset] = (value & 0xff)
  2238. this[offset + 1] = (value >>> 8)
  2239. return offset + 2
  2240. }
  2241. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  2242. value = +value
  2243. offset = offset >>> 0
  2244. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  2245. this[offset] = (value >>> 8)
  2246. this[offset + 1] = (value & 0xff)
  2247. return offset + 2
  2248. }
  2249. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  2250. value = +value
  2251. offset = offset >>> 0
  2252. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  2253. this[offset] = (value & 0xff)
  2254. this[offset + 1] = (value >>> 8)
  2255. this[offset + 2] = (value >>> 16)
  2256. this[offset + 3] = (value >>> 24)
  2257. return offset + 4
  2258. }
  2259. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  2260. value = +value
  2261. offset = offset >>> 0
  2262. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  2263. if (value < 0) value = 0xffffffff + value + 1
  2264. this[offset] = (value >>> 24)
  2265. this[offset + 1] = (value >>> 16)
  2266. this[offset + 2] = (value >>> 8)
  2267. this[offset + 3] = (value & 0xff)
  2268. return offset + 4
  2269. }
  2270. function checkIEEE754 (buf, value, offset, ext, max, min) {
  2271. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2272. if (offset < 0) throw new RangeError('Index out of range')
  2273. }
  2274. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2275. value = +value
  2276. offset = offset >>> 0
  2277. if (!noAssert) {
  2278. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  2279. }
  2280. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  2281. return offset + 4
  2282. }
  2283. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  2284. return writeFloat(this, value, offset, true, noAssert)
  2285. }
  2286. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  2287. return writeFloat(this, value, offset, false, noAssert)
  2288. }
  2289. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2290. value = +value
  2291. offset = offset >>> 0
  2292. if (!noAssert) {
  2293. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  2294. }
  2295. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  2296. return offset + 8
  2297. }
  2298. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  2299. return writeDouble(this, value, offset, true, noAssert)
  2300. }
  2301. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  2302. return writeDouble(this, value, offset, false, noAssert)
  2303. }
  2304. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2305. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  2306. if (!start) start = 0
  2307. if (!end && end !== 0) end = this.length
  2308. if (targetStart >= target.length) targetStart = target.length
  2309. if (!targetStart) targetStart = 0
  2310. if (end > 0 && end < start) end = start
  2311. // Copy 0 bytes; we're done
  2312. if (end === start) return 0
  2313. if (target.length === 0 || this.length === 0) return 0
  2314. // Fatal error conditions
  2315. if (targetStart < 0) {
  2316. throw new RangeError('targetStart out of bounds')
  2317. }
  2318. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2319. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2320. // Are we oob?
  2321. if (end > this.length) end = this.length
  2322. if (target.length - targetStart < end - start) {
  2323. end = target.length - targetStart + start
  2324. }
  2325. var len = end - start
  2326. var i
  2327. if (this === target && start < targetStart && targetStart < end) {
  2328. // descending copy from end
  2329. for (i = len - 1; i >= 0; --i) {
  2330. target[i + targetStart] = this[i + start]
  2331. }
  2332. } else if (len < 1000) {
  2333. // ascending copy from start
  2334. for (i = 0; i < len; ++i) {
  2335. target[i + targetStart] = this[i + start]
  2336. }
  2337. } else {
  2338. Uint8Array.prototype.set.call(
  2339. target,
  2340. this.subarray(start, start + len),
  2341. targetStart
  2342. )
  2343. }
  2344. return len
  2345. }
  2346. // Usage:
  2347. // buffer.fill(number[, offset[, end]])
  2348. // buffer.fill(buffer[, offset[, end]])
  2349. // buffer.fill(string[, offset[, end]][, encoding])
  2350. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  2351. // Handle string cases:
  2352. if (typeof val === 'string') {
  2353. if (typeof start === 'string') {
  2354. encoding = start
  2355. start = 0
  2356. end = this.length
  2357. } else if (typeof end === 'string') {
  2358. encoding = end
  2359. end = this.length
  2360. }
  2361. if (val.length === 1) {
  2362. var code = val.charCodeAt(0)
  2363. if (code < 256) {
  2364. val = code
  2365. }
  2366. }
  2367. if (encoding !== undefined && typeof encoding !== 'string') {
  2368. throw new TypeError('encoding must be a string')
  2369. }
  2370. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  2371. throw new TypeError('Unknown encoding: ' + encoding)
  2372. }
  2373. } else if (typeof val === 'number') {
  2374. val = val & 255
  2375. }
  2376. // Invalid ranges are not set to a default, so can range check early.
  2377. if (start < 0 || this.length < start || this.length < end) {
  2378. throw new RangeError('Out of range index')
  2379. }
  2380. if (end <= start) {
  2381. return this
  2382. }
  2383. start = start >>> 0
  2384. end = end === undefined ? this.length : end >>> 0
  2385. if (!val) val = 0
  2386. var i
  2387. if (typeof val === 'number') {
  2388. for (i = start; i < end; ++i) {
  2389. this[i] = val
  2390. }
  2391. } else {
  2392. var bytes = Buffer.isBuffer(val)
  2393. ? val
  2394. : new Buffer(val, encoding)
  2395. var len = bytes.length
  2396. for (i = 0; i < end - start; ++i) {
  2397. this[i + start] = bytes[i % len]
  2398. }
  2399. }
  2400. return this
  2401. }
  2402. // HELPER FUNCTIONS
  2403. // ================
  2404. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  2405. function base64clean (str) {
  2406. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2407. str = str.trim().replace(INVALID_BASE64_RE, '')
  2408. // Node converts strings with length < 2 to ''
  2409. if (str.length < 2) return ''
  2410. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2411. while (str.length % 4 !== 0) {
  2412. str = str + '='
  2413. }
  2414. return str
  2415. }
  2416. function toHex (n) {
  2417. if (n < 16) return '0' + n.toString(16)
  2418. return n.toString(16)
  2419. }
  2420. function utf8ToBytes (string, units) {
  2421. units = units || Infinity
  2422. var codePoint
  2423. var length = string.length
  2424. var leadSurrogate = null
  2425. var bytes = []
  2426. for (var i = 0; i < length; ++i) {
  2427. codePoint = string.charCodeAt(i)
  2428. // is surrogate component
  2429. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2430. // last char was a lead
  2431. if (!leadSurrogate) {
  2432. // no lead yet
  2433. if (codePoint > 0xDBFF) {
  2434. // unexpected trail
  2435. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2436. continue
  2437. } else if (i + 1 === length) {
  2438. // unpaired lead
  2439. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2440. continue
  2441. }
  2442. // valid lead
  2443. leadSurrogate = codePoint
  2444. continue
  2445. }
  2446. // 2 leads in a row
  2447. if (codePoint < 0xDC00) {
  2448. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2449. leadSurrogate = codePoint
  2450. continue
  2451. }
  2452. // valid surrogate pair
  2453. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  2454. } else if (leadSurrogate) {
  2455. // valid bmp char, but last char was a lead
  2456. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2457. }
  2458. leadSurrogate = null
  2459. // encode utf8
  2460. if (codePoint < 0x80) {
  2461. if ((units -= 1) < 0) break
  2462. bytes.push(codePoint)
  2463. } else if (codePoint < 0x800) {
  2464. if ((units -= 2) < 0) break
  2465. bytes.push(
  2466. codePoint >> 0x6 | 0xC0,
  2467. codePoint & 0x3F | 0x80
  2468. )
  2469. } else if (codePoint < 0x10000) {
  2470. if ((units -= 3) < 0) break
  2471. bytes.push(
  2472. codePoint >> 0xC | 0xE0,
  2473. codePoint >> 0x6 & 0x3F | 0x80,
  2474. codePoint & 0x3F | 0x80
  2475. )
  2476. } else if (codePoint < 0x110000) {
  2477. if ((units -= 4) < 0) break
  2478. bytes.push(
  2479. codePoint >> 0x12 | 0xF0,
  2480. codePoint >> 0xC & 0x3F | 0x80,
  2481. codePoint >> 0x6 & 0x3F | 0x80,
  2482. codePoint & 0x3F | 0x80
  2483. )
  2484. } else {
  2485. throw new Error('Invalid code point')
  2486. }
  2487. }
  2488. return bytes
  2489. }
  2490. function asciiToBytes (str) {
  2491. var byteArray = []
  2492. for (var i = 0; i < str.length; ++i) {
  2493. // Node's code seems to be doing this and not & 0x7F..
  2494. byteArray.push(str.charCodeAt(i) & 0xFF)
  2495. }
  2496. return byteArray
  2497. }
  2498. function utf16leToBytes (str, units) {
  2499. var c, hi, lo
  2500. var byteArray = []
  2501. for (var i = 0; i < str.length; ++i) {
  2502. if ((units -= 2) < 0) break
  2503. c = str.charCodeAt(i)
  2504. hi = c >> 8
  2505. lo = c % 256
  2506. byteArray.push(lo)
  2507. byteArray.push(hi)
  2508. }
  2509. return byteArray
  2510. }
  2511. function base64ToBytes (str) {
  2512. return base64.toByteArray(base64clean(str))
  2513. }
  2514. function blitBuffer (src, dst, offset, length) {
  2515. for (var i = 0; i < length; ++i) {
  2516. if ((i + offset >= dst.length) || (i >= src.length)) break
  2517. dst[i + offset] = src[i]
  2518. }
  2519. return i
  2520. }
  2521. // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
  2522. // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
  2523. function isArrayBuffer (obj) {
  2524. return obj instanceof ArrayBuffer ||
  2525. (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
  2526. typeof obj.byteLength === 'number')
  2527. }
  2528. // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
  2529. function isArrayBufferView (obj) {
  2530. return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
  2531. }
  2532. function numberIsNaN (obj) {
  2533. return obj !== obj // eslint-disable-line no-self-compare
  2534. }
  2535. },{"base64-js":31,"ieee754":120}],33:[function(require,module,exports){
  2536. // Copyright Joyent, Inc. and other Node contributors.
  2537. //
  2538. // Permission is hereby granted, free of charge, to any person obtaining a
  2539. // copy of this software and associated documentation files (the
  2540. // "Software"), to deal in the Software without restriction, including
  2541. // without limitation the rights to use, copy, modify, merge, publish,
  2542. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2543. // persons to whom the Software is furnished to do so, subject to the
  2544. // following conditions:
  2545. //
  2546. // The above copyright notice and this permission notice shall be included
  2547. // in all copies or substantial portions of the Software.
  2548. //
  2549. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2550. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2551. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2552. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2553. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2554. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2555. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2556. function EventEmitter() {
  2557. this._events = this._events || {};
  2558. this._maxListeners = this._maxListeners || undefined;
  2559. }
  2560. module.exports = EventEmitter;
  2561. // Backwards-compat with node 0.10.x
  2562. EventEmitter.EventEmitter = EventEmitter;
  2563. EventEmitter.prototype._events = undefined;
  2564. EventEmitter.prototype._maxListeners = undefined;
  2565. // By default EventEmitters will print a warning if more than 10 listeners are
  2566. // added to it. This is a useful default which helps finding memory leaks.
  2567. EventEmitter.defaultMaxListeners = 10;
  2568. // Obviously not all Emitters should be limited to 10. This function allows
  2569. // that to be increased. Set to zero for unlimited.
  2570. EventEmitter.prototype.setMaxListeners = function(n) {
  2571. if (!isNumber(n) || n < 0 || isNaN(n))
  2572. throw TypeError('n must be a positive number');
  2573. this._maxListeners = n;
  2574. return this;
  2575. };
  2576. EventEmitter.prototype.emit = function(type) {
  2577. var er, handler, len, args, i, listeners;
  2578. if (!this._events)
  2579. this._events = {};
  2580. // If there is no 'error' event listener then throw.
  2581. if (type === 'error') {
  2582. if (!this._events.error ||
  2583. (isObject(this._events.error) && !this._events.error.length)) {
  2584. er = arguments[1];
  2585. if (er instanceof Error) {
  2586. throw er; // Unhandled 'error' event
  2587. } else {
  2588. // At least give some kind of context to the user
  2589. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  2590. err.context = er;
  2591. throw err;
  2592. }
  2593. }
  2594. }
  2595. handler = this._events[type];
  2596. if (isUndefined(handler))
  2597. return false;
  2598. if (isFunction(handler)) {
  2599. switch (arguments.length) {
  2600. // fast cases
  2601. case 1:
  2602. handler.call(this);
  2603. break;
  2604. case 2:
  2605. handler.call(this, arguments[1]);
  2606. break;
  2607. case 3:
  2608. handler.call(this, arguments[1], arguments[2]);
  2609. break;
  2610. // slower
  2611. default:
  2612. args = Array.prototype.slice.call(arguments, 1);
  2613. handler.apply(this, args);
  2614. }
  2615. } else if (isObject(handler)) {
  2616. args = Array.prototype.slice.call(arguments, 1);
  2617. listeners = handler.slice();
  2618. len = listeners.length;
  2619. for (i = 0; i < len; i++)
  2620. listeners[i].apply(this, args);
  2621. }
  2622. return true;
  2623. };
  2624. EventEmitter.prototype.addListener = function(type, listener) {
  2625. var m;
  2626. if (!isFunction(listener))
  2627. throw TypeError('listener must be a function');
  2628. if (!this._events)
  2629. this._events = {};
  2630. // To avoid recursion in the case that type === "newListener"! Before
  2631. // adding it to the listeners, first emit "newListener".
  2632. if (this._events.newListener)
  2633. this.emit('newListener', type,
  2634. isFunction(listener.listener) ?
  2635. listener.listener : listener);
  2636. if (!this._events[type])
  2637. // Optimize the case of one listener. Don't need the extra array object.
  2638. this._events[type] = listener;
  2639. else if (isObject(this._events[type]))
  2640. // If we've already got an array, just append.
  2641. this._events[type].push(listener);
  2642. else
  2643. // Adding the second element, need to change to array.
  2644. this._events[type] = [this._events[type], listener];
  2645. // Check for listener leak
  2646. if (isObject(this._events[type]) && !this._events[type].warned) {
  2647. if (!isUndefined(this._maxListeners)) {
  2648. m = this._maxListeners;
  2649. } else {
  2650. m = EventEmitter.defaultMaxListeners;
  2651. }
  2652. if (m && m > 0 && this._events[type].length > m) {
  2653. this._events[type].warned = true;
  2654. console.error('(node) warning: possible EventEmitter memory ' +
  2655. 'leak detected. %d listeners added. ' +
  2656. 'Use emitter.setMaxListeners() to increase limit.',
  2657. this._events[type].length);
  2658. if (typeof console.trace === 'function') {
  2659. // not supported in IE 10
  2660. console.trace();
  2661. }
  2662. }
  2663. }
  2664. return this;
  2665. };
  2666. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  2667. EventEmitter.prototype.once = function(type, listener) {
  2668. if (!isFunction(listener))
  2669. throw TypeError('listener must be a function');
  2670. var fired = false;
  2671. function g() {
  2672. this.removeListener(type, g);
  2673. if (!fired) {
  2674. fired = true;
  2675. listener.apply(this, arguments);
  2676. }
  2677. }
  2678. g.listener = listener;
  2679. this.on(type, g);
  2680. return this;
  2681. };
  2682. // emits a 'removeListener' event iff the listener was removed
  2683. EventEmitter.prototype.removeListener = function(type, listener) {
  2684. var list, position, length, i;
  2685. if (!isFunction(listener))
  2686. throw TypeError('listener must be a function');
  2687. if (!this._events || !this._events[type])
  2688. return this;
  2689. list = this._events[type];
  2690. length = list.length;
  2691. position = -1;
  2692. if (list === listener ||
  2693. (isFunction(list.listener) && list.listener === listener)) {
  2694. delete this._events[type];
  2695. if (this._events.removeListener)
  2696. this.emit('removeListener', type, listener);
  2697. } else if (isObject(list)) {
  2698. for (i = length; i-- > 0;) {
  2699. if (list[i] === listener ||
  2700. (list[i].listener && list[i].listener === listener)) {
  2701. position = i;
  2702. break;
  2703. }
  2704. }
  2705. if (position < 0)
  2706. return this;
  2707. if (list.length === 1) {
  2708. list.length = 0;
  2709. delete this._events[type];
  2710. } else {
  2711. list.splice(position, 1);
  2712. }
  2713. if (this._events.removeListener)
  2714. this.emit('removeListener', type, listener);
  2715. }
  2716. return this;
  2717. };
  2718. EventEmitter.prototype.removeAllListeners = function(type) {
  2719. var key, listeners;
  2720. if (!this._events)
  2721. return this;
  2722. // not listening for removeListener, no need to emit
  2723. if (!this._events.removeListener) {
  2724. if (arguments.length === 0)
  2725. this._events = {};
  2726. else if (this._events[type])
  2727. delete this._events[type];
  2728. return this;
  2729. }
  2730. // emit removeListener for all listeners on all events
  2731. if (arguments.length === 0) {
  2732. for (key in this._events) {
  2733. if (key === 'removeListener') continue;
  2734. this.removeAllListeners(key);
  2735. }
  2736. this.removeAllListeners('removeListener');
  2737. this._events = {};
  2738. return this;
  2739. }
  2740. listeners = this._events[type];
  2741. if (isFunction(listeners)) {
  2742. this.removeListener(type, listeners);
  2743. } else if (listeners) {
  2744. // LIFO order
  2745. while (listeners.length)
  2746. this.removeListener(type, listeners[listeners.length - 1]);
  2747. }
  2748. delete this._events[type];
  2749. return this;
  2750. };
  2751. EventEmitter.prototype.listeners = function(type) {
  2752. var ret;
  2753. if (!this._events || !this._events[type])
  2754. ret = [];
  2755. else if (isFunction(this._events[type]))
  2756. ret = [this._events[type]];
  2757. else
  2758. ret = this._events[type].slice();
  2759. return ret;
  2760. };
  2761. EventEmitter.prototype.listenerCount = function(type) {
  2762. if (this._events) {
  2763. var evlistener = this._events[type];
  2764. if (isFunction(evlistener))
  2765. return 1;
  2766. else if (evlistener)
  2767. return evlistener.length;
  2768. }
  2769. return 0;
  2770. };
  2771. EventEmitter.listenerCount = function(emitter, type) {
  2772. return emitter.listenerCount(type);
  2773. };
  2774. function isFunction(arg) {
  2775. return typeof arg === 'function';
  2776. }
  2777. function isNumber(arg) {
  2778. return typeof arg === 'number';
  2779. }
  2780. function isObject(arg) {
  2781. return typeof arg === 'object' && arg !== null;
  2782. }
  2783. function isUndefined(arg) {
  2784. return arg === void 0;
  2785. }
  2786. },{}],34:[function(require,module,exports){
  2787. var http = require('http')
  2788. var url = require('url')
  2789. var https = module.exports
  2790. for (var key in http) {
  2791. if (http.hasOwnProperty(key)) https[key] = http[key]
  2792. }
  2793. https.request = function (params, cb) {
  2794. params = validateParams(params)
  2795. return http.request.call(this, params, cb)
  2796. }
  2797. https.get = function (params, cb) {
  2798. params = validateParams(params)
  2799. return http.get.call(this, params, cb)
  2800. }
  2801. function validateParams (params) {
  2802. if (typeof params === 'string') {
  2803. params = url.parse(params)
  2804. }
  2805. if (!params.protocol) {
  2806. params.protocol = 'https:'
  2807. }
  2808. if (params.protocol !== 'https:') {
  2809. throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
  2810. }
  2811. return params
  2812. }
  2813. },{"http":131,"url":35}],35:[function(require,module,exports){
  2814. // Copyright Joyent, Inc. and other Node contributors.
  2815. //
  2816. // Permission is hereby granted, free of charge, to any person obtaining a
  2817. // copy of this software and associated documentation files (the
  2818. // "Software"), to deal in the Software without restriction, including
  2819. // without limitation the rights to use, copy, modify, merge, publish,
  2820. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2821. // persons to whom the Software is furnished to do so, subject to the
  2822. // following conditions:
  2823. //
  2824. // The above copyright notice and this permission notice shall be included
  2825. // in all copies or substantial portions of the Software.
  2826. //
  2827. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2828. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2829. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2830. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2831. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2832. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2833. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2834. 'use strict';
  2835. var punycode = require('punycode');
  2836. var util = require('./util');
  2837. exports.parse = urlParse;
  2838. exports.resolve = urlResolve;
  2839. exports.resolveObject = urlResolveObject;
  2840. exports.format = urlFormat;
  2841. exports.Url = Url;
  2842. function Url() {
  2843. this.protocol = null;
  2844. this.slashes = null;
  2845. this.auth = null;
  2846. this.host = null;
  2847. this.port = null;
  2848. this.hostname = null;
  2849. this.hash = null;
  2850. this.search = null;
  2851. this.query = null;
  2852. this.pathname = null;
  2853. this.path = null;
  2854. this.href = null;
  2855. }
  2856. // Reference: RFC 3986, RFC 1808, RFC 2396
  2857. // define these here so at least they only have to be
  2858. // compiled once on the first module load.
  2859. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  2860. portPattern = /:[0-9]*$/,
  2861. // Special case for a simple path URL
  2862. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  2863. // RFC 2396: characters reserved for delimiting URLs.
  2864. // We actually just auto-escape these.
  2865. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  2866. // RFC 2396: characters not allowed for various reasons.
  2867. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  2868. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  2869. autoEscape = ['\''].concat(unwise),
  2870. // Characters that are never ever allowed in a hostname.
  2871. // Note that any invalid chars are also handled, but these
  2872. // are the ones that are *expected* to be seen, so we fast-path
  2873. // them.
  2874. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  2875. hostEndingChars = ['/', '?', '#'],
  2876. hostnameMaxLen = 255,
  2877. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  2878. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  2879. // protocols that can allow "unsafe" and "unwise" chars.
  2880. unsafeProtocol = {
  2881. 'javascript': true,
  2882. 'javascript:': true
  2883. },
  2884. // protocols that never have a hostname.
  2885. hostlessProtocol = {
  2886. 'javascript': true,
  2887. 'javascript:': true
  2888. },
  2889. // protocols that always contain a // bit.
  2890. slashedProtocol = {
  2891. 'http': true,
  2892. 'https': true,
  2893. 'ftp': true,
  2894. 'gopher': true,
  2895. 'file': true,
  2896. 'http:': true,
  2897. 'https:': true,
  2898. 'ftp:': true,
  2899. 'gopher:': true,
  2900. 'file:': true
  2901. },
  2902. querystring = require('querystring');
  2903. function urlParse(url, parseQueryString, slashesDenoteHost) {
  2904. if (url && util.isObject(url) && url instanceof Url) return url;
  2905. var u = new Url;
  2906. u.parse(url, parseQueryString, slashesDenoteHost);
  2907. return u;
  2908. }
  2909. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  2910. if (!util.isString(url)) {
  2911. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  2912. }
  2913. // Copy chrome, IE, opera backslash-handling behavior.
  2914. // Back slashes before the query string get converted to forward slashes
  2915. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  2916. var queryIndex = url.indexOf('?'),
  2917. splitter =
  2918. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  2919. uSplit = url.split(splitter),
  2920. slashRegex = /\\/g;
  2921. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  2922. url = uSplit.join(splitter);
  2923. var rest = url;
  2924. // trim before proceeding.
  2925. // This is to support parse stuff like " http://foo.com \n"
  2926. rest = rest.trim();
  2927. if (!slashesDenoteHost && url.split('#').length === 1) {
  2928. // Try fast path regexp
  2929. var simplePath = simplePathPattern.exec(rest);
  2930. if (simplePath) {
  2931. this.path = rest;
  2932. this.href = rest;
  2933. this.pathname = simplePath[1];
  2934. if (simplePath[2]) {
  2935. this.search = simplePath[2];
  2936. if (parseQueryString) {
  2937. this.query = querystring.parse(this.search.substr(1));
  2938. } else {
  2939. this.query = this.search.substr(1);
  2940. }
  2941. } else if (parseQueryString) {
  2942. this.search = '';
  2943. this.query = {};
  2944. }
  2945. return this;
  2946. }
  2947. }
  2948. var proto = protocolPattern.exec(rest);
  2949. if (proto) {
  2950. proto = proto[0];
  2951. var lowerProto = proto.toLowerCase();
  2952. this.protocol = lowerProto;
  2953. rest = rest.substr(proto.length);
  2954. }
  2955. // figure out if it's got a host
  2956. // user@server is *always* interpreted as a hostname, and url
  2957. // resolution will treat //foo/bar as host=foo,path=bar because that's
  2958. // how the browser resolves relative URLs.
  2959. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  2960. var slashes = rest.substr(0, 2) === '//';
  2961. if (slashes && !(proto && hostlessProtocol[proto])) {
  2962. rest = rest.substr(2);
  2963. this.slashes = true;
  2964. }
  2965. }
  2966. if (!hostlessProtocol[proto] &&
  2967. (slashes || (proto && !slashedProtocol[proto]))) {
  2968. // there's a hostname.
  2969. // the first instance of /, ?, ;, or # ends the host.
  2970. //
  2971. // If there is an @ in the hostname, then non-host chars *are* allowed
  2972. // to the left of the last @ sign, unless some host-ending character
  2973. // comes *before* the @-sign.
  2974. // URLs are obnoxious.
  2975. //
  2976. // ex:
  2977. // http://a@b@c/ => user:a@b host:c
  2978. // http://a@b?@c => user:a host:c path:/?@c
  2979. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  2980. // Review our test case against browsers more comprehensively.
  2981. // find the first instance of any hostEndingChars
  2982. var hostEnd = -1;
  2983. for (var i = 0; i < hostEndingChars.length; i++) {
  2984. var hec = rest.indexOf(hostEndingChars[i]);
  2985. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  2986. hostEnd = hec;
  2987. }
  2988. // at this point, either we have an explicit point where the
  2989. // auth portion cannot go past, or the last @ char is the decider.
  2990. var auth, atSign;
  2991. if (hostEnd === -1) {
  2992. // atSign can be anywhere.
  2993. atSign = rest.lastIndexOf('@');
  2994. } else {
  2995. // atSign must be in auth portion.
  2996. // http://a@b/c@d => host:b auth:a path:/c@d
  2997. atSign = rest.lastIndexOf('@', hostEnd);
  2998. }
  2999. // Now we have a portion which is definitely the auth.
  3000. // Pull that off.
  3001. if (atSign !== -1) {
  3002. auth = rest.slice(0, atSign);
  3003. rest = rest.slice(atSign + 1);
  3004. this.auth = decodeURIComponent(auth);
  3005. }
  3006. // the host is the remaining to the left of the first non-host char
  3007. hostEnd = -1;
  3008. for (var i = 0; i < nonHostChars.length; i++) {
  3009. var hec = rest.indexOf(nonHostChars[i]);
  3010. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  3011. hostEnd = hec;
  3012. }
  3013. // if we still have not hit it, then the entire thing is a host.
  3014. if (hostEnd === -1)
  3015. hostEnd = rest.length;
  3016. this.host = rest.slice(0, hostEnd);
  3017. rest = rest.slice(hostEnd);
  3018. // pull out port.
  3019. this.parseHost();
  3020. // we've indicated that there is a hostname,
  3021. // so even if it's empty, it has to be present.
  3022. this.hostname = this.hostname || '';
  3023. // if hostname begins with [ and ends with ]
  3024. // assume that it's an IPv6 address.
  3025. var ipv6Hostname = this.hostname[0] === '[' &&
  3026. this.hostname[this.hostname.length - 1] === ']';
  3027. // validate a little.
  3028. if (!ipv6Hostname) {
  3029. var hostparts = this.hostname.split(/\./);
  3030. for (var i = 0, l = hostparts.length; i < l; i++) {
  3031. var part = hostparts[i];
  3032. if (!part) continue;
  3033. if (!part.match(hostnamePartPattern)) {
  3034. var newpart = '';
  3035. for (var j = 0, k = part.length; j < k; j++) {
  3036. if (part.charCodeAt(j) > 127) {
  3037. // we replace non-ASCII char with a temporary placeholder
  3038. // we need this to make sure size of hostname is not
  3039. // broken by replacing non-ASCII by nothing
  3040. newpart += 'x';
  3041. } else {
  3042. newpart += part[j];
  3043. }
  3044. }
  3045. // we test again with ASCII char only
  3046. if (!newpart.match(hostnamePartPattern)) {
  3047. var validParts = hostparts.slice(0, i);
  3048. var notHost = hostparts.slice(i + 1);
  3049. var bit = part.match(hostnamePartStart);
  3050. if (bit) {
  3051. validParts.push(bit[1]);
  3052. notHost.unshift(bit[2]);
  3053. }
  3054. if (notHost.length) {
  3055. rest = '/' + notHost.join('.') + rest;
  3056. }
  3057. this.hostname = validParts.join('.');
  3058. break;
  3059. }
  3060. }
  3061. }
  3062. }
  3063. if (this.hostname.length > hostnameMaxLen) {
  3064. this.hostname = '';
  3065. } else {
  3066. // hostnames are always lower case.
  3067. this.hostname = this.hostname.toLowerCase();
  3068. }
  3069. if (!ipv6Hostname) {
  3070. // IDNA Support: Returns a punycoded representation of "domain".
  3071. // It only converts parts of the domain name that
  3072. // have non-ASCII characters, i.e. it doesn't matter if
  3073. // you call it with a domain that already is ASCII-only.
  3074. this.hostname = punycode.toASCII(this.hostname);
  3075. }
  3076. var p = this.port ? ':' + this.port : '';
  3077. var h = this.hostname || '';
  3078. this.host = h + p;
  3079. this.href += this.host;
  3080. // strip [ and ] from the hostname
  3081. // the host field still retains them, though
  3082. if (ipv6Hostname) {
  3083. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  3084. if (rest[0] !== '/') {
  3085. rest = '/' + rest;
  3086. }
  3087. }
  3088. }
  3089. // now rest is set to the post-host stuff.
  3090. // chop off any delim chars.
  3091. if (!unsafeProtocol[lowerProto]) {
  3092. // First, make 100% sure that any "autoEscape" chars get
  3093. // escaped, even if encodeURIComponent doesn't think they
  3094. // need to be.
  3095. for (var i = 0, l = autoEscape.length; i < l; i++) {
  3096. var ae = autoEscape[i];
  3097. if (rest.indexOf(ae) === -1)
  3098. continue;
  3099. var esc = encodeURIComponent(ae);
  3100. if (esc === ae) {
  3101. esc = escape(ae);
  3102. }
  3103. rest = rest.split(ae).join(esc);
  3104. }
  3105. }
  3106. // chop off from the tail first.
  3107. var hash = rest.indexOf('#');
  3108. if (hash !== -1) {
  3109. // got a fragment string.
  3110. this.hash = rest.substr(hash);
  3111. rest = rest.slice(0, hash);
  3112. }
  3113. var qm = rest.indexOf('?');
  3114. if (qm !== -1) {
  3115. this.search = rest.substr(qm);
  3116. this.query = rest.substr(qm + 1);
  3117. if (parseQueryString) {
  3118. this.query = querystring.parse(this.query);
  3119. }
  3120. rest = rest.slice(0, qm);
  3121. } else if (parseQueryString) {
  3122. // no query string, but parseQueryString still requested
  3123. this.search = '';
  3124. this.query = {};
  3125. }
  3126. if (rest) this.pathname = rest;
  3127. if (slashedProtocol[lowerProto] &&
  3128. this.hostname && !this.pathname) {
  3129. this.pathname = '/';
  3130. }
  3131. //to support http.request
  3132. if (this.pathname || this.search) {
  3133. var p = this.pathname || '';
  3134. var s = this.search || '';
  3135. this.path = p + s;
  3136. }
  3137. // finally, reconstruct the href based on what has been validated.
  3138. this.href = this.format();
  3139. return this;
  3140. };
  3141. // format a parsed object into a url string
  3142. function urlFormat(obj) {
  3143. // ensure it's an object, and not a string url.
  3144. // If it's an obj, this is a no-op.
  3145. // this way, you can call url_format() on strings
  3146. // to clean up potentially wonky urls.
  3147. if (util.isString(obj)) obj = urlParse(obj);
  3148. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  3149. return obj.format();
  3150. }
  3151. Url.prototype.format = function() {
  3152. var auth = this.auth || '';
  3153. if (auth) {
  3154. auth = encodeURIComponent(auth);
  3155. auth = auth.replace(/%3A/i, ':');
  3156. auth += '@';
  3157. }
  3158. var protocol = this.protocol || '',
  3159. pathname = this.pathname || '',
  3160. hash = this.hash || '',
  3161. host = false,
  3162. query = '';
  3163. if (this.host) {
  3164. host = auth + this.host;
  3165. } else if (this.hostname) {
  3166. host = auth + (this.hostname.indexOf(':') === -1 ?
  3167. this.hostname :
  3168. '[' + this.hostname + ']');
  3169. if (this.port) {
  3170. host += ':' + this.port;
  3171. }
  3172. }
  3173. if (this.query &&
  3174. util.isObject(this.query) &&
  3175. Object.keys(this.query).length) {
  3176. query = querystring.stringify(this.query);
  3177. }
  3178. var search = this.search || (query && ('?' + query)) || '';
  3179. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  3180. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  3181. // unless they had them to begin with.
  3182. if (this.slashes ||
  3183. (!protocol || slashedProtocol[protocol]) && host !== false) {
  3184. host = '//' + (host || '');
  3185. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  3186. } else if (!host) {
  3187. host = '';
  3188. }
  3189. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  3190. if (search && search.charAt(0) !== '?') search = '?' + search;
  3191. pathname = pathname.replace(/[?#]/g, function(match) {
  3192. return encodeURIComponent(match);
  3193. });
  3194. search = search.replace('#', '%23');
  3195. return protocol + host + pathname + search + hash;
  3196. };
  3197. function urlResolve(source, relative) {
  3198. return urlParse(source, false, true).resolve(relative);
  3199. }
  3200. Url.prototype.resolve = function(relative) {
  3201. return this.resolveObject(urlParse(relative, false, true)).format();
  3202. };
  3203. function urlResolveObject(source, relative) {
  3204. if (!source) return relative;
  3205. return urlParse(source, false, true).resolveObject(relative);
  3206. }
  3207. Url.prototype.resolveObject = function(relative) {
  3208. if (util.isString(relative)) {
  3209. var rel = new Url();
  3210. rel.parse(relative, false, true);
  3211. relative = rel;
  3212. }
  3213. var result = new Url();
  3214. var tkeys = Object.keys(this);
  3215. for (var tk = 0; tk < tkeys.length; tk++) {
  3216. var tkey = tkeys[tk];
  3217. result[tkey] = this[tkey];
  3218. }
  3219. // hash is always overridden, no matter what.
  3220. // even href="" will remove it.
  3221. result.hash = relative.hash;
  3222. // if the relative url is empty, then there's nothing left to do here.
  3223. if (relative.href === '') {
  3224. result.href = result.format();
  3225. return result;
  3226. }
  3227. // hrefs like //foo/bar always cut to the protocol.
  3228. if (relative.slashes && !relative.protocol) {
  3229. // take everything except the protocol from relative
  3230. var rkeys = Object.keys(relative);
  3231. for (var rk = 0; rk < rkeys.length; rk++) {
  3232. var rkey = rkeys[rk];
  3233. if (rkey !== 'protocol')
  3234. result[rkey] = relative[rkey];
  3235. }
  3236. //urlParse appends trailing / to urls like http://www.example.com
  3237. if (slashedProtocol[result.protocol] &&
  3238. result.hostname && !result.pathname) {
  3239. result.path = result.pathname = '/';
  3240. }
  3241. result.href = result.format();
  3242. return result;
  3243. }
  3244. if (relative.protocol && relative.protocol !== result.protocol) {
  3245. // if it's a known url protocol, then changing
  3246. // the protocol does weird things
  3247. // first, if it's not file:, then we MUST have a host,
  3248. // and if there was a path
  3249. // to begin with, then we MUST have a path.
  3250. // if it is file:, then the host is dropped,
  3251. // because that's known to be hostless.
  3252. // anything else is assumed to be absolute.
  3253. if (!slashedProtocol[relative.protocol]) {
  3254. var keys = Object.keys(relative);
  3255. for (var v = 0; v < keys.length; v++) {
  3256. var k = keys[v];
  3257. result[k] = relative[k];
  3258. }
  3259. result.href = result.format();
  3260. return result;
  3261. }
  3262. result.protocol = relative.protocol;
  3263. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  3264. var relPath = (relative.pathname || '').split('/');
  3265. while (relPath.length && !(relative.host = relPath.shift()));
  3266. if (!relative.host) relative.host = '';
  3267. if (!relative.hostname) relative.hostname = '';
  3268. if (relPath[0] !== '') relPath.unshift('');
  3269. if (relPath.length < 2) relPath.unshift('');
  3270. result.pathname = relPath.join('/');
  3271. } else {
  3272. result.pathname = relative.pathname;
  3273. }
  3274. result.search = relative.search;
  3275. result.query = relative.query;
  3276. result.host = relative.host || '';
  3277. result.auth = relative.auth;
  3278. result.hostname = relative.hostname || relative.host;
  3279. result.port = relative.port;
  3280. // to support http.request
  3281. if (result.pathname || result.search) {
  3282. var p = result.pathname || '';
  3283. var s = result.search || '';
  3284. result.path = p + s;
  3285. }
  3286. result.slashes = result.slashes || relative.slashes;
  3287. result.href = result.format();
  3288. return result;
  3289. }
  3290. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  3291. isRelAbs = (
  3292. relative.host ||
  3293. relative.pathname && relative.pathname.charAt(0) === '/'
  3294. ),
  3295. mustEndAbs = (isRelAbs || isSourceAbs ||
  3296. (result.host && relative.pathname)),
  3297. removeAllDots = mustEndAbs,
  3298. srcPath = result.pathname && result.pathname.split('/') || [],
  3299. relPath = relative.pathname && relative.pathname.split('/') || [],
  3300. psychotic = result.protocol && !slashedProtocol[result.protocol];
  3301. // if the url is a non-slashed url, then relative
  3302. // links like ../.. should be able
  3303. // to crawl up to the hostname, as well. This is strange.
  3304. // result.protocol has already been set by now.
  3305. // Later on, put the first path part into the host field.
  3306. if (psychotic) {
  3307. result.hostname = '';
  3308. result.port = null;
  3309. if (result.host) {
  3310. if (srcPath[0] === '') srcPath[0] = result.host;
  3311. else srcPath.unshift(result.host);
  3312. }
  3313. result.host = '';
  3314. if (relative.protocol) {
  3315. relative.hostname = null;
  3316. relative.port = null;
  3317. if (relative.host) {
  3318. if (relPath[0] === '') relPath[0] = relative.host;
  3319. else relPath.unshift(relative.host);
  3320. }
  3321. relative.host = null;
  3322. }
  3323. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  3324. }
  3325. if (isRelAbs) {
  3326. // it's absolute.
  3327. result.host = (relative.host || relative.host === '') ?
  3328. relative.host : result.host;
  3329. result.hostname = (relative.hostname || relative.hostname === '') ?
  3330. relative.hostname : result.hostname;
  3331. result.search = relative.search;
  3332. result.query = relative.query;
  3333. srcPath = relPath;
  3334. // fall through to the dot-handling below.
  3335. } else if (relPath.length) {
  3336. // it's relative
  3337. // throw away the existing file, and take the new path instead.
  3338. if (!srcPath) srcPath = [];
  3339. srcPath.pop();
  3340. srcPath = srcPath.concat(relPath);
  3341. result.search = relative.search;
  3342. result.query = relative.query;
  3343. } else if (!util.isNullOrUndefined(relative.search)) {
  3344. // just pull out the search.
  3345. // like href='?foo'.
  3346. // Put this after the other two cases because it simplifies the booleans
  3347. if (psychotic) {
  3348. result.hostname = result.host = srcPath.shift();
  3349. //occationaly the auth can get stuck only in host
  3350. //this especially happens in cases like
  3351. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  3352. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  3353. result.host.split('@') : false;
  3354. if (authInHost) {
  3355. result.auth = authInHost.shift();
  3356. result.host = result.hostname = authInHost.shift();
  3357. }
  3358. }
  3359. result.search = relative.search;
  3360. result.query = relative.query;
  3361. //to support http.request
  3362. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  3363. result.path = (result.pathname ? result.pathname : '') +
  3364. (result.search ? result.search : '');
  3365. }
  3366. result.href = result.format();
  3367. return result;
  3368. }
  3369. if (!srcPath.length) {
  3370. // no path at all. easy.
  3371. // we've already handled the other stuff above.
  3372. result.pathname = null;
  3373. //to support http.request
  3374. if (result.search) {
  3375. result.path = '/' + result.search;
  3376. } else {
  3377. result.path = null;
  3378. }
  3379. result.href = result.format();
  3380. return result;
  3381. }
  3382. // if a url ENDs in . or .., then it must get a trailing slash.
  3383. // however, if it ends in anything else non-slashy,
  3384. // then it must NOT get a trailing slash.
  3385. var last = srcPath.slice(-1)[0];
  3386. var hasTrailingSlash = (
  3387. (result.host || relative.host || srcPath.length > 1) &&
  3388. (last === '.' || last === '..') || last === '');
  3389. // strip single dots, resolve double dots to parent dir
  3390. // if the path tries to go above the root, `up` ends up > 0
  3391. var up = 0;
  3392. for (var i = srcPath.length; i >= 0; i--) {
  3393. last = srcPath[i];
  3394. if (last === '.') {
  3395. srcPath.splice(i, 1);
  3396. } else if (last === '..') {
  3397. srcPath.splice(i, 1);
  3398. up++;
  3399. } else if (up) {
  3400. srcPath.splice(i, 1);
  3401. up--;
  3402. }
  3403. }
  3404. // if the path is allowed to go above the root, restore leading ..s
  3405. if (!mustEndAbs && !removeAllDots) {
  3406. for (; up--; up) {
  3407. srcPath.unshift('..');
  3408. }
  3409. }
  3410. if (mustEndAbs && srcPath[0] !== '' &&
  3411. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  3412. srcPath.unshift('');
  3413. }
  3414. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  3415. srcPath.push('');
  3416. }
  3417. var isAbsolute = srcPath[0] === '' ||
  3418. (srcPath[0] && srcPath[0].charAt(0) === '/');
  3419. // put the host back
  3420. if (psychotic) {
  3421. result.hostname = result.host = isAbsolute ? '' :
  3422. srcPath.length ? srcPath.shift() : '';
  3423. //occationaly the auth can get stuck only in host
  3424. //this especially happens in cases like
  3425. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  3426. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  3427. result.host.split('@') : false;
  3428. if (authInHost) {
  3429. result.auth = authInHost.shift();
  3430. result.host = result.hostname = authInHost.shift();
  3431. }
  3432. }
  3433. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  3434. if (mustEndAbs && !isAbsolute) {
  3435. srcPath.unshift('');
  3436. }
  3437. if (!srcPath.length) {
  3438. result.pathname = null;
  3439. result.path = null;
  3440. } else {
  3441. result.pathname = srcPath.join('/');
  3442. }
  3443. //to support request.http
  3444. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  3445. result.path = (result.pathname ? result.pathname : '') +
  3446. (result.search ? result.search : '');
  3447. }
  3448. result.auth = relative.auth || result.auth;
  3449. result.slashes = result.slashes || relative.slashes;
  3450. result.href = result.format();
  3451. return result;
  3452. };
  3453. Url.prototype.parseHost = function() {
  3454. var host = this.host;
  3455. var port = portPattern.exec(host);
  3456. if (port) {
  3457. port = port[0];
  3458. if (port !== ':') {
  3459. this.port = port.substr(1);
  3460. }
  3461. host = host.substr(0, host.length - port.length);
  3462. }
  3463. if (host) this.hostname = host;
  3464. };
  3465. },{"./util":36,"punycode":126,"querystring":129}],36:[function(require,module,exports){
  3466. 'use strict';
  3467. module.exports = {
  3468. isString: function(arg) {
  3469. return typeof(arg) === 'string';
  3470. },
  3471. isObject: function(arg) {
  3472. return typeof(arg) === 'object' && arg !== null;
  3473. },
  3474. isNull: function(arg) {
  3475. return arg === null;
  3476. },
  3477. isNullOrUndefined: function(arg) {
  3478. return arg == null;
  3479. }
  3480. };
  3481. },{}],37:[function(require,module,exports){
  3482. module.exports = {
  3483. "100": "Continue",
  3484. "101": "Switching Protocols",
  3485. "102": "Processing",
  3486. "200": "OK",
  3487. "201": "Created",
  3488. "202": "Accepted",
  3489. "203": "Non-Authoritative Information",
  3490. "204": "No Content",
  3491. "205": "Reset Content",
  3492. "206": "Partial Content",
  3493. "207": "Multi-Status",
  3494. "208": "Already Reported",
  3495. "226": "IM Used",
  3496. "300": "Multiple Choices",
  3497. "301": "Moved Permanently",
  3498. "302": "Found",
  3499. "303": "See Other",
  3500. "304": "Not Modified",
  3501. "305": "Use Proxy",
  3502. "307": "Temporary Redirect",
  3503. "308": "Permanent Redirect",
  3504. "400": "Bad Request",
  3505. "401": "Unauthorized",
  3506. "402": "Payment Required",
  3507. "403": "Forbidden",
  3508. "404": "Not Found",
  3509. "405": "Method Not Allowed",
  3510. "406": "Not Acceptable",
  3511. "407": "Proxy Authentication Required",
  3512. "408": "Request Timeout",
  3513. "409": "Conflict",
  3514. "410": "Gone",
  3515. "411": "Length Required",
  3516. "412": "Precondition Failed",
  3517. "413": "Payload Too Large",
  3518. "414": "URI Too Long",
  3519. "415": "Unsupported Media Type",
  3520. "416": "Range Not Satisfiable",
  3521. "417": "Expectation Failed",
  3522. "418": "I'm a teapot",
  3523. "421": "Misdirected Request",
  3524. "422": "Unprocessable Entity",
  3525. "423": "Locked",
  3526. "424": "Failed Dependency",
  3527. "425": "Unordered Collection",
  3528. "426": "Upgrade Required",
  3529. "428": "Precondition Required",
  3530. "429": "Too Many Requests",
  3531. "431": "Request Header Fields Too Large",
  3532. "451": "Unavailable For Legal Reasons",
  3533. "500": "Internal Server Error",
  3534. "501": "Not Implemented",
  3535. "502": "Bad Gateway",
  3536. "503": "Service Unavailable",
  3537. "504": "Gateway Timeout",
  3538. "505": "HTTP Version Not Supported",
  3539. "506": "Variant Also Negotiates",
  3540. "507": "Insufficient Storage",
  3541. "508": "Loop Detected",
  3542. "509": "Bandwidth Limit Exceeded",
  3543. "510": "Not Extended",
  3544. "511": "Network Authentication Required"
  3545. }
  3546. },{}],38:[function(require,module,exports){
  3547. (function (Buffer){
  3548. // Copyright Joyent, Inc. and other Node contributors.
  3549. //
  3550. // Permission is hereby granted, free of charge, to any person obtaining a
  3551. // copy of this software and associated documentation files (the
  3552. // "Software"), to deal in the Software without restriction, including
  3553. // without limitation the rights to use, copy, modify, merge, publish,
  3554. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3555. // persons to whom the Software is furnished to do so, subject to the
  3556. // following conditions:
  3557. //
  3558. // The above copyright notice and this permission notice shall be included
  3559. // in all copies or substantial portions of the Software.
  3560. //
  3561. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3562. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3563. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3564. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3565. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3566. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3567. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3568. // NOTE: These type checking functions intentionally don't use `instanceof`
  3569. // because it is fragile and can be easily faked with `Object.create()`.
  3570. function isArray(arg) {
  3571. if (Array.isArray) {
  3572. return Array.isArray(arg);
  3573. }
  3574. return objectToString(arg) === '[object Array]';
  3575. }
  3576. exports.isArray = isArray;
  3577. function isBoolean(arg) {
  3578. return typeof arg === 'boolean';
  3579. }
  3580. exports.isBoolean = isBoolean;
  3581. function isNull(arg) {
  3582. return arg === null;
  3583. }
  3584. exports.isNull = isNull;
  3585. function isNullOrUndefined(arg) {
  3586. return arg == null;
  3587. }
  3588. exports.isNullOrUndefined = isNullOrUndefined;
  3589. function isNumber(arg) {
  3590. return typeof arg === 'number';
  3591. }
  3592. exports.isNumber = isNumber;
  3593. function isString(arg) {
  3594. return typeof arg === 'string';
  3595. }
  3596. exports.isString = isString;
  3597. function isSymbol(arg) {
  3598. return typeof arg === 'symbol';
  3599. }
  3600. exports.isSymbol = isSymbol;
  3601. function isUndefined(arg) {
  3602. return arg === void 0;
  3603. }
  3604. exports.isUndefined = isUndefined;
  3605. function isRegExp(re) {
  3606. return objectToString(re) === '[object RegExp]';
  3607. }
  3608. exports.isRegExp = isRegExp;
  3609. function isObject(arg) {
  3610. return typeof arg === 'object' && arg !== null;
  3611. }
  3612. exports.isObject = isObject;
  3613. function isDate(d) {
  3614. return objectToString(d) === '[object Date]';
  3615. }
  3616. exports.isDate = isDate;
  3617. function isError(e) {
  3618. return (objectToString(e) === '[object Error]' || e instanceof Error);
  3619. }
  3620. exports.isError = isError;
  3621. function isFunction(arg) {
  3622. return typeof arg === 'function';
  3623. }
  3624. exports.isFunction = isFunction;
  3625. function isPrimitive(arg) {
  3626. return arg === null ||
  3627. typeof arg === 'boolean' ||
  3628. typeof arg === 'number' ||
  3629. typeof arg === 'string' ||
  3630. typeof arg === 'symbol' || // ES6 symbol
  3631. typeof arg === 'undefined';
  3632. }
  3633. exports.isPrimitive = isPrimitive;
  3634. exports.isBuffer = Buffer.isBuffer;
  3635. function objectToString(o) {
  3636. return Object.prototype.toString.call(o);
  3637. }
  3638. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  3639. },{"../../is-buffer/index.js":122}],39:[function(require,module,exports){
  3640. // https://d3js.org/d3-array/ Version 1.2.1. Copyright 2017 Mike Bostock.
  3641. (function (global, factory) {
  3642. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3643. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  3644. (factory((global.d3 = global.d3 || {})));
  3645. }(this, (function (exports) { 'use strict';
  3646. var ascending = function(a, b) {
  3647. return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
  3648. };
  3649. var bisector = function(compare) {
  3650. if (compare.length === 1) compare = ascendingComparator(compare);
  3651. return {
  3652. left: function(a, x, lo, hi) {
  3653. if (lo == null) lo = 0;
  3654. if (hi == null) hi = a.length;
  3655. while (lo < hi) {
  3656. var mid = lo + hi >>> 1;
  3657. if (compare(a[mid], x) < 0) lo = mid + 1;
  3658. else hi = mid;
  3659. }
  3660. return lo;
  3661. },
  3662. right: function(a, x, lo, hi) {
  3663. if (lo == null) lo = 0;
  3664. if (hi == null) hi = a.length;
  3665. while (lo < hi) {
  3666. var mid = lo + hi >>> 1;
  3667. if (compare(a[mid], x) > 0) hi = mid;
  3668. else lo = mid + 1;
  3669. }
  3670. return lo;
  3671. }
  3672. };
  3673. };
  3674. function ascendingComparator(f) {
  3675. return function(d, x) {
  3676. return ascending(f(d), x);
  3677. };
  3678. }
  3679. var ascendingBisect = bisector(ascending);
  3680. var bisectRight = ascendingBisect.right;
  3681. var bisectLeft = ascendingBisect.left;
  3682. var pairs = function(array, f) {
  3683. if (f == null) f = pair;
  3684. var i = 0, n = array.length - 1, p = array[0], pairs = new Array(n < 0 ? 0 : n);
  3685. while (i < n) pairs[i] = f(p, p = array[++i]);
  3686. return pairs;
  3687. };
  3688. function pair(a, b) {
  3689. return [a, b];
  3690. }
  3691. var cross = function(values0, values1, reduce) {
  3692. var n0 = values0.length,
  3693. n1 = values1.length,
  3694. values = new Array(n0 * n1),
  3695. i0,
  3696. i1,
  3697. i,
  3698. value0;
  3699. if (reduce == null) reduce = pair;
  3700. for (i0 = i = 0; i0 < n0; ++i0) {
  3701. for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {
  3702. values[i] = reduce(value0, values1[i1]);
  3703. }
  3704. }
  3705. return values;
  3706. };
  3707. var descending = function(a, b) {
  3708. return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
  3709. };
  3710. var number = function(x) {
  3711. return x === null ? NaN : +x;
  3712. };
  3713. var variance = function(values, valueof) {
  3714. var n = values.length,
  3715. m = 0,
  3716. i = -1,
  3717. mean = 0,
  3718. value,
  3719. delta,
  3720. sum = 0;
  3721. if (valueof == null) {
  3722. while (++i < n) {
  3723. if (!isNaN(value = number(values[i]))) {
  3724. delta = value - mean;
  3725. mean += delta / ++m;
  3726. sum += delta * (value - mean);
  3727. }
  3728. }
  3729. }
  3730. else {
  3731. while (++i < n) {
  3732. if (!isNaN(value = number(valueof(values[i], i, values)))) {
  3733. delta = value - mean;
  3734. mean += delta / ++m;
  3735. sum += delta * (value - mean);
  3736. }
  3737. }
  3738. }
  3739. if (m > 1) return sum / (m - 1);
  3740. };
  3741. var deviation = function(array, f) {
  3742. var v = variance(array, f);
  3743. return v ? Math.sqrt(v) : v;
  3744. };
  3745. var extent = function(values, valueof) {
  3746. var n = values.length,
  3747. i = -1,
  3748. value,
  3749. min,
  3750. max;
  3751. if (valueof == null) {
  3752. while (++i < n) { // Find the first comparable value.
  3753. if ((value = values[i]) != null && value >= value) {
  3754. min = max = value;
  3755. while (++i < n) { // Compare the remaining values.
  3756. if ((value = values[i]) != null) {
  3757. if (min > value) min = value;
  3758. if (max < value) max = value;
  3759. }
  3760. }
  3761. }
  3762. }
  3763. }
  3764. else {
  3765. while (++i < n) { // Find the first comparable value.
  3766. if ((value = valueof(values[i], i, values)) != null && value >= value) {
  3767. min = max = value;
  3768. while (++i < n) { // Compare the remaining values.
  3769. if ((value = valueof(values[i], i, values)) != null) {
  3770. if (min > value) min = value;
  3771. if (max < value) max = value;
  3772. }
  3773. }
  3774. }
  3775. }
  3776. }
  3777. return [min, max];
  3778. };
  3779. var array = Array.prototype;
  3780. var slice = array.slice;
  3781. var map = array.map;
  3782. var constant = function(x) {
  3783. return function() {
  3784. return x;
  3785. };
  3786. };
  3787. var identity = function(x) {
  3788. return x;
  3789. };
  3790. var range = function(start, stop, step) {
  3791. start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
  3792. var i = -1,
  3793. n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
  3794. range = new Array(n);
  3795. while (++i < n) {
  3796. range[i] = start + i * step;
  3797. }
  3798. return range;
  3799. };
  3800. var e10 = Math.sqrt(50);
  3801. var e5 = Math.sqrt(10);
  3802. var e2 = Math.sqrt(2);
  3803. var ticks = function(start, stop, count) {
  3804. var reverse,
  3805. i = -1,
  3806. n,
  3807. ticks,
  3808. step;
  3809. stop = +stop, start = +start, count = +count;
  3810. if (start === stop && count > 0) return [start];
  3811. if (reverse = stop < start) n = start, start = stop, stop = n;
  3812. if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];
  3813. if (step > 0) {
  3814. start = Math.ceil(start / step);
  3815. stop = Math.floor(stop / step);
  3816. ticks = new Array(n = Math.ceil(stop - start + 1));
  3817. while (++i < n) ticks[i] = (start + i) * step;
  3818. } else {
  3819. start = Math.floor(start * step);
  3820. stop = Math.ceil(stop * step);
  3821. ticks = new Array(n = Math.ceil(start - stop + 1));
  3822. while (++i < n) ticks[i] = (start - i) / step;
  3823. }
  3824. if (reverse) ticks.reverse();
  3825. return ticks;
  3826. };
  3827. function tickIncrement(start, stop, count) {
  3828. var step = (stop - start) / Math.max(0, count),
  3829. power = Math.floor(Math.log(step) / Math.LN10),
  3830. error = step / Math.pow(10, power);
  3831. return power >= 0
  3832. ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
  3833. : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
  3834. }
  3835. function tickStep(start, stop, count) {
  3836. var step0 = Math.abs(stop - start) / Math.max(0, count),
  3837. step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
  3838. error = step0 / step1;
  3839. if (error >= e10) step1 *= 10;
  3840. else if (error >= e5) step1 *= 5;
  3841. else if (error >= e2) step1 *= 2;
  3842. return stop < start ? -step1 : step1;
  3843. }
  3844. var sturges = function(values) {
  3845. return Math.ceil(Math.log(values.length) / Math.LN2) + 1;
  3846. };
  3847. var histogram = function() {
  3848. var value = identity,
  3849. domain = extent,
  3850. threshold = sturges;
  3851. function histogram(data) {
  3852. var i,
  3853. n = data.length,
  3854. x,
  3855. values = new Array(n);
  3856. for (i = 0; i < n; ++i) {
  3857. values[i] = value(data[i], i, data);
  3858. }
  3859. var xz = domain(values),
  3860. x0 = xz[0],
  3861. x1 = xz[1],
  3862. tz = threshold(values, x0, x1);
  3863. // Convert number of thresholds into uniform thresholds.
  3864. if (!Array.isArray(tz)) {
  3865. tz = tickStep(x0, x1, tz);
  3866. tz = range(Math.ceil(x0 / tz) * tz, Math.floor(x1 / tz) * tz, tz); // exclusive
  3867. }
  3868. // Remove any thresholds outside the domain.
  3869. var m = tz.length;
  3870. while (tz[0] <= x0) tz.shift(), --m;
  3871. while (tz[m - 1] > x1) tz.pop(), --m;
  3872. var bins = new Array(m + 1),
  3873. bin;
  3874. // Initialize bins.
  3875. for (i = 0; i <= m; ++i) {
  3876. bin = bins[i] = [];
  3877. bin.x0 = i > 0 ? tz[i - 1] : x0;
  3878. bin.x1 = i < m ? tz[i] : x1;
  3879. }
  3880. // Assign data to bins by value, ignoring any outside the domain.
  3881. for (i = 0; i < n; ++i) {
  3882. x = values[i];
  3883. if (x0 <= x && x <= x1) {
  3884. bins[bisectRight(tz, x, 0, m)].push(data[i]);
  3885. }
  3886. }
  3887. return bins;
  3888. }
  3889. histogram.value = function(_) {
  3890. return arguments.length ? (value = typeof _ === "function" ? _ : constant(_), histogram) : value;
  3891. };
  3892. histogram.domain = function(_) {
  3893. return arguments.length ? (domain = typeof _ === "function" ? _ : constant([_[0], _[1]]), histogram) : domain;
  3894. };
  3895. histogram.thresholds = function(_) {
  3896. return arguments.length ? (threshold = typeof _ === "function" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram) : threshold;
  3897. };
  3898. return histogram;
  3899. };
  3900. var quantile = function(values, p, valueof) {
  3901. if (valueof == null) valueof = number;
  3902. if (!(n = values.length)) return;
  3903. if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);
  3904. if (p >= 1) return +valueof(values[n - 1], n - 1, values);
  3905. var n,
  3906. i = (n - 1) * p,
  3907. i0 = Math.floor(i),
  3908. value0 = +valueof(values[i0], i0, values),
  3909. value1 = +valueof(values[i0 + 1], i0 + 1, values);
  3910. return value0 + (value1 - value0) * (i - i0);
  3911. };
  3912. var freedmanDiaconis = function(values, min, max) {
  3913. values = map.call(values, number).sort(ascending);
  3914. return Math.ceil((max - min) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));
  3915. };
  3916. var scott = function(values, min, max) {
  3917. return Math.ceil((max - min) / (3.5 * deviation(values) * Math.pow(values.length, -1 / 3)));
  3918. };
  3919. var max = function(values, valueof) {
  3920. var n = values.length,
  3921. i = -1,
  3922. value,
  3923. max;
  3924. if (valueof == null) {
  3925. while (++i < n) { // Find the first comparable value.
  3926. if ((value = values[i]) != null && value >= value) {
  3927. max = value;
  3928. while (++i < n) { // Compare the remaining values.
  3929. if ((value = values[i]) != null && value > max) {
  3930. max = value;
  3931. }
  3932. }
  3933. }
  3934. }
  3935. }
  3936. else {
  3937. while (++i < n) { // Find the first comparable value.
  3938. if ((value = valueof(values[i], i, values)) != null && value >= value) {
  3939. max = value;
  3940. while (++i < n) { // Compare the remaining values.
  3941. if ((value = valueof(values[i], i, values)) != null && value > max) {
  3942. max = value;
  3943. }
  3944. }
  3945. }
  3946. }
  3947. }
  3948. return max;
  3949. };
  3950. var mean = function(values, valueof) {
  3951. var n = values.length,
  3952. m = n,
  3953. i = -1,
  3954. value,
  3955. sum = 0;
  3956. if (valueof == null) {
  3957. while (++i < n) {
  3958. if (!isNaN(value = number(values[i]))) sum += value;
  3959. else --m;
  3960. }
  3961. }
  3962. else {
  3963. while (++i < n) {
  3964. if (!isNaN(value = number(valueof(values[i], i, values)))) sum += value;
  3965. else --m;
  3966. }
  3967. }
  3968. if (m) return sum / m;
  3969. };
  3970. var median = function(values, valueof) {
  3971. var n = values.length,
  3972. i = -1,
  3973. value,
  3974. numbers = [];
  3975. if (valueof == null) {
  3976. while (++i < n) {
  3977. if (!isNaN(value = number(values[i]))) {
  3978. numbers.push(value);
  3979. }
  3980. }
  3981. }
  3982. else {
  3983. while (++i < n) {
  3984. if (!isNaN(value = number(valueof(values[i], i, values)))) {
  3985. numbers.push(value);
  3986. }
  3987. }
  3988. }
  3989. return quantile(numbers.sort(ascending), 0.5);
  3990. };
  3991. var merge = function(arrays) {
  3992. var n = arrays.length,
  3993. m,
  3994. i = -1,
  3995. j = 0,
  3996. merged,
  3997. array;
  3998. while (++i < n) j += arrays[i].length;
  3999. merged = new Array(j);
  4000. while (--n >= 0) {
  4001. array = arrays[n];
  4002. m = array.length;
  4003. while (--m >= 0) {
  4004. merged[--j] = array[m];
  4005. }
  4006. }
  4007. return merged;
  4008. };
  4009. var min = function(values, valueof) {
  4010. var n = values.length,
  4011. i = -1,
  4012. value,
  4013. min;
  4014. if (valueof == null) {
  4015. while (++i < n) { // Find the first comparable value.
  4016. if ((value = values[i]) != null && value >= value) {
  4017. min = value;
  4018. while (++i < n) { // Compare the remaining values.
  4019. if ((value = values[i]) != null && min > value) {
  4020. min = value;
  4021. }
  4022. }
  4023. }
  4024. }
  4025. }
  4026. else {
  4027. while (++i < n) { // Find the first comparable value.
  4028. if ((value = valueof(values[i], i, values)) != null && value >= value) {
  4029. min = value;
  4030. while (++i < n) { // Compare the remaining values.
  4031. if ((value = valueof(values[i], i, values)) != null && min > value) {
  4032. min = value;
  4033. }
  4034. }
  4035. }
  4036. }
  4037. }
  4038. return min;
  4039. };
  4040. var permute = function(array, indexes) {
  4041. var i = indexes.length, permutes = new Array(i);
  4042. while (i--) permutes[i] = array[indexes[i]];
  4043. return permutes;
  4044. };
  4045. var scan = function(values, compare) {
  4046. if (!(n = values.length)) return;
  4047. var n,
  4048. i = 0,
  4049. j = 0,
  4050. xi,
  4051. xj = values[j];
  4052. if (compare == null) compare = ascending;
  4053. while (++i < n) {
  4054. if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {
  4055. xj = xi, j = i;
  4056. }
  4057. }
  4058. if (compare(xj, xj) === 0) return j;
  4059. };
  4060. var shuffle = function(array, i0, i1) {
  4061. var m = (i1 == null ? array.length : i1) - (i0 = i0 == null ? 0 : +i0),
  4062. t,
  4063. i;
  4064. while (m) {
  4065. i = Math.random() * m-- | 0;
  4066. t = array[m + i0];
  4067. array[m + i0] = array[i + i0];
  4068. array[i + i0] = t;
  4069. }
  4070. return array;
  4071. };
  4072. var sum = function(values, valueof) {
  4073. var n = values.length,
  4074. i = -1,
  4075. value,
  4076. sum = 0;
  4077. if (valueof == null) {
  4078. while (++i < n) {
  4079. if (value = +values[i]) sum += value; // Note: zero and null are equivalent.
  4080. }
  4081. }
  4082. else {
  4083. while (++i < n) {
  4084. if (value = +valueof(values[i], i, values)) sum += value;
  4085. }
  4086. }
  4087. return sum;
  4088. };
  4089. var transpose = function(matrix) {
  4090. if (!(n = matrix.length)) return [];
  4091. for (var i = -1, m = min(matrix, length), transpose = new Array(m); ++i < m;) {
  4092. for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) {
  4093. row[j] = matrix[j][i];
  4094. }
  4095. }
  4096. return transpose;
  4097. };
  4098. function length(d) {
  4099. return d.length;
  4100. }
  4101. var zip = function() {
  4102. return transpose(arguments);
  4103. };
  4104. exports.bisect = bisectRight;
  4105. exports.bisectRight = bisectRight;
  4106. exports.bisectLeft = bisectLeft;
  4107. exports.ascending = ascending;
  4108. exports.bisector = bisector;
  4109. exports.cross = cross;
  4110. exports.descending = descending;
  4111. exports.deviation = deviation;
  4112. exports.extent = extent;
  4113. exports.histogram = histogram;
  4114. exports.thresholdFreedmanDiaconis = freedmanDiaconis;
  4115. exports.thresholdScott = scott;
  4116. exports.thresholdSturges = sturges;
  4117. exports.max = max;
  4118. exports.mean = mean;
  4119. exports.median = median;
  4120. exports.merge = merge;
  4121. exports.min = min;
  4122. exports.pairs = pairs;
  4123. exports.permute = permute;
  4124. exports.quantile = quantile;
  4125. exports.range = range;
  4126. exports.scan = scan;
  4127. exports.shuffle = shuffle;
  4128. exports.sum = sum;
  4129. exports.ticks = ticks;
  4130. exports.tickIncrement = tickIncrement;
  4131. exports.tickStep = tickStep;
  4132. exports.transpose = transpose;
  4133. exports.variance = variance;
  4134. exports.zip = zip;
  4135. Object.defineProperty(exports, '__esModule', { value: true });
  4136. })));
  4137. },{}],40:[function(require,module,exports){
  4138. // https://d3js.org/d3-axis/ Version 1.0.8. Copyright 2017 Mike Bostock.
  4139. (function (global, factory) {
  4140. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4141. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4142. (factory((global.d3 = global.d3 || {})));
  4143. }(this, (function (exports) { 'use strict';
  4144. var slice = Array.prototype.slice;
  4145. var identity = function(x) {
  4146. return x;
  4147. };
  4148. var top = 1;
  4149. var right = 2;
  4150. var bottom = 3;
  4151. var left = 4;
  4152. var epsilon = 1e-6;
  4153. function translateX(x) {
  4154. return "translate(" + (x + 0.5) + ",0)";
  4155. }
  4156. function translateY(y) {
  4157. return "translate(0," + (y + 0.5) + ")";
  4158. }
  4159. function number(scale) {
  4160. return function(d) {
  4161. return +scale(d);
  4162. };
  4163. }
  4164. function center(scale) {
  4165. var offset = Math.max(0, scale.bandwidth() - 1) / 2; // Adjust for 0.5px offset.
  4166. if (scale.round()) offset = Math.round(offset);
  4167. return function(d) {
  4168. return +scale(d) + offset;
  4169. };
  4170. }
  4171. function entering() {
  4172. return !this.__axis;
  4173. }
  4174. function axis(orient, scale) {
  4175. var tickArguments = [],
  4176. tickValues = null,
  4177. tickFormat = null,
  4178. tickSizeInner = 6,
  4179. tickSizeOuter = 6,
  4180. tickPadding = 3,
  4181. k = orient === top || orient === left ? -1 : 1,
  4182. x = orient === left || orient === right ? "x" : "y",
  4183. transform = orient === top || orient === bottom ? translateX : translateY;
  4184. function axis(context) {
  4185. var values = tickValues == null ? (scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain()) : tickValues,
  4186. format = tickFormat == null ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity) : tickFormat,
  4187. spacing = Math.max(tickSizeInner, 0) + tickPadding,
  4188. range = scale.range(),
  4189. range0 = +range[0] + 0.5,
  4190. range1 = +range[range.length - 1] + 0.5,
  4191. position = (scale.bandwidth ? center : number)(scale.copy()),
  4192. selection = context.selection ? context.selection() : context,
  4193. path = selection.selectAll(".domain").data([null]),
  4194. tick = selection.selectAll(".tick").data(values, scale).order(),
  4195. tickExit = tick.exit(),
  4196. tickEnter = tick.enter().append("g").attr("class", "tick"),
  4197. line = tick.select("line"),
  4198. text = tick.select("text");
  4199. path = path.merge(path.enter().insert("path", ".tick")
  4200. .attr("class", "domain")
  4201. .attr("stroke", "#000"));
  4202. tick = tick.merge(tickEnter);
  4203. line = line.merge(tickEnter.append("line")
  4204. .attr("stroke", "#000")
  4205. .attr(x + "2", k * tickSizeInner));
  4206. text = text.merge(tickEnter.append("text")
  4207. .attr("fill", "#000")
  4208. .attr(x, k * spacing)
  4209. .attr("dy", orient === top ? "0em" : orient === bottom ? "0.71em" : "0.32em"));
  4210. if (context !== selection) {
  4211. path = path.transition(context);
  4212. tick = tick.transition(context);
  4213. line = line.transition(context);
  4214. text = text.transition(context);
  4215. tickExit = tickExit.transition(context)
  4216. .attr("opacity", epsilon)
  4217. .attr("transform", function(d) { return isFinite(d = position(d)) ? transform(d) : this.getAttribute("transform"); });
  4218. tickEnter
  4219. .attr("opacity", epsilon)
  4220. .attr("transform", function(d) { var p = this.parentNode.__axis; return transform(p && isFinite(p = p(d)) ? p : position(d)); });
  4221. }
  4222. tickExit.remove();
  4223. path
  4224. .attr("d", orient === left || orient == right
  4225. ? "M" + k * tickSizeOuter + "," + range0 + "H0.5V" + range1 + "H" + k * tickSizeOuter
  4226. : "M" + range0 + "," + k * tickSizeOuter + "V0.5H" + range1 + "V" + k * tickSizeOuter);
  4227. tick
  4228. .attr("opacity", 1)
  4229. .attr("transform", function(d) { return transform(position(d)); });
  4230. line
  4231. .attr(x + "2", k * tickSizeInner);
  4232. text
  4233. .attr(x, k * spacing)
  4234. .text(format);
  4235. selection.filter(entering)
  4236. .attr("fill", "none")
  4237. .attr("font-size", 10)
  4238. .attr("font-family", "sans-serif")
  4239. .attr("text-anchor", orient === right ? "start" : orient === left ? "end" : "middle");
  4240. selection
  4241. .each(function() { this.__axis = position; });
  4242. }
  4243. axis.scale = function(_) {
  4244. return arguments.length ? (scale = _, axis) : scale;
  4245. };
  4246. axis.ticks = function() {
  4247. return tickArguments = slice.call(arguments), axis;
  4248. };
  4249. axis.tickArguments = function(_) {
  4250. return arguments.length ? (tickArguments = _ == null ? [] : slice.call(_), axis) : tickArguments.slice();
  4251. };
  4252. axis.tickValues = function(_) {
  4253. return arguments.length ? (tickValues = _ == null ? null : slice.call(_), axis) : tickValues && tickValues.slice();
  4254. };
  4255. axis.tickFormat = function(_) {
  4256. return arguments.length ? (tickFormat = _, axis) : tickFormat;
  4257. };
  4258. axis.tickSize = function(_) {
  4259. return arguments.length ? (tickSizeInner = tickSizeOuter = +_, axis) : tickSizeInner;
  4260. };
  4261. axis.tickSizeInner = function(_) {
  4262. return arguments.length ? (tickSizeInner = +_, axis) : tickSizeInner;
  4263. };
  4264. axis.tickSizeOuter = function(_) {
  4265. return arguments.length ? (tickSizeOuter = +_, axis) : tickSizeOuter;
  4266. };
  4267. axis.tickPadding = function(_) {
  4268. return arguments.length ? (tickPadding = +_, axis) : tickPadding;
  4269. };
  4270. return axis;
  4271. }
  4272. function axisTop(scale) {
  4273. return axis(top, scale);
  4274. }
  4275. function axisRight(scale) {
  4276. return axis(right, scale);
  4277. }
  4278. function axisBottom(scale) {
  4279. return axis(bottom, scale);
  4280. }
  4281. function axisLeft(scale) {
  4282. return axis(left, scale);
  4283. }
  4284. exports.axisTop = axisTop;
  4285. exports.axisRight = axisRight;
  4286. exports.axisBottom = axisBottom;
  4287. exports.axisLeft = axisLeft;
  4288. Object.defineProperty(exports, '__esModule', { value: true });
  4289. })));
  4290. },{}],41:[function(require,module,exports){
  4291. // https://d3js.org/d3-brush/ Version 1.0.4. Copyright 2017 Mike Bostock.
  4292. (function (global, factory) {
  4293. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-dispatch'), require('d3-drag'), require('d3-interpolate'), require('d3-selection'), require('d3-transition')) :
  4294. typeof define === 'function' && define.amd ? define(['exports', 'd3-dispatch', 'd3-drag', 'd3-interpolate', 'd3-selection', 'd3-transition'], factory) :
  4295. (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3,global.d3));
  4296. }(this, (function (exports,d3Dispatch,d3Drag,d3Interpolate,d3Selection,d3Transition) { 'use strict';
  4297. var constant = function(x) {
  4298. return function() {
  4299. return x;
  4300. };
  4301. };
  4302. var BrushEvent = function(target, type, selection) {
  4303. this.target = target;
  4304. this.type = type;
  4305. this.selection = selection;
  4306. };
  4307. function nopropagation() {
  4308. d3Selection.event.stopImmediatePropagation();
  4309. }
  4310. var noevent = function() {
  4311. d3Selection.event.preventDefault();
  4312. d3Selection.event.stopImmediatePropagation();
  4313. };
  4314. var MODE_DRAG = {name: "drag"};
  4315. var MODE_SPACE = {name: "space"};
  4316. var MODE_HANDLE = {name: "handle"};
  4317. var MODE_CENTER = {name: "center"};
  4318. var X = {
  4319. name: "x",
  4320. handles: ["e", "w"].map(type),
  4321. input: function(x, e) { return x && [[x[0], e[0][1]], [x[1], e[1][1]]]; },
  4322. output: function(xy) { return xy && [xy[0][0], xy[1][0]]; }
  4323. };
  4324. var Y = {
  4325. name: "y",
  4326. handles: ["n", "s"].map(type),
  4327. input: function(y, e) { return y && [[e[0][0], y[0]], [e[1][0], y[1]]]; },
  4328. output: function(xy) { return xy && [xy[0][1], xy[1][1]]; }
  4329. };
  4330. var XY = {
  4331. name: "xy",
  4332. handles: ["n", "e", "s", "w", "nw", "ne", "se", "sw"].map(type),
  4333. input: function(xy) { return xy; },
  4334. output: function(xy) { return xy; }
  4335. };
  4336. var cursors = {
  4337. overlay: "crosshair",
  4338. selection: "move",
  4339. n: "ns-resize",
  4340. e: "ew-resize",
  4341. s: "ns-resize",
  4342. w: "ew-resize",
  4343. nw: "nwse-resize",
  4344. ne: "nesw-resize",
  4345. se: "nwse-resize",
  4346. sw: "nesw-resize"
  4347. };
  4348. var flipX = {
  4349. e: "w",
  4350. w: "e",
  4351. nw: "ne",
  4352. ne: "nw",
  4353. se: "sw",
  4354. sw: "se"
  4355. };
  4356. var flipY = {
  4357. n: "s",
  4358. s: "n",
  4359. nw: "sw",
  4360. ne: "se",
  4361. se: "ne",
  4362. sw: "nw"
  4363. };
  4364. var signsX = {
  4365. overlay: +1,
  4366. selection: +1,
  4367. n: null,
  4368. e: +1,
  4369. s: null,
  4370. w: -1,
  4371. nw: -1,
  4372. ne: +1,
  4373. se: +1,
  4374. sw: -1
  4375. };
  4376. var signsY = {
  4377. overlay: +1,
  4378. selection: +1,
  4379. n: -1,
  4380. e: null,
  4381. s: +1,
  4382. w: null,
  4383. nw: -1,
  4384. ne: -1,
  4385. se: +1,
  4386. sw: +1
  4387. };
  4388. function type(t) {
  4389. return {type: t};
  4390. }
  4391. // Ignore right-click, since that should open the context menu.
  4392. function defaultFilter() {
  4393. return !d3Selection.event.button;
  4394. }
  4395. function defaultExtent() {
  4396. var svg = this.ownerSVGElement || this;
  4397. return [[0, 0], [svg.width.baseVal.value, svg.height.baseVal.value]];
  4398. }
  4399. // Like d3.local, but with the name “__brush” rather than auto-generated.
  4400. function local(node) {
  4401. while (!node.__brush) if (!(node = node.parentNode)) return;
  4402. return node.__brush;
  4403. }
  4404. function empty(extent) {
  4405. return extent[0][0] === extent[1][0]
  4406. || extent[0][1] === extent[1][1];
  4407. }
  4408. function brushSelection(node) {
  4409. var state = node.__brush;
  4410. return state ? state.dim.output(state.selection) : null;
  4411. }
  4412. function brushX() {
  4413. return brush$1(X);
  4414. }
  4415. function brushY() {
  4416. return brush$1(Y);
  4417. }
  4418. var brush = function() {
  4419. return brush$1(XY);
  4420. };
  4421. function brush$1(dim) {
  4422. var extent = defaultExtent,
  4423. filter = defaultFilter,
  4424. listeners = d3Dispatch.dispatch(brush, "start", "brush", "end"),
  4425. handleSize = 6,
  4426. touchending;
  4427. function brush(group) {
  4428. var overlay = group
  4429. .property("__brush", initialize)
  4430. .selectAll(".overlay")
  4431. .data([type("overlay")]);
  4432. overlay.enter().append("rect")
  4433. .attr("class", "overlay")
  4434. .attr("pointer-events", "all")
  4435. .attr("cursor", cursors.overlay)
  4436. .merge(overlay)
  4437. .each(function() {
  4438. var extent = local(this).extent;
  4439. d3Selection.select(this)
  4440. .attr("x", extent[0][0])
  4441. .attr("y", extent[0][1])
  4442. .attr("width", extent[1][0] - extent[0][0])
  4443. .attr("height", extent[1][1] - extent[0][1]);
  4444. });
  4445. group.selectAll(".selection")
  4446. .data([type("selection")])
  4447. .enter().append("rect")
  4448. .attr("class", "selection")
  4449. .attr("cursor", cursors.selection)
  4450. .attr("fill", "#777")
  4451. .attr("fill-opacity", 0.3)
  4452. .attr("stroke", "#fff")
  4453. .attr("shape-rendering", "crispEdges");
  4454. var handle = group.selectAll(".handle")
  4455. .data(dim.handles, function(d) { return d.type; });
  4456. handle.exit().remove();
  4457. handle.enter().append("rect")
  4458. .attr("class", function(d) { return "handle handle--" + d.type; })
  4459. .attr("cursor", function(d) { return cursors[d.type]; });
  4460. group
  4461. .each(redraw)
  4462. .attr("fill", "none")
  4463. .attr("pointer-events", "all")
  4464. .style("-webkit-tap-highlight-color", "rgba(0,0,0,0)")
  4465. .on("mousedown.brush touchstart.brush", started);
  4466. }
  4467. brush.move = function(group, selection) {
  4468. if (group.selection) {
  4469. group
  4470. .on("start.brush", function() { emitter(this, arguments).beforestart().start(); })
  4471. .on("interrupt.brush end.brush", function() { emitter(this, arguments).end(); })
  4472. .tween("brush", function() {
  4473. var that = this,
  4474. state = that.__brush,
  4475. emit = emitter(that, arguments),
  4476. selection0 = state.selection,
  4477. selection1 = dim.input(typeof selection === "function" ? selection.apply(this, arguments) : selection, state.extent),
  4478. i = d3Interpolate.interpolate(selection0, selection1);
  4479. function tween(t) {
  4480. state.selection = t === 1 && empty(selection1) ? null : i(t);
  4481. redraw.call(that);
  4482. emit.brush();
  4483. }
  4484. return selection0 && selection1 ? tween : tween(1);
  4485. });
  4486. } else {
  4487. group
  4488. .each(function() {
  4489. var that = this,
  4490. args = arguments,
  4491. state = that.__brush,
  4492. selection1 = dim.input(typeof selection === "function" ? selection.apply(that, args) : selection, state.extent),
  4493. emit = emitter(that, args).beforestart();
  4494. d3Transition.interrupt(that);
  4495. state.selection = selection1 == null || empty(selection1) ? null : selection1;
  4496. redraw.call(that);
  4497. emit.start().brush().end();
  4498. });
  4499. }
  4500. };
  4501. function redraw() {
  4502. var group = d3Selection.select(this),
  4503. selection = local(this).selection;
  4504. if (selection) {
  4505. group.selectAll(".selection")
  4506. .style("display", null)
  4507. .attr("x", selection[0][0])
  4508. .attr("y", selection[0][1])
  4509. .attr("width", selection[1][0] - selection[0][0])
  4510. .attr("height", selection[1][1] - selection[0][1]);
  4511. group.selectAll(".handle")
  4512. .style("display", null)
  4513. .attr("x", function(d) { return d.type[d.type.length - 1] === "e" ? selection[1][0] - handleSize / 2 : selection[0][0] - handleSize / 2; })
  4514. .attr("y", function(d) { return d.type[0] === "s" ? selection[1][1] - handleSize / 2 : selection[0][1] - handleSize / 2; })
  4515. .attr("width", function(d) { return d.type === "n" || d.type === "s" ? selection[1][0] - selection[0][0] + handleSize : handleSize; })
  4516. .attr("height", function(d) { return d.type === "e" || d.type === "w" ? selection[1][1] - selection[0][1] + handleSize : handleSize; });
  4517. }
  4518. else {
  4519. group.selectAll(".selection,.handle")
  4520. .style("display", "none")
  4521. .attr("x", null)
  4522. .attr("y", null)
  4523. .attr("width", null)
  4524. .attr("height", null);
  4525. }
  4526. }
  4527. function emitter(that, args) {
  4528. return that.__brush.emitter || new Emitter(that, args);
  4529. }
  4530. function Emitter(that, args) {
  4531. this.that = that;
  4532. this.args = args;
  4533. this.state = that.__brush;
  4534. this.active = 0;
  4535. }
  4536. Emitter.prototype = {
  4537. beforestart: function() {
  4538. if (++this.active === 1) this.state.emitter = this, this.starting = true;
  4539. return this;
  4540. },
  4541. start: function() {
  4542. if (this.starting) this.starting = false, this.emit("start");
  4543. return this;
  4544. },
  4545. brush: function() {
  4546. this.emit("brush");
  4547. return this;
  4548. },
  4549. end: function() {
  4550. if (--this.active === 0) delete this.state.emitter, this.emit("end");
  4551. return this;
  4552. },
  4553. emit: function(type) {
  4554. d3Selection.customEvent(new BrushEvent(brush, type, dim.output(this.state.selection)), listeners.apply, listeners, [type, this.that, this.args]);
  4555. }
  4556. };
  4557. function started() {
  4558. if (d3Selection.event.touches) { if (d3Selection.event.changedTouches.length < d3Selection.event.touches.length) return noevent(); }
  4559. else if (touchending) return;
  4560. if (!filter.apply(this, arguments)) return;
  4561. var that = this,
  4562. type = d3Selection.event.target.__data__.type,
  4563. mode = (d3Selection.event.metaKey ? type = "overlay" : type) === "selection" ? MODE_DRAG : (d3Selection.event.altKey ? MODE_CENTER : MODE_HANDLE),
  4564. signX = dim === Y ? null : signsX[type],
  4565. signY = dim === X ? null : signsY[type],
  4566. state = local(that),
  4567. extent = state.extent,
  4568. selection = state.selection,
  4569. W = extent[0][0], w0, w1,
  4570. N = extent[0][1], n0, n1,
  4571. E = extent[1][0], e0, e1,
  4572. S = extent[1][1], s0, s1,
  4573. dx,
  4574. dy,
  4575. moving,
  4576. shifting = signX && signY && d3Selection.event.shiftKey,
  4577. lockX,
  4578. lockY,
  4579. point0 = d3Selection.mouse(that),
  4580. point = point0,
  4581. emit = emitter(that, arguments).beforestart();
  4582. if (type === "overlay") {
  4583. state.selection = selection = [
  4584. [w0 = dim === Y ? W : point0[0], n0 = dim === X ? N : point0[1]],
  4585. [e0 = dim === Y ? E : w0, s0 = dim === X ? S : n0]
  4586. ];
  4587. } else {
  4588. w0 = selection[0][0];
  4589. n0 = selection[0][1];
  4590. e0 = selection[1][0];
  4591. s0 = selection[1][1];
  4592. }
  4593. w1 = w0;
  4594. n1 = n0;
  4595. e1 = e0;
  4596. s1 = s0;
  4597. var group = d3Selection.select(that)
  4598. .attr("pointer-events", "none");
  4599. var overlay = group.selectAll(".overlay")
  4600. .attr("cursor", cursors[type]);
  4601. if (d3Selection.event.touches) {
  4602. group
  4603. .on("touchmove.brush", moved, true)
  4604. .on("touchend.brush touchcancel.brush", ended, true);
  4605. } else {
  4606. var view = d3Selection.select(d3Selection.event.view)
  4607. .on("keydown.brush", keydowned, true)
  4608. .on("keyup.brush", keyupped, true)
  4609. .on("mousemove.brush", moved, true)
  4610. .on("mouseup.brush", ended, true);
  4611. d3Drag.dragDisable(d3Selection.event.view);
  4612. }
  4613. nopropagation();
  4614. d3Transition.interrupt(that);
  4615. redraw.call(that);
  4616. emit.start();
  4617. function moved() {
  4618. var point1 = d3Selection.mouse(that);
  4619. if (shifting && !lockX && !lockY) {
  4620. if (Math.abs(point1[0] - point[0]) > Math.abs(point1[1] - point[1])) lockY = true;
  4621. else lockX = true;
  4622. }
  4623. point = point1;
  4624. moving = true;
  4625. noevent();
  4626. move();
  4627. }
  4628. function move() {
  4629. var t;
  4630. dx = point[0] - point0[0];
  4631. dy = point[1] - point0[1];
  4632. switch (mode) {
  4633. case MODE_SPACE:
  4634. case MODE_DRAG: {
  4635. if (signX) dx = Math.max(W - w0, Math.min(E - e0, dx)), w1 = w0 + dx, e1 = e0 + dx;
  4636. if (signY) dy = Math.max(N - n0, Math.min(S - s0, dy)), n1 = n0 + dy, s1 = s0 + dy;
  4637. break;
  4638. }
  4639. case MODE_HANDLE: {
  4640. if (signX < 0) dx = Math.max(W - w0, Math.min(E - w0, dx)), w1 = w0 + dx, e1 = e0;
  4641. else if (signX > 0) dx = Math.max(W - e0, Math.min(E - e0, dx)), w1 = w0, e1 = e0 + dx;
  4642. if (signY < 0) dy = Math.max(N - n0, Math.min(S - n0, dy)), n1 = n0 + dy, s1 = s0;
  4643. else if (signY > 0) dy = Math.max(N - s0, Math.min(S - s0, dy)), n1 = n0, s1 = s0 + dy;
  4644. break;
  4645. }
  4646. case MODE_CENTER: {
  4647. if (signX) w1 = Math.max(W, Math.min(E, w0 - dx * signX)), e1 = Math.max(W, Math.min(E, e0 + dx * signX));
  4648. if (signY) n1 = Math.max(N, Math.min(S, n0 - dy * signY)), s1 = Math.max(N, Math.min(S, s0 + dy * signY));
  4649. break;
  4650. }
  4651. }
  4652. if (e1 < w1) {
  4653. signX *= -1;
  4654. t = w0, w0 = e0, e0 = t;
  4655. t = w1, w1 = e1, e1 = t;
  4656. if (type in flipX) overlay.attr("cursor", cursors[type = flipX[type]]);
  4657. }
  4658. if (s1 < n1) {
  4659. signY *= -1;
  4660. t = n0, n0 = s0, s0 = t;
  4661. t = n1, n1 = s1, s1 = t;
  4662. if (type in flipY) overlay.attr("cursor", cursors[type = flipY[type]]);
  4663. }
  4664. if (state.selection) selection = state.selection; // May be set by brush.move!
  4665. if (lockX) w1 = selection[0][0], e1 = selection[1][0];
  4666. if (lockY) n1 = selection[0][1], s1 = selection[1][1];
  4667. if (selection[0][0] !== w1
  4668. || selection[0][1] !== n1
  4669. || selection[1][0] !== e1
  4670. || selection[1][1] !== s1) {
  4671. state.selection = [[w1, n1], [e1, s1]];
  4672. redraw.call(that);
  4673. emit.brush();
  4674. }
  4675. }
  4676. function ended() {
  4677. nopropagation();
  4678. if (d3Selection.event.touches) {
  4679. if (d3Selection.event.touches.length) return;
  4680. if (touchending) clearTimeout(touchending);
  4681. touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed!
  4682. group.on("touchmove.brush touchend.brush touchcancel.brush", null);
  4683. } else {
  4684. d3Drag.dragEnable(d3Selection.event.view, moving);
  4685. view.on("keydown.brush keyup.brush mousemove.brush mouseup.brush", null);
  4686. }
  4687. group.attr("pointer-events", "all");
  4688. overlay.attr("cursor", cursors.overlay);
  4689. if (state.selection) selection = state.selection; // May be set by brush.move (on start)!
  4690. if (empty(selection)) state.selection = null, redraw.call(that);
  4691. emit.end();
  4692. }
  4693. function keydowned() {
  4694. switch (d3Selection.event.keyCode) {
  4695. case 16: { // SHIFT
  4696. shifting = signX && signY;
  4697. break;
  4698. }
  4699. case 18: { // ALT
  4700. if (mode === MODE_HANDLE) {
  4701. if (signX) e0 = e1 - dx * signX, w0 = w1 + dx * signX;
  4702. if (signY) s0 = s1 - dy * signY, n0 = n1 + dy * signY;
  4703. mode = MODE_CENTER;
  4704. move();
  4705. }
  4706. break;
  4707. }
  4708. case 32: { // SPACE; takes priority over ALT
  4709. if (mode === MODE_HANDLE || mode === MODE_CENTER) {
  4710. if (signX < 0) e0 = e1 - dx; else if (signX > 0) w0 = w1 - dx;
  4711. if (signY < 0) s0 = s1 - dy; else if (signY > 0) n0 = n1 - dy;
  4712. mode = MODE_SPACE;
  4713. overlay.attr("cursor", cursors.selection);
  4714. move();
  4715. }
  4716. break;
  4717. }
  4718. default: return;
  4719. }
  4720. noevent();
  4721. }
  4722. function keyupped() {
  4723. switch (d3Selection.event.keyCode) {
  4724. case 16: { // SHIFT
  4725. if (shifting) {
  4726. lockX = lockY = shifting = false;
  4727. move();
  4728. }
  4729. break;
  4730. }
  4731. case 18: { // ALT
  4732. if (mode === MODE_CENTER) {
  4733. if (signX < 0) e0 = e1; else if (signX > 0) w0 = w1;
  4734. if (signY < 0) s0 = s1; else if (signY > 0) n0 = n1;
  4735. mode = MODE_HANDLE;
  4736. move();
  4737. }
  4738. break;
  4739. }
  4740. case 32: { // SPACE
  4741. if (mode === MODE_SPACE) {
  4742. if (d3Selection.event.altKey) {
  4743. if (signX) e0 = e1 - dx * signX, w0 = w1 + dx * signX;
  4744. if (signY) s0 = s1 - dy * signY, n0 = n1 + dy * signY;
  4745. mode = MODE_CENTER;
  4746. } else {
  4747. if (signX < 0) e0 = e1; else if (signX > 0) w0 = w1;
  4748. if (signY < 0) s0 = s1; else if (signY > 0) n0 = n1;
  4749. mode = MODE_HANDLE;
  4750. }
  4751. overlay.attr("cursor", cursors[type]);
  4752. move();
  4753. }
  4754. break;
  4755. }
  4756. default: return;
  4757. }
  4758. noevent();
  4759. }
  4760. }
  4761. function initialize() {
  4762. var state = this.__brush || {selection: null};
  4763. state.extent = extent.apply(this, arguments);
  4764. state.dim = dim;
  4765. return state;
  4766. }
  4767. brush.extent = function(_) {
  4768. return arguments.length ? (extent = typeof _ === "function" ? _ : constant([[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]]), brush) : extent;
  4769. };
  4770. brush.filter = function(_) {
  4771. return arguments.length ? (filter = typeof _ === "function" ? _ : constant(!!_), brush) : filter;
  4772. };
  4773. brush.handleSize = function(_) {
  4774. return arguments.length ? (handleSize = +_, brush) : handleSize;
  4775. };
  4776. brush.on = function() {
  4777. var value = listeners.on.apply(listeners, arguments);
  4778. return value === listeners ? brush : value;
  4779. };
  4780. return brush;
  4781. }
  4782. exports.brush = brush;
  4783. exports.brushX = brushX;
  4784. exports.brushY = brushY;
  4785. exports.brushSelection = brushSelection;
  4786. Object.defineProperty(exports, '__esModule', { value: true });
  4787. })));
  4788. },{"d3-dispatch":45,"d3-drag":46,"d3-interpolate":53,"d3-selection":61,"d3-transition":66}],42:[function(require,module,exports){
  4789. // https://d3js.org/d3-chord/ Version 1.0.4. Copyright 2017 Mike Bostock.
  4790. (function (global, factory) {
  4791. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-array'), require('d3-path')) :
  4792. typeof define === 'function' && define.amd ? define(['exports', 'd3-array', 'd3-path'], factory) :
  4793. (factory((global.d3 = global.d3 || {}),global.d3,global.d3));
  4794. }(this, (function (exports,d3Array,d3Path) { 'use strict';
  4795. var cos = Math.cos;
  4796. var sin = Math.sin;
  4797. var pi = Math.PI;
  4798. var halfPi = pi / 2;
  4799. var tau = pi * 2;
  4800. var max = Math.max;
  4801. function compareValue(compare) {
  4802. return function(a, b) {
  4803. return compare(
  4804. a.source.value + a.target.value,
  4805. b.source.value + b.target.value
  4806. );
  4807. };
  4808. }
  4809. var chord = function() {
  4810. var padAngle = 0,
  4811. sortGroups = null,
  4812. sortSubgroups = null,
  4813. sortChords = null;
  4814. function chord(matrix) {
  4815. var n = matrix.length,
  4816. groupSums = [],
  4817. groupIndex = d3Array.range(n),
  4818. subgroupIndex = [],
  4819. chords = [],
  4820. groups = chords.groups = new Array(n),
  4821. subgroups = new Array(n * n),
  4822. k,
  4823. x,
  4824. x0,
  4825. dx,
  4826. i,
  4827. j;
  4828. // Compute the sum.
  4829. k = 0, i = -1; while (++i < n) {
  4830. x = 0, j = -1; while (++j < n) {
  4831. x += matrix[i][j];
  4832. }
  4833. groupSums.push(x);
  4834. subgroupIndex.push(d3Array.range(n));
  4835. k += x;
  4836. }
  4837. // Sort groups…
  4838. if (sortGroups) groupIndex.sort(function(a, b) {
  4839. return sortGroups(groupSums[a], groupSums[b]);
  4840. });
  4841. // Sort subgroups…
  4842. if (sortSubgroups) subgroupIndex.forEach(function(d, i) {
  4843. d.sort(function(a, b) {
  4844. return sortSubgroups(matrix[i][a], matrix[i][b]);
  4845. });
  4846. });
  4847. // Convert the sum to scaling factor for [0, 2pi].
  4848. // TODO Allow start and end angle to be specified?
  4849. // TODO Allow padding to be specified as percentage?
  4850. k = max(0, tau - padAngle * n) / k;
  4851. dx = k ? padAngle : tau / n;
  4852. // Compute the start and end angle for each group and subgroup.
  4853. // Note: Opera has a bug reordering object literal properties!
  4854. x = 0, i = -1; while (++i < n) {
  4855. x0 = x, j = -1; while (++j < n) {
  4856. var di = groupIndex[i],
  4857. dj = subgroupIndex[di][j],
  4858. v = matrix[di][dj],
  4859. a0 = x,
  4860. a1 = x += v * k;
  4861. subgroups[dj * n + di] = {
  4862. index: di,
  4863. subindex: dj,
  4864. startAngle: a0,
  4865. endAngle: a1,
  4866. value: v
  4867. };
  4868. }
  4869. groups[di] = {
  4870. index: di,
  4871. startAngle: x0,
  4872. endAngle: x,
  4873. value: groupSums[di]
  4874. };
  4875. x += dx;
  4876. }
  4877. // Generate chords for each (non-empty) subgroup-subgroup link.
  4878. i = -1; while (++i < n) {
  4879. j = i - 1; while (++j < n) {
  4880. var source = subgroups[j * n + i],
  4881. target = subgroups[i * n + j];
  4882. if (source.value || target.value) {
  4883. chords.push(source.value < target.value
  4884. ? {source: target, target: source}
  4885. : {source: source, target: target});
  4886. }
  4887. }
  4888. }
  4889. return sortChords ? chords.sort(sortChords) : chords;
  4890. }
  4891. chord.padAngle = function(_) {
  4892. return arguments.length ? (padAngle = max(0, _), chord) : padAngle;
  4893. };
  4894. chord.sortGroups = function(_) {
  4895. return arguments.length ? (sortGroups = _, chord) : sortGroups;
  4896. };
  4897. chord.sortSubgroups = function(_) {
  4898. return arguments.length ? (sortSubgroups = _, chord) : sortSubgroups;
  4899. };
  4900. chord.sortChords = function(_) {
  4901. return arguments.length ? (_ == null ? sortChords = null : (sortChords = compareValue(_))._ = _, chord) : sortChords && sortChords._;
  4902. };
  4903. return chord;
  4904. };
  4905. var slice = Array.prototype.slice;
  4906. var constant = function(x) {
  4907. return function() {
  4908. return x;
  4909. };
  4910. };
  4911. function defaultSource(d) {
  4912. return d.source;
  4913. }
  4914. function defaultTarget(d) {
  4915. return d.target;
  4916. }
  4917. function defaultRadius(d) {
  4918. return d.radius;
  4919. }
  4920. function defaultStartAngle(d) {
  4921. return d.startAngle;
  4922. }
  4923. function defaultEndAngle(d) {
  4924. return d.endAngle;
  4925. }
  4926. var ribbon = function() {
  4927. var source = defaultSource,
  4928. target = defaultTarget,
  4929. radius = defaultRadius,
  4930. startAngle = defaultStartAngle,
  4931. endAngle = defaultEndAngle,
  4932. context = null;
  4933. function ribbon() {
  4934. var buffer,
  4935. argv = slice.call(arguments),
  4936. s = source.apply(this, argv),
  4937. t = target.apply(this, argv),
  4938. sr = +radius.apply(this, (argv[0] = s, argv)),
  4939. sa0 = startAngle.apply(this, argv) - halfPi,
  4940. sa1 = endAngle.apply(this, argv) - halfPi,
  4941. sx0 = sr * cos(sa0),
  4942. sy0 = sr * sin(sa0),
  4943. tr = +radius.apply(this, (argv[0] = t, argv)),
  4944. ta0 = startAngle.apply(this, argv) - halfPi,
  4945. ta1 = endAngle.apply(this, argv) - halfPi;
  4946. if (!context) context = buffer = d3Path.path();
  4947. context.moveTo(sx0, sy0);
  4948. context.arc(0, 0, sr, sa0, sa1);
  4949. if (sa0 !== ta0 || sa1 !== ta1) { // TODO sr !== tr?
  4950. context.quadraticCurveTo(0, 0, tr * cos(ta0), tr * sin(ta0));
  4951. context.arc(0, 0, tr, ta0, ta1);
  4952. }
  4953. context.quadraticCurveTo(0, 0, sx0, sy0);
  4954. context.closePath();
  4955. if (buffer) return context = null, buffer + "" || null;
  4956. }
  4957. ribbon.radius = function(_) {
  4958. return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), ribbon) : radius;
  4959. };
  4960. ribbon.startAngle = function(_) {
  4961. return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant(+_), ribbon) : startAngle;
  4962. };
  4963. ribbon.endAngle = function(_) {
  4964. return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant(+_), ribbon) : endAngle;
  4965. };
  4966. ribbon.source = function(_) {
  4967. return arguments.length ? (source = _, ribbon) : source;
  4968. };
  4969. ribbon.target = function(_) {
  4970. return arguments.length ? (target = _, ribbon) : target;
  4971. };
  4972. ribbon.context = function(_) {
  4973. return arguments.length ? ((context = _ == null ? null : _), ribbon) : context;
  4974. };
  4975. return ribbon;
  4976. };
  4977. exports.chord = chord;
  4978. exports.ribbon = ribbon;
  4979. Object.defineProperty(exports, '__esModule', { value: true });
  4980. })));
  4981. },{"d3-array":39,"d3-path":54}],43:[function(require,module,exports){
  4982. // https://d3js.org/d3-collection/ Version 1.0.4. Copyright 2017 Mike Bostock.
  4983. (function (global, factory) {
  4984. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4985. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4986. (factory((global.d3 = global.d3 || {})));
  4987. }(this, (function (exports) { 'use strict';
  4988. var prefix = "$";
  4989. function Map() {}
  4990. Map.prototype = map.prototype = {
  4991. constructor: Map,
  4992. has: function(key) {
  4993. return (prefix + key) in this;
  4994. },
  4995. get: function(key) {
  4996. return this[prefix + key];
  4997. },
  4998. set: function(key, value) {
  4999. this[prefix + key] = value;
  5000. return this;
  5001. },
  5002. remove: function(key) {
  5003. var property = prefix + key;
  5004. return property in this && delete this[property];
  5005. },
  5006. clear: function() {
  5007. for (var property in this) if (property[0] === prefix) delete this[property];
  5008. },
  5009. keys: function() {
  5010. var keys = [];
  5011. for (var property in this) if (property[0] === prefix) keys.push(property.slice(1));
  5012. return keys;
  5013. },
  5014. values: function() {
  5015. var values = [];
  5016. for (var property in this) if (property[0] === prefix) values.push(this[property]);
  5017. return values;
  5018. },
  5019. entries: function() {
  5020. var entries = [];
  5021. for (var property in this) if (property[0] === prefix) entries.push({key: property.slice(1), value: this[property]});
  5022. return entries;
  5023. },
  5024. size: function() {
  5025. var size = 0;
  5026. for (var property in this) if (property[0] === prefix) ++size;
  5027. return size;
  5028. },
  5029. empty: function() {
  5030. for (var property in this) if (property[0] === prefix) return false;
  5031. return true;
  5032. },
  5033. each: function(f) {
  5034. for (var property in this) if (property[0] === prefix) f(this[property], property.slice(1), this);
  5035. }
  5036. };
  5037. function map(object, f) {
  5038. var map = new Map;
  5039. // Copy constructor.
  5040. if (object instanceof Map) object.each(function(value, key) { map.set(key, value); });
  5041. // Index array by numeric index or specified key function.
  5042. else if (Array.isArray(object)) {
  5043. var i = -1,
  5044. n = object.length,
  5045. o;
  5046. if (f == null) while (++i < n) map.set(i, object[i]);
  5047. else while (++i < n) map.set(f(o = object[i], i, object), o);
  5048. }
  5049. // Convert object to map.
  5050. else if (object) for (var key in object) map.set(key, object[key]);
  5051. return map;
  5052. }
  5053. var nest = function() {
  5054. var keys = [],
  5055. sortKeys = [],
  5056. sortValues,
  5057. rollup,
  5058. nest;
  5059. function apply(array, depth, createResult, setResult) {
  5060. if (depth >= keys.length) {
  5061. if (sortValues != null) array.sort(sortValues);
  5062. return rollup != null ? rollup(array) : array;
  5063. }
  5064. var i = -1,
  5065. n = array.length,
  5066. key = keys[depth++],
  5067. keyValue,
  5068. value,
  5069. valuesByKey = map(),
  5070. values,
  5071. result = createResult();
  5072. while (++i < n) {
  5073. if (values = valuesByKey.get(keyValue = key(value = array[i]) + "")) {
  5074. values.push(value);
  5075. } else {
  5076. valuesByKey.set(keyValue, [value]);
  5077. }
  5078. }
  5079. valuesByKey.each(function(values, key) {
  5080. setResult(result, key, apply(values, depth, createResult, setResult));
  5081. });
  5082. return result;
  5083. }
  5084. function entries(map$$1, depth) {
  5085. if (++depth > keys.length) return map$$1;
  5086. var array, sortKey = sortKeys[depth - 1];
  5087. if (rollup != null && depth >= keys.length) array = map$$1.entries();
  5088. else array = [], map$$1.each(function(v, k) { array.push({key: k, values: entries(v, depth)}); });
  5089. return sortKey != null ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array;
  5090. }
  5091. return nest = {
  5092. object: function(array) { return apply(array, 0, createObject, setObject); },
  5093. map: function(array) { return apply(array, 0, createMap, setMap); },
  5094. entries: function(array) { return entries(apply(array, 0, createMap, setMap), 0); },
  5095. key: function(d) { keys.push(d); return nest; },
  5096. sortKeys: function(order) { sortKeys[keys.length - 1] = order; return nest; },
  5097. sortValues: function(order) { sortValues = order; return nest; },
  5098. rollup: function(f) { rollup = f; return nest; }
  5099. };
  5100. };
  5101. function createObject() {
  5102. return {};
  5103. }
  5104. function setObject(object, key, value) {
  5105. object[key] = value;
  5106. }
  5107. function createMap() {
  5108. return map();
  5109. }
  5110. function setMap(map$$1, key, value) {
  5111. map$$1.set(key, value);
  5112. }
  5113. function Set() {}
  5114. var proto = map.prototype;
  5115. Set.prototype = set.prototype = {
  5116. constructor: Set,
  5117. has: proto.has,
  5118. add: function(value) {
  5119. value += "";
  5120. this[prefix + value] = value;
  5121. return this;
  5122. },
  5123. remove: proto.remove,
  5124. clear: proto.clear,
  5125. values: proto.keys,
  5126. size: proto.size,
  5127. empty: proto.empty,
  5128. each: proto.each
  5129. };
  5130. function set(object, f) {
  5131. var set = new Set;
  5132. // Copy constructor.
  5133. if (object instanceof Set) object.each(function(value) { set.add(value); });
  5134. // Otherwise, assume it’s an array.
  5135. else if (object) {
  5136. var i = -1, n = object.length;
  5137. if (f == null) while (++i < n) set.add(object[i]);
  5138. else while (++i < n) set.add(f(object[i], i, object));
  5139. }
  5140. return set;
  5141. }
  5142. var keys = function(map) {
  5143. var keys = [];
  5144. for (var key in map) keys.push(key);
  5145. return keys;
  5146. };
  5147. var values = function(map) {
  5148. var values = [];
  5149. for (var key in map) values.push(map[key]);
  5150. return values;
  5151. };
  5152. var entries = function(map) {
  5153. var entries = [];
  5154. for (var key in map) entries.push({key: key, value: map[key]});
  5155. return entries;
  5156. };
  5157. exports.nest = nest;
  5158. exports.set = set;
  5159. exports.map = map;
  5160. exports.keys = keys;
  5161. exports.values = values;
  5162. exports.entries = entries;
  5163. Object.defineProperty(exports, '__esModule', { value: true });
  5164. })));
  5165. },{}],44:[function(require,module,exports){
  5166. // https://d3js.org/d3-color/ Version 1.0.3. Copyright 2017 Mike Bostock.
  5167. (function (global, factory) {
  5168. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  5169. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5170. (factory((global.d3 = global.d3 || {})));
  5171. }(this, (function (exports) { 'use strict';
  5172. var define = function(constructor, factory, prototype) {
  5173. constructor.prototype = factory.prototype = prototype;
  5174. prototype.constructor = constructor;
  5175. };
  5176. function extend(parent, definition) {
  5177. var prototype = Object.create(parent.prototype);
  5178. for (var key in definition) prototype[key] = definition[key];
  5179. return prototype;
  5180. }
  5181. function Color() {}
  5182. var darker = 0.7;
  5183. var brighter = 1 / darker;
  5184. var reI = "\\s*([+-]?\\d+)\\s*";
  5185. var reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*";
  5186. var reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
  5187. var reHex3 = /^#([0-9a-f]{3})$/;
  5188. var reHex6 = /^#([0-9a-f]{6})$/;
  5189. var reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$");
  5190. var reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$");
  5191. var reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$");
  5192. var reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$");
  5193. var reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$");
  5194. var reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");
  5195. var named = {
  5196. aliceblue: 0xf0f8ff,
  5197. antiquewhite: 0xfaebd7,
  5198. aqua: 0x00ffff,
  5199. aquamarine: 0x7fffd4,
  5200. azure: 0xf0ffff,
  5201. beige: 0xf5f5dc,
  5202. bisque: 0xffe4c4,
  5203. black: 0x000000,
  5204. blanchedalmond: 0xffebcd,
  5205. blue: 0x0000ff,
  5206. blueviolet: 0x8a2be2,
  5207. brown: 0xa52a2a,
  5208. burlywood: 0xdeb887,
  5209. cadetblue: 0x5f9ea0,
  5210. chartreuse: 0x7fff00,
  5211. chocolate: 0xd2691e,
  5212. coral: 0xff7f50,
  5213. cornflowerblue: 0x6495ed,
  5214. cornsilk: 0xfff8dc,
  5215. crimson: 0xdc143c,
  5216. cyan: 0x00ffff,
  5217. darkblue: 0x00008b,
  5218. darkcyan: 0x008b8b,
  5219. darkgoldenrod: 0xb8860b,
  5220. darkgray: 0xa9a9a9,
  5221. darkgreen: 0x006400,
  5222. darkgrey: 0xa9a9a9,
  5223. darkkhaki: 0xbdb76b,
  5224. darkmagenta: 0x8b008b,
  5225. darkolivegreen: 0x556b2f,
  5226. darkorange: 0xff8c00,
  5227. darkorchid: 0x9932cc,
  5228. darkred: 0x8b0000,
  5229. darksalmon: 0xe9967a,
  5230. darkseagreen: 0x8fbc8f,
  5231. darkslateblue: 0x483d8b,
  5232. darkslategray: 0x2f4f4f,
  5233. darkslategrey: 0x2f4f4f,
  5234. darkturquoise: 0x00ced1,
  5235. darkviolet: 0x9400d3,
  5236. deeppink: 0xff1493,
  5237. deepskyblue: 0x00bfff,
  5238. dimgray: 0x696969,
  5239. dimgrey: 0x696969,
  5240. dodgerblue: 0x1e90ff,
  5241. firebrick: 0xb22222,
  5242. floralwhite: 0xfffaf0,
  5243. forestgreen: 0x228b22,
  5244. fuchsia: 0xff00ff,
  5245. gainsboro: 0xdcdcdc,
  5246. ghostwhite: 0xf8f8ff,
  5247. gold: 0xffd700,
  5248. goldenrod: 0xdaa520,
  5249. gray: 0x808080,
  5250. green: 0x008000,
  5251. greenyellow: 0xadff2f,
  5252. grey: 0x808080,
  5253. honeydew: 0xf0fff0,
  5254. hotpink: 0xff69b4,
  5255. indianred: 0xcd5c5c,
  5256. indigo: 0x4b0082,
  5257. ivory: 0xfffff0,
  5258. khaki: 0xf0e68c,
  5259. lavender: 0xe6e6fa,
  5260. lavenderblush: 0xfff0f5,
  5261. lawngreen: 0x7cfc00,
  5262. lemonchiffon: 0xfffacd,
  5263. lightblue: 0xadd8e6,
  5264. lightcoral: 0xf08080,
  5265. lightcyan: 0xe0ffff,
  5266. lightgoldenrodyellow: 0xfafad2,
  5267. lightgray: 0xd3d3d3,
  5268. lightgreen: 0x90ee90,
  5269. lightgrey: 0xd3d3d3,
  5270. lightpink: 0xffb6c1,
  5271. lightsalmon: 0xffa07a,
  5272. lightseagreen: 0x20b2aa,
  5273. lightskyblue: 0x87cefa,
  5274. lightslategray: 0x778899,
  5275. lightslategrey: 0x778899,
  5276. lightsteelblue: 0xb0c4de,
  5277. lightyellow: 0xffffe0,
  5278. lime: 0x00ff00,
  5279. limegreen: 0x32cd32,
  5280. linen: 0xfaf0e6,
  5281. magenta: 0xff00ff,
  5282. maroon: 0x800000,
  5283. mediumaquamarine: 0x66cdaa,
  5284. mediumblue: 0x0000cd,
  5285. mediumorchid: 0xba55d3,
  5286. mediumpurple: 0x9370db,
  5287. mediumseagreen: 0x3cb371,
  5288. mediumslateblue: 0x7b68ee,
  5289. mediumspringgreen: 0x00fa9a,
  5290. mediumturquoise: 0x48d1cc,
  5291. mediumvioletred: 0xc71585,
  5292. midnightblue: 0x191970,
  5293. mintcream: 0xf5fffa,
  5294. mistyrose: 0xffe4e1,
  5295. moccasin: 0xffe4b5,
  5296. navajowhite: 0xffdead,
  5297. navy: 0x000080,
  5298. oldlace: 0xfdf5e6,
  5299. olive: 0x808000,
  5300. olivedrab: 0x6b8e23,
  5301. orange: 0xffa500,
  5302. orangered: 0xff4500,
  5303. orchid: 0xda70d6,
  5304. palegoldenrod: 0xeee8aa,
  5305. palegreen: 0x98fb98,
  5306. paleturquoise: 0xafeeee,
  5307. palevioletred: 0xdb7093,
  5308. papayawhip: 0xffefd5,
  5309. peachpuff: 0xffdab9,
  5310. peru: 0xcd853f,
  5311. pink: 0xffc0cb,
  5312. plum: 0xdda0dd,
  5313. powderblue: 0xb0e0e6,
  5314. purple: 0x800080,
  5315. rebeccapurple: 0x663399,
  5316. red: 0xff0000,
  5317. rosybrown: 0xbc8f8f,
  5318. royalblue: 0x4169e1,
  5319. saddlebrown: 0x8b4513,
  5320. salmon: 0xfa8072,
  5321. sandybrown: 0xf4a460,
  5322. seagreen: 0x2e8b57,
  5323. seashell: 0xfff5ee,
  5324. sienna: 0xa0522d,
  5325. silver: 0xc0c0c0,
  5326. skyblue: 0x87ceeb,
  5327. slateblue: 0x6a5acd,
  5328. slategray: 0x708090,
  5329. slategrey: 0x708090,
  5330. snow: 0xfffafa,
  5331. springgreen: 0x00ff7f,
  5332. steelblue: 0x4682b4,
  5333. tan: 0xd2b48c,
  5334. teal: 0x008080,
  5335. thistle: 0xd8bfd8,
  5336. tomato: 0xff6347,
  5337. turquoise: 0x40e0d0,
  5338. violet: 0xee82ee,
  5339. wheat: 0xf5deb3,
  5340. white: 0xffffff,
  5341. whitesmoke: 0xf5f5f5,
  5342. yellow: 0xffff00,
  5343. yellowgreen: 0x9acd32
  5344. };
  5345. define(Color, color, {
  5346. displayable: function() {
  5347. return this.rgb().displayable();
  5348. },
  5349. toString: function() {
  5350. return this.rgb() + "";
  5351. }
  5352. });
  5353. function color(format) {
  5354. var m;
  5355. format = (format + "").trim().toLowerCase();
  5356. return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00
  5357. : (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000
  5358. : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
  5359. : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
  5360. : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
  5361. : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
  5362. : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
  5363. : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
  5364. : named.hasOwnProperty(format) ? rgbn(named[format])
  5365. : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
  5366. : null;
  5367. }
  5368. function rgbn(n) {
  5369. return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
  5370. }
  5371. function rgba(r, g, b, a) {
  5372. if (a <= 0) r = g = b = NaN;
  5373. return new Rgb(r, g, b, a);
  5374. }
  5375. function rgbConvert(o) {
  5376. if (!(o instanceof Color)) o = color(o);
  5377. if (!o) return new Rgb;
  5378. o = o.rgb();
  5379. return new Rgb(o.r, o.g, o.b, o.opacity);
  5380. }
  5381. function rgb(r, g, b, opacity) {
  5382. return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
  5383. }
  5384. function Rgb(r, g, b, opacity) {
  5385. this.r = +r;
  5386. this.g = +g;
  5387. this.b = +b;
  5388. this.opacity = +opacity;
  5389. }
  5390. define(Rgb, rgb, extend(Color, {
  5391. brighter: function(k) {
  5392. k = k == null ? brighter : Math.pow(brighter, k);
  5393. return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  5394. },
  5395. darker: function(k) {
  5396. k = k == null ? darker : Math.pow(darker, k);
  5397. return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  5398. },
  5399. rgb: function() {
  5400. return this;
  5401. },
  5402. displayable: function() {
  5403. return (0 <= this.r && this.r <= 255)
  5404. && (0 <= this.g && this.g <= 255)
  5405. && (0 <= this.b && this.b <= 255)
  5406. && (0 <= this.opacity && this.opacity <= 1);
  5407. },
  5408. toString: function() {
  5409. var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
  5410. return (a === 1 ? "rgb(" : "rgba(")
  5411. + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
  5412. + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
  5413. + Math.max(0, Math.min(255, Math.round(this.b) || 0))
  5414. + (a === 1 ? ")" : ", " + a + ")");
  5415. }
  5416. }));
  5417. function hsla(h, s, l, a) {
  5418. if (a <= 0) h = s = l = NaN;
  5419. else if (l <= 0 || l >= 1) h = s = NaN;
  5420. else if (s <= 0) h = NaN;
  5421. return new Hsl(h, s, l, a);
  5422. }
  5423. function hslConvert(o) {
  5424. if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  5425. if (!(o instanceof Color)) o = color(o);
  5426. if (!o) return new Hsl;
  5427. if (o instanceof Hsl) return o;
  5428. o = o.rgb();
  5429. var r = o.r / 255,
  5430. g = o.g / 255,
  5431. b = o.b / 255,
  5432. min = Math.min(r, g, b),
  5433. max = Math.max(r, g, b),
  5434. h = NaN,
  5435. s = max - min,
  5436. l = (max + min) / 2;
  5437. if (s) {
  5438. if (r === max) h = (g - b) / s + (g < b) * 6;
  5439. else if (g === max) h = (b - r) / s + 2;
  5440. else h = (r - g) / s + 4;
  5441. s /= l < 0.5 ? max + min : 2 - max - min;
  5442. h *= 60;
  5443. } else {
  5444. s = l > 0 && l < 1 ? 0 : h;
  5445. }
  5446. return new Hsl(h, s, l, o.opacity);
  5447. }
  5448. function hsl(h, s, l, opacity) {
  5449. return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
  5450. }
  5451. function Hsl(h, s, l, opacity) {
  5452. this.h = +h;
  5453. this.s = +s;
  5454. this.l = +l;
  5455. this.opacity = +opacity;
  5456. }
  5457. define(Hsl, hsl, extend(Color, {
  5458. brighter: function(k) {
  5459. k = k == null ? brighter : Math.pow(brighter, k);
  5460. return new Hsl(this.h, this.s, this.l * k, this.opacity);
  5461. },
  5462. darker: function(k) {
  5463. k = k == null ? darker : Math.pow(darker, k);
  5464. return new Hsl(this.h, this.s, this.l * k, this.opacity);
  5465. },
  5466. rgb: function() {
  5467. var h = this.h % 360 + (this.h < 0) * 360,
  5468. s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
  5469. l = this.l,
  5470. m2 = l + (l < 0.5 ? l : 1 - l) * s,
  5471. m1 = 2 * l - m2;
  5472. return new Rgb(
  5473. hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
  5474. hsl2rgb(h, m1, m2),
  5475. hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
  5476. this.opacity
  5477. );
  5478. },
  5479. displayable: function() {
  5480. return (0 <= this.s && this.s <= 1 || isNaN(this.s))
  5481. && (0 <= this.l && this.l <= 1)
  5482. && (0 <= this.opacity && this.opacity <= 1);
  5483. }
  5484. }));
  5485. /* From FvD 13.37, CSS Color Module Level 3 */
  5486. function hsl2rgb(h, m1, m2) {
  5487. return (h < 60 ? m1 + (m2 - m1) * h / 60
  5488. : h < 180 ? m2
  5489. : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
  5490. : m1) * 255;
  5491. }
  5492. var deg2rad = Math.PI / 180;
  5493. var rad2deg = 180 / Math.PI;
  5494. var Kn = 18;
  5495. var Xn = 0.950470;
  5496. var Yn = 1;
  5497. var Zn = 1.088830;
  5498. var t0 = 4 / 29;
  5499. var t1 = 6 / 29;
  5500. var t2 = 3 * t1 * t1;
  5501. var t3 = t1 * t1 * t1;
  5502. function labConvert(o) {
  5503. if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
  5504. if (o instanceof Hcl) {
  5505. var h = o.h * deg2rad;
  5506. return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
  5507. }
  5508. if (!(o instanceof Rgb)) o = rgbConvert(o);
  5509. var b = rgb2xyz(o.r),
  5510. a = rgb2xyz(o.g),
  5511. l = rgb2xyz(o.b),
  5512. x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn),
  5513. y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn),
  5514. z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn);
  5515. return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
  5516. }
  5517. function lab(l, a, b, opacity) {
  5518. return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
  5519. }
  5520. function Lab(l, a, b, opacity) {
  5521. this.l = +l;
  5522. this.a = +a;
  5523. this.b = +b;
  5524. this.opacity = +opacity;
  5525. }
  5526. define(Lab, lab, extend(Color, {
  5527. brighter: function(k) {
  5528. return new Lab(this.l + Kn * (k == null ? 1 : k), this.a, this.b, this.opacity);
  5529. },
  5530. darker: function(k) {
  5531. return new Lab(this.l - Kn * (k == null ? 1 : k), this.a, this.b, this.opacity);
  5532. },
  5533. rgb: function() {
  5534. var y = (this.l + 16) / 116,
  5535. x = isNaN(this.a) ? y : y + this.a / 500,
  5536. z = isNaN(this.b) ? y : y - this.b / 200;
  5537. y = Yn * lab2xyz(y);
  5538. x = Xn * lab2xyz(x);
  5539. z = Zn * lab2xyz(z);
  5540. return new Rgb(
  5541. xyz2rgb( 3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB
  5542. xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z),
  5543. xyz2rgb( 0.0556434 * x - 0.2040259 * y + 1.0572252 * z),
  5544. this.opacity
  5545. );
  5546. }
  5547. }));
  5548. function xyz2lab(t) {
  5549. return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
  5550. }
  5551. function lab2xyz(t) {
  5552. return t > t1 ? t * t * t : t2 * (t - t0);
  5553. }
  5554. function xyz2rgb(x) {
  5555. return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
  5556. }
  5557. function rgb2xyz(x) {
  5558. return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
  5559. }
  5560. function hclConvert(o) {
  5561. if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
  5562. if (!(o instanceof Lab)) o = labConvert(o);
  5563. var h = Math.atan2(o.b, o.a) * rad2deg;
  5564. return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
  5565. }
  5566. function hcl(h, c, l, opacity) {
  5567. return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
  5568. }
  5569. function Hcl(h, c, l, opacity) {
  5570. this.h = +h;
  5571. this.c = +c;
  5572. this.l = +l;
  5573. this.opacity = +opacity;
  5574. }
  5575. define(Hcl, hcl, extend(Color, {
  5576. brighter: function(k) {
  5577. return new Hcl(this.h, this.c, this.l + Kn * (k == null ? 1 : k), this.opacity);
  5578. },
  5579. darker: function(k) {
  5580. return new Hcl(this.h, this.c, this.l - Kn * (k == null ? 1 : k), this.opacity);
  5581. },
  5582. rgb: function() {
  5583. return labConvert(this).rgb();
  5584. }
  5585. }));
  5586. var A = -0.14861;
  5587. var B = +1.78277;
  5588. var C = -0.29227;
  5589. var D = -0.90649;
  5590. var E = +1.97294;
  5591. var ED = E * D;
  5592. var EB = E * B;
  5593. var BC_DA = B * C - D * A;
  5594. function cubehelixConvert(o) {
  5595. if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
  5596. if (!(o instanceof Rgb)) o = rgbConvert(o);
  5597. var r = o.r / 255,
  5598. g = o.g / 255,
  5599. b = o.b / 255,
  5600. l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
  5601. bl = b - l,
  5602. k = (E * (g - l) - C * bl) / D,
  5603. s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
  5604. h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
  5605. return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
  5606. }
  5607. function cubehelix(h, s, l, opacity) {
  5608. return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
  5609. }
  5610. function Cubehelix(h, s, l, opacity) {
  5611. this.h = +h;
  5612. this.s = +s;
  5613. this.l = +l;
  5614. this.opacity = +opacity;
  5615. }
  5616. define(Cubehelix, cubehelix, extend(Color, {
  5617. brighter: function(k) {
  5618. k = k == null ? brighter : Math.pow(brighter, k);
  5619. return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  5620. },
  5621. darker: function(k) {
  5622. k = k == null ? darker : Math.pow(darker, k);
  5623. return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  5624. },
  5625. rgb: function() {
  5626. var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,
  5627. l = +this.l,
  5628. a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
  5629. cosh = Math.cos(h),
  5630. sinh = Math.sin(h);
  5631. return new Rgb(
  5632. 255 * (l + a * (A * cosh + B * sinh)),
  5633. 255 * (l + a * (C * cosh + D * sinh)),
  5634. 255 * (l + a * (E * cosh)),
  5635. this.opacity
  5636. );
  5637. }
  5638. }));
  5639. exports.color = color;
  5640. exports.rgb = rgb;
  5641. exports.hsl = hsl;
  5642. exports.lab = lab;
  5643. exports.hcl = hcl;
  5644. exports.cubehelix = cubehelix;
  5645. Object.defineProperty(exports, '__esModule', { value: true });
  5646. })));
  5647. },{}],45:[function(require,module,exports){
  5648. // https://d3js.org/d3-dispatch/ Version 1.0.3. Copyright 2017 Mike Bostock.
  5649. (function (global, factory) {
  5650. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  5651. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5652. (factory((global.d3 = global.d3 || {})));
  5653. }(this, (function (exports) { 'use strict';
  5654. var noop = {value: function() {}};
  5655. function dispatch() {
  5656. for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
  5657. if (!(t = arguments[i] + "") || (t in _)) throw new Error("illegal type: " + t);
  5658. _[t] = [];
  5659. }
  5660. return new Dispatch(_);
  5661. }
  5662. function Dispatch(_) {
  5663. this._ = _;
  5664. }
  5665. function parseTypenames(typenames, types) {
  5666. return typenames.trim().split(/^|\s+/).map(function(t) {
  5667. var name = "", i = t.indexOf(".");
  5668. if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
  5669. if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
  5670. return {type: t, name: name};
  5671. });
  5672. }
  5673. Dispatch.prototype = dispatch.prototype = {
  5674. constructor: Dispatch,
  5675. on: function(typename, callback) {
  5676. var _ = this._,
  5677. T = parseTypenames(typename + "", _),
  5678. t,
  5679. i = -1,
  5680. n = T.length;
  5681. // If no callback was specified, return the callback of the given type and name.
  5682. if (arguments.length < 2) {
  5683. while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t;
  5684. return;
  5685. }
  5686. // If a type was specified, set the callback for the given type and name.
  5687. // Otherwise, if a null callback was specified, remove callbacks of the given name.
  5688. if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
  5689. while (++i < n) {
  5690. if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback);
  5691. else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null);
  5692. }
  5693. return this;
  5694. },
  5695. copy: function() {
  5696. var copy = {}, _ = this._;
  5697. for (var t in _) copy[t] = _[t].slice();
  5698. return new Dispatch(copy);
  5699. },
  5700. call: function(type, that) {
  5701. if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
  5702. if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
  5703. for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  5704. },
  5705. apply: function(type, that, args) {
  5706. if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
  5707. for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  5708. }
  5709. };
  5710. function get(type, name) {
  5711. for (var i = 0, n = type.length, c; i < n; ++i) {
  5712. if ((c = type[i]).name === name) {
  5713. return c.value;
  5714. }
  5715. }
  5716. }
  5717. function set(type, name, callback) {
  5718. for (var i = 0, n = type.length; i < n; ++i) {
  5719. if (type[i].name === name) {
  5720. type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
  5721. break;
  5722. }
  5723. }
  5724. if (callback != null) type.push({name: name, value: callback});
  5725. return type;
  5726. }
  5727. exports.dispatch = dispatch;
  5728. Object.defineProperty(exports, '__esModule', { value: true });
  5729. })));
  5730. },{}],46:[function(require,module,exports){
  5731. // https://d3js.org/d3-drag/ Version 1.2.1. Copyright 2017 Mike Bostock.
  5732. (function (global, factory) {
  5733. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-dispatch'), require('d3-selection')) :
  5734. typeof define === 'function' && define.amd ? define(['exports', 'd3-dispatch', 'd3-selection'], factory) :
  5735. (factory((global.d3 = global.d3 || {}),global.d3,global.d3));
  5736. }(this, (function (exports,d3Dispatch,d3Selection) { 'use strict';
  5737. function nopropagation() {
  5738. d3Selection.event.stopImmediatePropagation();
  5739. }
  5740. var noevent = function() {
  5741. d3Selection.event.preventDefault();
  5742. d3Selection.event.stopImmediatePropagation();
  5743. };
  5744. var nodrag = function(view) {
  5745. var root = view.document.documentElement,
  5746. selection = d3Selection.select(view).on("dragstart.drag", noevent, true);
  5747. if ("onselectstart" in root) {
  5748. selection.on("selectstart.drag", noevent, true);
  5749. } else {
  5750. root.__noselect = root.style.MozUserSelect;
  5751. root.style.MozUserSelect = "none";
  5752. }
  5753. };
  5754. function yesdrag(view, noclick) {
  5755. var root = view.document.documentElement,
  5756. selection = d3Selection.select(view).on("dragstart.drag", null);
  5757. if (noclick) {
  5758. selection.on("click.drag", noevent, true);
  5759. setTimeout(function() { selection.on("click.drag", null); }, 0);
  5760. }
  5761. if ("onselectstart" in root) {
  5762. selection.on("selectstart.drag", null);
  5763. } else {
  5764. root.style.MozUserSelect = root.__noselect;
  5765. delete root.__noselect;
  5766. }
  5767. }
  5768. var constant = function(x) {
  5769. return function() {
  5770. return x;
  5771. };
  5772. };
  5773. function DragEvent(target, type, subject, id, active, x, y, dx, dy, dispatch$$1) {
  5774. this.target = target;
  5775. this.type = type;
  5776. this.subject = subject;
  5777. this.identifier = id;
  5778. this.active = active;
  5779. this.x = x;
  5780. this.y = y;
  5781. this.dx = dx;
  5782. this.dy = dy;
  5783. this._ = dispatch$$1;
  5784. }
  5785. DragEvent.prototype.on = function() {
  5786. var value = this._.on.apply(this._, arguments);
  5787. return value === this._ ? this : value;
  5788. };
  5789. // Ignore right-click, since that should open the context menu.
  5790. function defaultFilter() {
  5791. return !d3Selection.event.button;
  5792. }
  5793. function defaultContainer() {
  5794. return this.parentNode;
  5795. }
  5796. function defaultSubject(d) {
  5797. return d == null ? {x: d3Selection.event.x, y: d3Selection.event.y} : d;
  5798. }
  5799. function defaultTouchable() {
  5800. return "ontouchstart" in this;
  5801. }
  5802. var drag = function() {
  5803. var filter = defaultFilter,
  5804. container = defaultContainer,
  5805. subject = defaultSubject,
  5806. touchable = defaultTouchable,
  5807. gestures = {},
  5808. listeners = d3Dispatch.dispatch("start", "drag", "end"),
  5809. active = 0,
  5810. mousedownx,
  5811. mousedowny,
  5812. mousemoving,
  5813. touchending,
  5814. clickDistance2 = 0;
  5815. function drag(selection) {
  5816. selection
  5817. .on("mousedown.drag", mousedowned)
  5818. .filter(touchable)
  5819. .on("touchstart.drag", touchstarted)
  5820. .on("touchmove.drag", touchmoved)
  5821. .on("touchend.drag touchcancel.drag", touchended)
  5822. .style("touch-action", "none")
  5823. .style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  5824. }
  5825. function mousedowned() {
  5826. if (touchending || !filter.apply(this, arguments)) return;
  5827. var gesture = beforestart("mouse", container.apply(this, arguments), d3Selection.mouse, this, arguments);
  5828. if (!gesture) return;
  5829. d3Selection.select(d3Selection.event.view).on("mousemove.drag", mousemoved, true).on("mouseup.drag", mouseupped, true);
  5830. nodrag(d3Selection.event.view);
  5831. nopropagation();
  5832. mousemoving = false;
  5833. mousedownx = d3Selection.event.clientX;
  5834. mousedowny = d3Selection.event.clientY;
  5835. gesture("start");
  5836. }
  5837. function mousemoved() {
  5838. noevent();
  5839. if (!mousemoving) {
  5840. var dx = d3Selection.event.clientX - mousedownx, dy = d3Selection.event.clientY - mousedowny;
  5841. mousemoving = dx * dx + dy * dy > clickDistance2;
  5842. }
  5843. gestures.mouse("drag");
  5844. }
  5845. function mouseupped() {
  5846. d3Selection.select(d3Selection.event.view).on("mousemove.drag mouseup.drag", null);
  5847. yesdrag(d3Selection.event.view, mousemoving);
  5848. noevent();
  5849. gestures.mouse("end");
  5850. }
  5851. function touchstarted() {
  5852. if (!filter.apply(this, arguments)) return;
  5853. var touches = d3Selection.event.changedTouches,
  5854. c = container.apply(this, arguments),
  5855. n = touches.length, i, gesture;
  5856. for (i = 0; i < n; ++i) {
  5857. if (gesture = beforestart(touches[i].identifier, c, d3Selection.touch, this, arguments)) {
  5858. nopropagation();
  5859. gesture("start");
  5860. }
  5861. }
  5862. }
  5863. function touchmoved() {
  5864. var touches = d3Selection.event.changedTouches,
  5865. n = touches.length, i, gesture;
  5866. for (i = 0; i < n; ++i) {
  5867. if (gesture = gestures[touches[i].identifier]) {
  5868. noevent();
  5869. gesture("drag");
  5870. }
  5871. }
  5872. }
  5873. function touchended() {
  5874. var touches = d3Selection.event.changedTouches,
  5875. n = touches.length, i, gesture;
  5876. if (touchending) clearTimeout(touchending);
  5877. touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed!
  5878. for (i = 0; i < n; ++i) {
  5879. if (gesture = gestures[touches[i].identifier]) {
  5880. nopropagation();
  5881. gesture("end");
  5882. }
  5883. }
  5884. }
  5885. function beforestart(id, container, point, that, args) {
  5886. var p = point(container, id), s, dx, dy,
  5887. sublisteners = listeners.copy();
  5888. if (!d3Selection.customEvent(new DragEvent(drag, "beforestart", s, id, active, p[0], p[1], 0, 0, sublisteners), function() {
  5889. if ((d3Selection.event.subject = s = subject.apply(that, args)) == null) return false;
  5890. dx = s.x - p[0] || 0;
  5891. dy = s.y - p[1] || 0;
  5892. return true;
  5893. })) return;
  5894. return function gesture(type) {
  5895. var p0 = p, n;
  5896. switch (type) {
  5897. case "start": gestures[id] = gesture, n = active++; break;
  5898. case "end": delete gestures[id], --active; // nobreak
  5899. case "drag": p = point(container, id), n = active; break;
  5900. }
  5901. d3Selection.customEvent(new DragEvent(drag, type, s, id, n, p[0] + dx, p[1] + dy, p[0] - p0[0], p[1] - p0[1], sublisteners), sublisteners.apply, sublisteners, [type, that, args]);
  5902. };
  5903. }
  5904. drag.filter = function(_) {
  5905. return arguments.length ? (filter = typeof _ === "function" ? _ : constant(!!_), drag) : filter;
  5906. };
  5907. drag.container = function(_) {
  5908. return arguments.length ? (container = typeof _ === "function" ? _ : constant(_), drag) : container;
  5909. };
  5910. drag.subject = function(_) {
  5911. return arguments.length ? (subject = typeof _ === "function" ? _ : constant(_), drag) : subject;
  5912. };
  5913. drag.touchable = function(_) {
  5914. return arguments.length ? (touchable = typeof _ === "function" ? _ : constant(!!_), drag) : touchable;
  5915. };
  5916. drag.on = function() {
  5917. var value = listeners.on.apply(listeners, arguments);
  5918. return value === listeners ? drag : value;
  5919. };
  5920. drag.clickDistance = function(_) {
  5921. return arguments.length ? (clickDistance2 = (_ = +_) * _, drag) : Math.sqrt(clickDistance2);
  5922. };
  5923. return drag;
  5924. };
  5925. exports.drag = drag;
  5926. exports.dragDisable = nodrag;
  5927. exports.dragEnable = yesdrag;
  5928. Object.defineProperty(exports, '__esModule', { value: true });
  5929. })));
  5930. },{"d3-dispatch":45,"d3-selection":61}],47:[function(require,module,exports){
  5931. // https://d3js.org/d3-dsv/ Version 1.0.8. Copyright 2017 Mike Bostock.
  5932. (function (global, factory) {
  5933. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  5934. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5935. (factory((global.d3 = global.d3 || {})));
  5936. }(this, (function (exports) { 'use strict';
  5937. var EOL = {};
  5938. var EOF = {};
  5939. var QUOTE = 34;
  5940. var NEWLINE = 10;
  5941. var RETURN = 13;
  5942. function objectConverter(columns) {
  5943. return new Function("d", "return {" + columns.map(function(name, i) {
  5944. return JSON.stringify(name) + ": d[" + i + "]";
  5945. }).join(",") + "}");
  5946. }
  5947. function customConverter(columns, f) {
  5948. var object = objectConverter(columns);
  5949. return function(row, i) {
  5950. return f(object(row), i, columns);
  5951. };
  5952. }
  5953. // Compute unique columns in order of discovery.
  5954. function inferColumns(rows) {
  5955. var columnSet = Object.create(null),
  5956. columns = [];
  5957. rows.forEach(function(row) {
  5958. for (var column in row) {
  5959. if (!(column in columnSet)) {
  5960. columns.push(columnSet[column] = column);
  5961. }
  5962. }
  5963. });
  5964. return columns;
  5965. }
  5966. var dsv = function(delimiter) {
  5967. var reFormat = new RegExp("[\"" + delimiter + "\n\r]"),
  5968. DELIMITER = delimiter.charCodeAt(0);
  5969. function parse(text, f) {
  5970. var convert, columns, rows = parseRows(text, function(row, i) {
  5971. if (convert) return convert(row, i - 1);
  5972. columns = row, convert = f ? customConverter(row, f) : objectConverter(row);
  5973. });
  5974. rows.columns = columns || [];
  5975. return rows;
  5976. }
  5977. function parseRows(text, f) {
  5978. var rows = [], // output rows
  5979. N = text.length,
  5980. I = 0, // current character index
  5981. n = 0, // current line number
  5982. t, // current token
  5983. eof = N <= 0, // current token followed by EOF?
  5984. eol = false; // current token followed by EOL?
  5985. // Strip the trailing newline.
  5986. if (text.charCodeAt(N - 1) === NEWLINE) --N;
  5987. if (text.charCodeAt(N - 1) === RETURN) --N;
  5988. function token() {
  5989. if (eof) return EOF;
  5990. if (eol) return eol = false, EOL;
  5991. // Unescape quotes.
  5992. var i, j = I, c;
  5993. if (text.charCodeAt(j) === QUOTE) {
  5994. while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE);
  5995. if ((i = I) >= N) eof = true;
  5996. else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true;
  5997. else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
  5998. return text.slice(j + 1, i - 1).replace(/""/g, "\"");
  5999. }
  6000. // Find next delimiter or newline.
  6001. while (I < N) {
  6002. if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;
  6003. else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
  6004. else if (c !== DELIMITER) continue;
  6005. return text.slice(j, i);
  6006. }
  6007. // Return last token before EOF.
  6008. return eof = true, text.slice(j, N);
  6009. }
  6010. while ((t = token()) !== EOF) {
  6011. var row = [];
  6012. while (t !== EOL && t !== EOF) row.push(t), t = token();
  6013. if (f && (row = f(row, n++)) == null) continue;
  6014. rows.push(row);
  6015. }
  6016. return rows;
  6017. }
  6018. function format(rows, columns) {
  6019. if (columns == null) columns = inferColumns(rows);
  6020. return [columns.map(formatValue).join(delimiter)].concat(rows.map(function(row) {
  6021. return columns.map(function(column) {
  6022. return formatValue(row[column]);
  6023. }).join(delimiter);
  6024. })).join("\n");
  6025. }
  6026. function formatRows(rows) {
  6027. return rows.map(formatRow).join("\n");
  6028. }
  6029. function formatRow(row) {
  6030. return row.map(formatValue).join(delimiter);
  6031. }
  6032. function formatValue(text) {
  6033. return text == null ? ""
  6034. : reFormat.test(text += "") ? "\"" + text.replace(/"/g, "\"\"") + "\""
  6035. : text;
  6036. }
  6037. return {
  6038. parse: parse,
  6039. parseRows: parseRows,
  6040. format: format,
  6041. formatRows: formatRows
  6042. };
  6043. };
  6044. var csv = dsv(",");
  6045. var csvParse = csv.parse;
  6046. var csvParseRows = csv.parseRows;
  6047. var csvFormat = csv.format;
  6048. var csvFormatRows = csv.formatRows;
  6049. var tsv = dsv("\t");
  6050. var tsvParse = tsv.parse;
  6051. var tsvParseRows = tsv.parseRows;
  6052. var tsvFormat = tsv.format;
  6053. var tsvFormatRows = tsv.formatRows;
  6054. exports.dsvFormat = dsv;
  6055. exports.csvParse = csvParse;
  6056. exports.csvParseRows = csvParseRows;
  6057. exports.csvFormat = csvFormat;
  6058. exports.csvFormatRows = csvFormatRows;
  6059. exports.tsvParse = tsvParse;
  6060. exports.tsvParseRows = tsvParseRows;
  6061. exports.tsvFormat = tsvFormat;
  6062. exports.tsvFormatRows = tsvFormatRows;
  6063. Object.defineProperty(exports, '__esModule', { value: true });
  6064. })));
  6065. },{}],48:[function(require,module,exports){
  6066. // https://d3js.org/d3-ease/ Version 1.0.3. Copyright 2017 Mike Bostock.
  6067. (function (global, factory) {
  6068. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  6069. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  6070. (factory((global.d3 = global.d3 || {})));
  6071. }(this, (function (exports) { 'use strict';
  6072. function linear(t) {
  6073. return +t;
  6074. }
  6075. function quadIn(t) {
  6076. return t * t;
  6077. }
  6078. function quadOut(t) {
  6079. return t * (2 - t);
  6080. }
  6081. function quadInOut(t) {
  6082. return ((t *= 2) <= 1 ? t * t : --t * (2 - t) + 1) / 2;
  6083. }
  6084. function cubicIn(t) {
  6085. return t * t * t;
  6086. }
  6087. function cubicOut(t) {
  6088. return --t * t * t + 1;
  6089. }
  6090. function cubicInOut(t) {
  6091. return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
  6092. }
  6093. var exponent = 3;
  6094. var polyIn = (function custom(e) {
  6095. e = +e;
  6096. function polyIn(t) {
  6097. return Math.pow(t, e);
  6098. }
  6099. polyIn.exponent = custom;
  6100. return polyIn;
  6101. })(exponent);
  6102. var polyOut = (function custom(e) {
  6103. e = +e;
  6104. function polyOut(t) {
  6105. return 1 - Math.pow(1 - t, e);
  6106. }
  6107. polyOut.exponent = custom;
  6108. return polyOut;
  6109. })(exponent);
  6110. var polyInOut = (function custom(e) {
  6111. e = +e;
  6112. function polyInOut(t) {
  6113. return ((t *= 2) <= 1 ? Math.pow(t, e) : 2 - Math.pow(2 - t, e)) / 2;
  6114. }
  6115. polyInOut.exponent = custom;
  6116. return polyInOut;
  6117. })(exponent);
  6118. var pi = Math.PI;
  6119. var halfPi = pi / 2;
  6120. function sinIn(t) {
  6121. return 1 - Math.cos(t * halfPi);
  6122. }
  6123. function sinOut(t) {
  6124. return Math.sin(t * halfPi);
  6125. }
  6126. function sinInOut(t) {
  6127. return (1 - Math.cos(pi * t)) / 2;
  6128. }
  6129. function expIn(t) {
  6130. return Math.pow(2, 10 * t - 10);
  6131. }
  6132. function expOut(t) {
  6133. return 1 - Math.pow(2, -10 * t);
  6134. }
  6135. function expInOut(t) {
  6136. return ((t *= 2) <= 1 ? Math.pow(2, 10 * t - 10) : 2 - Math.pow(2, 10 - 10 * t)) / 2;
  6137. }
  6138. function circleIn(t) {
  6139. return 1 - Math.sqrt(1 - t * t);
  6140. }
  6141. function circleOut(t) {
  6142. return Math.sqrt(1 - --t * t);
  6143. }
  6144. function circleInOut(t) {
  6145. return ((t *= 2) <= 1 ? 1 - Math.sqrt(1 - t * t) : Math.sqrt(1 - (t -= 2) * t) + 1) / 2;
  6146. }
  6147. var b1 = 4 / 11;
  6148. var b2 = 6 / 11;
  6149. var b3 = 8 / 11;
  6150. var b4 = 3 / 4;
  6151. var b5 = 9 / 11;
  6152. var b6 = 10 / 11;
  6153. var b7 = 15 / 16;
  6154. var b8 = 21 / 22;
  6155. var b9 = 63 / 64;
  6156. var b0 = 1 / b1 / b1;
  6157. function bounceIn(t) {
  6158. return 1 - bounceOut(1 - t);
  6159. }
  6160. function bounceOut(t) {
  6161. return (t = +t) < b1 ? b0 * t * t : t < b3 ? b0 * (t -= b2) * t + b4 : t < b6 ? b0 * (t -= b5) * t + b7 : b0 * (t -= b8) * t + b9;
  6162. }
  6163. function bounceInOut(t) {
  6164. return ((t *= 2) <= 1 ? 1 - bounceOut(1 - t) : bounceOut(t - 1) + 1) / 2;
  6165. }
  6166. var overshoot = 1.70158;
  6167. var backIn = (function custom(s) {
  6168. s = +s;
  6169. function backIn(t) {
  6170. return t * t * ((s + 1) * t - s);
  6171. }
  6172. backIn.overshoot = custom;
  6173. return backIn;
  6174. })(overshoot);
  6175. var backOut = (function custom(s) {
  6176. s = +s;
  6177. function backOut(t) {
  6178. return --t * t * ((s + 1) * t + s) + 1;
  6179. }
  6180. backOut.overshoot = custom;
  6181. return backOut;
  6182. })(overshoot);
  6183. var backInOut = (function custom(s) {
  6184. s = +s;
  6185. function backInOut(t) {
  6186. return ((t *= 2) < 1 ? t * t * ((s + 1) * t - s) : (t -= 2) * t * ((s + 1) * t + s) + 2) / 2;
  6187. }
  6188. backInOut.overshoot = custom;
  6189. return backInOut;
  6190. })(overshoot);
  6191. var tau = 2 * Math.PI;
  6192. var amplitude = 1;
  6193. var period = 0.3;
  6194. var elasticIn = (function custom(a, p) {
  6195. var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);
  6196. function elasticIn(t) {
  6197. return a * Math.pow(2, 10 * --t) * Math.sin((s - t) / p);
  6198. }
  6199. elasticIn.amplitude = function(a) { return custom(a, p * tau); };
  6200. elasticIn.period = function(p) { return custom(a, p); };
  6201. return elasticIn;
  6202. })(amplitude, period);
  6203. var elasticOut = (function custom(a, p) {
  6204. var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);
  6205. function elasticOut(t) {
  6206. return 1 - a * Math.pow(2, -10 * (t = +t)) * Math.sin((t + s) / p);
  6207. }
  6208. elasticOut.amplitude = function(a) { return custom(a, p * tau); };
  6209. elasticOut.period = function(p) { return custom(a, p); };
  6210. return elasticOut;
  6211. })(amplitude, period);
  6212. var elasticInOut = (function custom(a, p) {
  6213. var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);
  6214. function elasticInOut(t) {
  6215. return ((t = t * 2 - 1) < 0
  6216. ? a * Math.pow(2, 10 * t) * Math.sin((s - t) / p)
  6217. : 2 - a * Math.pow(2, -10 * t) * Math.sin((s + t) / p)) / 2;
  6218. }
  6219. elasticInOut.amplitude = function(a) { return custom(a, p * tau); };
  6220. elasticInOut.period = function(p) { return custom(a, p); };
  6221. return elasticInOut;
  6222. })(amplitude, period);
  6223. exports.easeLinear = linear;
  6224. exports.easeQuad = quadInOut;
  6225. exports.easeQuadIn = quadIn;
  6226. exports.easeQuadOut = quadOut;
  6227. exports.easeQuadInOut = quadInOut;
  6228. exports.easeCubic = cubicInOut;
  6229. exports.easeCubicIn = cubicIn;
  6230. exports.easeCubicOut = cubicOut;
  6231. exports.easeCubicInOut = cubicInOut;
  6232. exports.easePoly = polyInOut;
  6233. exports.easePolyIn = polyIn;
  6234. exports.easePolyOut = polyOut;
  6235. exports.easePolyInOut = polyInOut;
  6236. exports.easeSin = sinInOut;
  6237. exports.easeSinIn = sinIn;
  6238. exports.easeSinOut = sinOut;
  6239. exports.easeSinInOut = sinInOut;
  6240. exports.easeExp = expInOut;
  6241. exports.easeExpIn = expIn;
  6242. exports.easeExpOut = expOut;
  6243. exports.easeExpInOut = expInOut;
  6244. exports.easeCircle = circleInOut;
  6245. exports.easeCircleIn = circleIn;
  6246. exports.easeCircleOut = circleOut;
  6247. exports.easeCircleInOut = circleInOut;
  6248. exports.easeBounce = bounceOut;
  6249. exports.easeBounceIn = bounceIn;
  6250. exports.easeBounceOut = bounceOut;
  6251. exports.easeBounceInOut = bounceInOut;
  6252. exports.easeBack = backInOut;
  6253. exports.easeBackIn = backIn;
  6254. exports.easeBackOut = backOut;
  6255. exports.easeBackInOut = backInOut;
  6256. exports.easeElastic = elasticOut;
  6257. exports.easeElasticIn = elasticIn;
  6258. exports.easeElasticOut = elasticOut;
  6259. exports.easeElasticInOut = elasticInOut;
  6260. Object.defineProperty(exports, '__esModule', { value: true });
  6261. })));
  6262. },{}],49:[function(require,module,exports){
  6263. // https://d3js.org/d3-force/ Version 1.1.0. Copyright 2017 Mike Bostock.
  6264. (function (global, factory) {
  6265. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-quadtree'), require('d3-collection'), require('d3-dispatch'), require('d3-timer')) :
  6266. typeof define === 'function' && define.amd ? define(['exports', 'd3-quadtree', 'd3-collection', 'd3-dispatch', 'd3-timer'], factory) :
  6267. (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3));
  6268. }(this, (function (exports,d3Quadtree,d3Collection,d3Dispatch,d3Timer) { 'use strict';
  6269. var center = function(x, y) {
  6270. var nodes;
  6271. if (x == null) x = 0;
  6272. if (y == null) y = 0;
  6273. function force() {
  6274. var i,
  6275. n = nodes.length,
  6276. node,
  6277. sx = 0,
  6278. sy = 0;
  6279. for (i = 0; i < n; ++i) {
  6280. node = nodes[i], sx += node.x, sy += node.y;
  6281. }
  6282. for (sx = sx / n - x, sy = sy / n - y, i = 0; i < n; ++i) {
  6283. node = nodes[i], node.x -= sx, node.y -= sy;
  6284. }
  6285. }
  6286. force.initialize = function(_) {
  6287. nodes = _;
  6288. };
  6289. force.x = function(_) {
  6290. return arguments.length ? (x = +_, force) : x;
  6291. };
  6292. force.y = function(_) {
  6293. return arguments.length ? (y = +_, force) : y;
  6294. };
  6295. return force;
  6296. };
  6297. var constant = function(x) {
  6298. return function() {
  6299. return x;
  6300. };
  6301. };
  6302. var jiggle = function() {
  6303. return (Math.random() - 0.5) * 1e-6;
  6304. };
  6305. function x(d) {
  6306. return d.x + d.vx;
  6307. }
  6308. function y(d) {
  6309. return d.y + d.vy;
  6310. }
  6311. var collide = function(radius) {
  6312. var nodes,
  6313. radii,
  6314. strength = 1,
  6315. iterations = 1;
  6316. if (typeof radius !== "function") radius = constant(radius == null ? 1 : +radius);
  6317. function force() {
  6318. var i, n = nodes.length,
  6319. tree,
  6320. node,
  6321. xi,
  6322. yi,
  6323. ri,
  6324. ri2;
  6325. for (var k = 0; k < iterations; ++k) {
  6326. tree = d3Quadtree.quadtree(nodes, x, y).visitAfter(prepare);
  6327. for (i = 0; i < n; ++i) {
  6328. node = nodes[i];
  6329. ri = radii[node.index], ri2 = ri * ri;
  6330. xi = node.x + node.vx;
  6331. yi = node.y + node.vy;
  6332. tree.visit(apply);
  6333. }
  6334. }
  6335. function apply(quad, x0, y0, x1, y1) {
  6336. var data = quad.data, rj = quad.r, r = ri + rj;
  6337. if (data) {
  6338. if (data.index > node.index) {
  6339. var x = xi - data.x - data.vx,
  6340. y = yi - data.y - data.vy,
  6341. l = x * x + y * y;
  6342. if (l < r * r) {
  6343. if (x === 0) x = jiggle(), l += x * x;
  6344. if (y === 0) y = jiggle(), l += y * y;
  6345. l = (r - (l = Math.sqrt(l))) / l * strength;
  6346. node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj));
  6347. node.vy += (y *= l) * r;
  6348. data.vx -= x * (r = 1 - r);
  6349. data.vy -= y * r;
  6350. }
  6351. }
  6352. return;
  6353. }
  6354. return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;
  6355. }
  6356. }
  6357. function prepare(quad) {
  6358. if (quad.data) return quad.r = radii[quad.data.index];
  6359. for (var i = quad.r = 0; i < 4; ++i) {
  6360. if (quad[i] && quad[i].r > quad.r) {
  6361. quad.r = quad[i].r;
  6362. }
  6363. }
  6364. }
  6365. function initialize() {
  6366. if (!nodes) return;
  6367. var i, n = nodes.length, node;
  6368. radii = new Array(n);
  6369. for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes);
  6370. }
  6371. force.initialize = function(_) {
  6372. nodes = _;
  6373. initialize();
  6374. };
  6375. force.iterations = function(_) {
  6376. return arguments.length ? (iterations = +_, force) : iterations;
  6377. };
  6378. force.strength = function(_) {
  6379. return arguments.length ? (strength = +_, force) : strength;
  6380. };
  6381. force.radius = function(_) {
  6382. return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
  6383. };
  6384. return force;
  6385. };
  6386. function index(d) {
  6387. return d.index;
  6388. }
  6389. function find(nodeById, nodeId) {
  6390. var node = nodeById.get(nodeId);
  6391. if (!node) throw new Error("missing: " + nodeId);
  6392. return node;
  6393. }
  6394. var link = function(links) {
  6395. var id = index,
  6396. strength = defaultStrength,
  6397. strengths,
  6398. distance = constant(30),
  6399. distances,
  6400. nodes,
  6401. count,
  6402. bias,
  6403. iterations = 1;
  6404. if (links == null) links = [];
  6405. function defaultStrength(link) {
  6406. return 1 / Math.min(count[link.source.index], count[link.target.index]);
  6407. }
  6408. function force(alpha) {
  6409. for (var k = 0, n = links.length; k < iterations; ++k) {
  6410. for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {
  6411. link = links[i], source = link.source, target = link.target;
  6412. x = target.x + target.vx - source.x - source.vx || jiggle();
  6413. y = target.y + target.vy - source.y - source.vy || jiggle();
  6414. l = Math.sqrt(x * x + y * y);
  6415. l = (l - distances[i]) / l * alpha * strengths[i];
  6416. x *= l, y *= l;
  6417. target.vx -= x * (b = bias[i]);
  6418. target.vy -= y * b;
  6419. source.vx += x * (b = 1 - b);
  6420. source.vy += y * b;
  6421. }
  6422. }
  6423. }
  6424. function initialize() {
  6425. if (!nodes) return;
  6426. var i,
  6427. n = nodes.length,
  6428. m = links.length,
  6429. nodeById = d3Collection.map(nodes, id),
  6430. link;
  6431. for (i = 0, count = new Array(n); i < m; ++i) {
  6432. link = links[i], link.index = i;
  6433. if (typeof link.source !== "object") link.source = find(nodeById, link.source);
  6434. if (typeof link.target !== "object") link.target = find(nodeById, link.target);
  6435. count[link.source.index] = (count[link.source.index] || 0) + 1;
  6436. count[link.target.index] = (count[link.target.index] || 0) + 1;
  6437. }
  6438. for (i = 0, bias = new Array(m); i < m; ++i) {
  6439. link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
  6440. }
  6441. strengths = new Array(m), initializeStrength();
  6442. distances = new Array(m), initializeDistance();
  6443. }
  6444. function initializeStrength() {
  6445. if (!nodes) return;
  6446. for (var i = 0, n = links.length; i < n; ++i) {
  6447. strengths[i] = +strength(links[i], i, links);
  6448. }
  6449. }
  6450. function initializeDistance() {
  6451. if (!nodes) return;
  6452. for (var i = 0, n = links.length; i < n; ++i) {
  6453. distances[i] = +distance(links[i], i, links);
  6454. }
  6455. }
  6456. force.initialize = function(_) {
  6457. nodes = _;
  6458. initialize();
  6459. };
  6460. force.links = function(_) {
  6461. return arguments.length ? (links = _, initialize(), force) : links;
  6462. };
  6463. force.id = function(_) {
  6464. return arguments.length ? (id = _, force) : id;
  6465. };
  6466. force.iterations = function(_) {
  6467. return arguments.length ? (iterations = +_, force) : iterations;
  6468. };
  6469. force.strength = function(_) {
  6470. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initializeStrength(), force) : strength;
  6471. };
  6472. force.distance = function(_) {
  6473. return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance;
  6474. };
  6475. return force;
  6476. };
  6477. function x$1(d) {
  6478. return d.x;
  6479. }
  6480. function y$1(d) {
  6481. return d.y;
  6482. }
  6483. var initialRadius = 10;
  6484. var initialAngle = Math.PI * (3 - Math.sqrt(5));
  6485. var simulation = function(nodes) {
  6486. var simulation,
  6487. alpha = 1,
  6488. alphaMin = 0.001,
  6489. alphaDecay = 1 - Math.pow(alphaMin, 1 / 300),
  6490. alphaTarget = 0,
  6491. velocityDecay = 0.6,
  6492. forces = d3Collection.map(),
  6493. stepper = d3Timer.timer(step),
  6494. event = d3Dispatch.dispatch("tick", "end");
  6495. if (nodes == null) nodes = [];
  6496. function step() {
  6497. tick();
  6498. event.call("tick", simulation);
  6499. if (alpha < alphaMin) {
  6500. stepper.stop();
  6501. event.call("end", simulation);
  6502. }
  6503. }
  6504. function tick() {
  6505. var i, n = nodes.length, node;
  6506. alpha += (alphaTarget - alpha) * alphaDecay;
  6507. forces.each(function(force) {
  6508. force(alpha);
  6509. });
  6510. for (i = 0; i < n; ++i) {
  6511. node = nodes[i];
  6512. if (node.fx == null) node.x += node.vx *= velocityDecay;
  6513. else node.x = node.fx, node.vx = 0;
  6514. if (node.fy == null) node.y += node.vy *= velocityDecay;
  6515. else node.y = node.fy, node.vy = 0;
  6516. }
  6517. }
  6518. function initializeNodes() {
  6519. for (var i = 0, n = nodes.length, node; i < n; ++i) {
  6520. node = nodes[i], node.index = i;
  6521. if (isNaN(node.x) || isNaN(node.y)) {
  6522. var radius = initialRadius * Math.sqrt(i), angle = i * initialAngle;
  6523. node.x = radius * Math.cos(angle);
  6524. node.y = radius * Math.sin(angle);
  6525. }
  6526. if (isNaN(node.vx) || isNaN(node.vy)) {
  6527. node.vx = node.vy = 0;
  6528. }
  6529. }
  6530. }
  6531. function initializeForce(force) {
  6532. if (force.initialize) force.initialize(nodes);
  6533. return force;
  6534. }
  6535. initializeNodes();
  6536. return simulation = {
  6537. tick: tick,
  6538. restart: function() {
  6539. return stepper.restart(step), simulation;
  6540. },
  6541. stop: function() {
  6542. return stepper.stop(), simulation;
  6543. },
  6544. nodes: function(_) {
  6545. return arguments.length ? (nodes = _, initializeNodes(), forces.each(initializeForce), simulation) : nodes;
  6546. },
  6547. alpha: function(_) {
  6548. return arguments.length ? (alpha = +_, simulation) : alpha;
  6549. },
  6550. alphaMin: function(_) {
  6551. return arguments.length ? (alphaMin = +_, simulation) : alphaMin;
  6552. },
  6553. alphaDecay: function(_) {
  6554. return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay;
  6555. },
  6556. alphaTarget: function(_) {
  6557. return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget;
  6558. },
  6559. velocityDecay: function(_) {
  6560. return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay;
  6561. },
  6562. force: function(name, _) {
  6563. return arguments.length > 1 ? ((_ == null ? forces.remove(name) : forces.set(name, initializeForce(_))), simulation) : forces.get(name);
  6564. },
  6565. find: function(x, y, radius) {
  6566. var i = 0,
  6567. n = nodes.length,
  6568. dx,
  6569. dy,
  6570. d2,
  6571. node,
  6572. closest;
  6573. if (radius == null) radius = Infinity;
  6574. else radius *= radius;
  6575. for (i = 0; i < n; ++i) {
  6576. node = nodes[i];
  6577. dx = x - node.x;
  6578. dy = y - node.y;
  6579. d2 = dx * dx + dy * dy;
  6580. if (d2 < radius) closest = node, radius = d2;
  6581. }
  6582. return closest;
  6583. },
  6584. on: function(name, _) {
  6585. return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name);
  6586. }
  6587. };
  6588. };
  6589. var manyBody = function() {
  6590. var nodes,
  6591. node,
  6592. alpha,
  6593. strength = constant(-30),
  6594. strengths,
  6595. distanceMin2 = 1,
  6596. distanceMax2 = Infinity,
  6597. theta2 = 0.81;
  6598. function force(_) {
  6599. var i, n = nodes.length, tree = d3Quadtree.quadtree(nodes, x$1, y$1).visitAfter(accumulate);
  6600. for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply);
  6601. }
  6602. function initialize() {
  6603. if (!nodes) return;
  6604. var i, n = nodes.length, node;
  6605. strengths = new Array(n);
  6606. for (i = 0; i < n; ++i) node = nodes[i], strengths[node.index] = +strength(node, i, nodes);
  6607. }
  6608. function accumulate(quad) {
  6609. var strength = 0, q, c, weight = 0, x, y, i;
  6610. // For internal nodes, accumulate forces from child quadrants.
  6611. if (quad.length) {
  6612. for (x = y = i = 0; i < 4; ++i) {
  6613. if ((q = quad[i]) && (c = Math.abs(q.value))) {
  6614. strength += q.value, weight += c, x += c * q.x, y += c * q.y;
  6615. }
  6616. }
  6617. quad.x = x / weight;
  6618. quad.y = y / weight;
  6619. }
  6620. // For leaf nodes, accumulate forces from coincident quadrants.
  6621. else {
  6622. q = quad;
  6623. q.x = q.data.x;
  6624. q.y = q.data.y;
  6625. do strength += strengths[q.data.index];
  6626. while (q = q.next);
  6627. }
  6628. quad.value = strength;
  6629. }
  6630. function apply(quad, x1, _, x2) {
  6631. if (!quad.value) return true;
  6632. var x = quad.x - node.x,
  6633. y = quad.y - node.y,
  6634. w = x2 - x1,
  6635. l = x * x + y * y;
  6636. // Apply the Barnes-Hut approximation if possible.
  6637. // Limit forces for very close nodes; randomize direction if coincident.
  6638. if (w * w / theta2 < l) {
  6639. if (l < distanceMax2) {
  6640. if (x === 0) x = jiggle(), l += x * x;
  6641. if (y === 0) y = jiggle(), l += y * y;
  6642. if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
  6643. node.vx += x * quad.value * alpha / l;
  6644. node.vy += y * quad.value * alpha / l;
  6645. }
  6646. return true;
  6647. }
  6648. // Otherwise, process points directly.
  6649. else if (quad.length || l >= distanceMax2) return;
  6650. // Limit forces for very close nodes; randomize direction if coincident.
  6651. if (quad.data !== node || quad.next) {
  6652. if (x === 0) x = jiggle(), l += x * x;
  6653. if (y === 0) y = jiggle(), l += y * y;
  6654. if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
  6655. }
  6656. do if (quad.data !== node) {
  6657. w = strengths[quad.data.index] * alpha / l;
  6658. node.vx += x * w;
  6659. node.vy += y * w;
  6660. } while (quad = quad.next);
  6661. }
  6662. force.initialize = function(_) {
  6663. nodes = _;
  6664. initialize();
  6665. };
  6666. force.strength = function(_) {
  6667. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  6668. };
  6669. force.distanceMin = function(_) {
  6670. return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);
  6671. };
  6672. force.distanceMax = function(_) {
  6673. return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);
  6674. };
  6675. force.theta = function(_) {
  6676. return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);
  6677. };
  6678. return force;
  6679. };
  6680. var radial = function(radius, x, y) {
  6681. var nodes,
  6682. strength = constant(0.1),
  6683. strengths,
  6684. radiuses;
  6685. if (typeof radius !== "function") radius = constant(+radius);
  6686. if (x == null) x = 0;
  6687. if (y == null) y = 0;
  6688. function force(alpha) {
  6689. for (var i = 0, n = nodes.length; i < n; ++i) {
  6690. var node = nodes[i],
  6691. dx = node.x - x || 1e-6,
  6692. dy = node.y - y || 1e-6,
  6693. r = Math.sqrt(dx * dx + dy * dy),
  6694. k = (radiuses[i] - r) * strengths[i] * alpha / r;
  6695. node.vx += dx * k;
  6696. node.vy += dy * k;
  6697. }
  6698. }
  6699. function initialize() {
  6700. if (!nodes) return;
  6701. var i, n = nodes.length;
  6702. strengths = new Array(n);
  6703. radiuses = new Array(n);
  6704. for (i = 0; i < n; ++i) {
  6705. radiuses[i] = +radius(nodes[i], i, nodes);
  6706. strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);
  6707. }
  6708. }
  6709. force.initialize = function(_) {
  6710. nodes = _, initialize();
  6711. };
  6712. force.strength = function(_) {
  6713. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  6714. };
  6715. force.radius = function(_) {
  6716. return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
  6717. };
  6718. force.x = function(_) {
  6719. return arguments.length ? (x = +_, force) : x;
  6720. };
  6721. force.y = function(_) {
  6722. return arguments.length ? (y = +_, force) : y;
  6723. };
  6724. return force;
  6725. };
  6726. var x$2 = function(x) {
  6727. var strength = constant(0.1),
  6728. nodes,
  6729. strengths,
  6730. xz;
  6731. if (typeof x !== "function") x = constant(x == null ? 0 : +x);
  6732. function force(alpha) {
  6733. for (var i = 0, n = nodes.length, node; i < n; ++i) {
  6734. node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha;
  6735. }
  6736. }
  6737. function initialize() {
  6738. if (!nodes) return;
  6739. var i, n = nodes.length;
  6740. strengths = new Array(n);
  6741. xz = new Array(n);
  6742. for (i = 0; i < n; ++i) {
  6743. strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
  6744. }
  6745. }
  6746. force.initialize = function(_) {
  6747. nodes = _;
  6748. initialize();
  6749. };
  6750. force.strength = function(_) {
  6751. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  6752. };
  6753. force.x = function(_) {
  6754. return arguments.length ? (x = typeof _ === "function" ? _ : constant(+_), initialize(), force) : x;
  6755. };
  6756. return force;
  6757. };
  6758. var y$2 = function(y) {
  6759. var strength = constant(0.1),
  6760. nodes,
  6761. strengths,
  6762. yz;
  6763. if (typeof y !== "function") y = constant(y == null ? 0 : +y);
  6764. function force(alpha) {
  6765. for (var i = 0, n = nodes.length, node; i < n; ++i) {
  6766. node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;
  6767. }
  6768. }
  6769. function initialize() {
  6770. if (!nodes) return;
  6771. var i, n = nodes.length;
  6772. strengths = new Array(n);
  6773. yz = new Array(n);
  6774. for (i = 0; i < n; ++i) {
  6775. strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
  6776. }
  6777. }
  6778. force.initialize = function(_) {
  6779. nodes = _;
  6780. initialize();
  6781. };
  6782. force.strength = function(_) {
  6783. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  6784. };
  6785. force.y = function(_) {
  6786. return arguments.length ? (y = typeof _ === "function" ? _ : constant(+_), initialize(), force) : y;
  6787. };
  6788. return force;
  6789. };
  6790. exports.forceCenter = center;
  6791. exports.forceCollide = collide;
  6792. exports.forceLink = link;
  6793. exports.forceManyBody = manyBody;
  6794. exports.forceRadial = radial;
  6795. exports.forceSimulation = simulation;
  6796. exports.forceX = x$2;
  6797. exports.forceY = y$2;
  6798. Object.defineProperty(exports, '__esModule', { value: true });
  6799. })));
  6800. },{"d3-collection":43,"d3-dispatch":45,"d3-quadtree":56,"d3-timer":65}],50:[function(require,module,exports){
  6801. // https://d3js.org/d3-format/ Version 1.2.1. Copyright 2017 Mike Bostock.
  6802. (function (global, factory) {
  6803. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  6804. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  6805. (factory((global.d3 = global.d3 || {})));
  6806. }(this, (function (exports) { 'use strict';
  6807. // Computes the decimal coefficient and exponent of the specified number x with
  6808. // significant digits p, where x is positive and p is in [1, 21] or undefined.
  6809. // For example, formatDecimal(1.23) returns ["123", 0].
  6810. var formatDecimal = function(x, p) {
  6811. if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
  6812. var i, coefficient = x.slice(0, i);
  6813. // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
  6814. // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
  6815. return [
  6816. coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
  6817. +x.slice(i + 1)
  6818. ];
  6819. };
  6820. var exponent = function(x) {
  6821. return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN;
  6822. };
  6823. var formatGroup = function(grouping, thousands) {
  6824. return function(value, width) {
  6825. var i = value.length,
  6826. t = [],
  6827. j = 0,
  6828. g = grouping[0],
  6829. length = 0;
  6830. while (i > 0 && g > 0) {
  6831. if (length + g + 1 > width) g = Math.max(1, width - length);
  6832. t.push(value.substring(i -= g, i + g));
  6833. if ((length += g + 1) > width) break;
  6834. g = grouping[j = (j + 1) % grouping.length];
  6835. }
  6836. return t.reverse().join(thousands);
  6837. };
  6838. };
  6839. var formatNumerals = function(numerals) {
  6840. return function(value) {
  6841. return value.replace(/[0-9]/g, function(i) {
  6842. return numerals[+i];
  6843. });
  6844. };
  6845. };
  6846. var formatDefault = function(x, p) {
  6847. x = x.toPrecision(p);
  6848. out: for (var n = x.length, i = 1, i0 = -1, i1; i < n; ++i) {
  6849. switch (x[i]) {
  6850. case ".": i0 = i1 = i; break;
  6851. case "0": if (i0 === 0) i0 = i; i1 = i; break;
  6852. case "e": break out;
  6853. default: if (i0 > 0) i0 = 0; break;
  6854. }
  6855. }
  6856. return i0 > 0 ? x.slice(0, i0) + x.slice(i1 + 1) : x;
  6857. };
  6858. var prefixExponent;
  6859. var formatPrefixAuto = function(x, p) {
  6860. var d = formatDecimal(x, p);
  6861. if (!d) return x + "";
  6862. var coefficient = d[0],
  6863. exponent = d[1],
  6864. i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
  6865. n = coefficient.length;
  6866. return i === n ? coefficient
  6867. : i > n ? coefficient + new Array(i - n + 1).join("0")
  6868. : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
  6869. : "0." + new Array(1 - i).join("0") + formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!
  6870. };
  6871. var formatRounded = function(x, p) {
  6872. var d = formatDecimal(x, p);
  6873. if (!d) return x + "";
  6874. var coefficient = d[0],
  6875. exponent = d[1];
  6876. return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
  6877. : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
  6878. : coefficient + new Array(exponent - coefficient.length + 2).join("0");
  6879. };
  6880. var formatTypes = {
  6881. "": formatDefault,
  6882. "%": function(x, p) { return (x * 100).toFixed(p); },
  6883. "b": function(x) { return Math.round(x).toString(2); },
  6884. "c": function(x) { return x + ""; },
  6885. "d": function(x) { return Math.round(x).toString(10); },
  6886. "e": function(x, p) { return x.toExponential(p); },
  6887. "f": function(x, p) { return x.toFixed(p); },
  6888. "g": function(x, p) { return x.toPrecision(p); },
  6889. "o": function(x) { return Math.round(x).toString(8); },
  6890. "p": function(x, p) { return formatRounded(x * 100, p); },
  6891. "r": formatRounded,
  6892. "s": formatPrefixAuto,
  6893. "X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
  6894. "x": function(x) { return Math.round(x).toString(16); }
  6895. };
  6896. // [[fill]align][sign][symbol][0][width][,][.precision][type]
  6897. var re = /^(?:(.)?([<>=^]))?([+\-\( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?([a-z%])?$/i;
  6898. function formatSpecifier(specifier) {
  6899. return new FormatSpecifier(specifier);
  6900. }
  6901. formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof
  6902. function FormatSpecifier(specifier) {
  6903. if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
  6904. var match,
  6905. fill = match[1] || " ",
  6906. align = match[2] || ">",
  6907. sign = match[3] || "-",
  6908. symbol = match[4] || "",
  6909. zero = !!match[5],
  6910. width = match[6] && +match[6],
  6911. comma = !!match[7],
  6912. precision = match[8] && +match[8].slice(1),
  6913. type = match[9] || "";
  6914. // The "n" type is an alias for ",g".
  6915. if (type === "n") comma = true, type = "g";
  6916. // Map invalid types to the default format.
  6917. else if (!formatTypes[type]) type = "";
  6918. // If zero fill is specified, padding goes after sign and before digits.
  6919. if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";
  6920. this.fill = fill;
  6921. this.align = align;
  6922. this.sign = sign;
  6923. this.symbol = symbol;
  6924. this.zero = zero;
  6925. this.width = width;
  6926. this.comma = comma;
  6927. this.precision = precision;
  6928. this.type = type;
  6929. }
  6930. FormatSpecifier.prototype.toString = function() {
  6931. return this.fill
  6932. + this.align
  6933. + this.sign
  6934. + this.symbol
  6935. + (this.zero ? "0" : "")
  6936. + (this.width == null ? "" : Math.max(1, this.width | 0))
  6937. + (this.comma ? "," : "")
  6938. + (this.precision == null ? "" : "." + Math.max(0, this.precision | 0))
  6939. + this.type;
  6940. };
  6941. var identity = function(x) {
  6942. return x;
  6943. };
  6944. var prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];
  6945. var formatLocale = function(locale) {
  6946. var group = locale.grouping && locale.thousands ? formatGroup(locale.grouping, locale.thousands) : identity,
  6947. currency = locale.currency,
  6948. decimal = locale.decimal,
  6949. numerals = locale.numerals ? formatNumerals(locale.numerals) : identity,
  6950. percent = locale.percent || "%";
  6951. function newFormat(specifier) {
  6952. specifier = formatSpecifier(specifier);
  6953. var fill = specifier.fill,
  6954. align = specifier.align,
  6955. sign = specifier.sign,
  6956. symbol = specifier.symbol,
  6957. zero = specifier.zero,
  6958. width = specifier.width,
  6959. comma = specifier.comma,
  6960. precision = specifier.precision,
  6961. type = specifier.type;
  6962. // Compute the prefix and suffix.
  6963. // For SI-prefix, the suffix is lazily computed.
  6964. var prefix = symbol === "$" ? currency[0] : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
  6965. suffix = symbol === "$" ? currency[1] : /[%p]/.test(type) ? percent : "";
  6966. // What format function should we use?
  6967. // Is this an integer type?
  6968. // Can this type generate exponential notation?
  6969. var formatType = formatTypes[type],
  6970. maybeSuffix = !type || /[defgprs%]/.test(type);
  6971. // Set the default precision if not specified,
  6972. // or clamp the specified precision to the supported range.
  6973. // For significant precision, it must be in [1, 21].
  6974. // For fixed precision, it must be in [0, 20].
  6975. precision = precision == null ? (type ? 6 : 12)
  6976. : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
  6977. : Math.max(0, Math.min(20, precision));
  6978. function format(value) {
  6979. var valuePrefix = prefix,
  6980. valueSuffix = suffix,
  6981. i, n, c;
  6982. if (type === "c") {
  6983. valueSuffix = formatType(value) + valueSuffix;
  6984. value = "";
  6985. } else {
  6986. value = +value;
  6987. // Perform the initial formatting.
  6988. var valueNegative = value < 0;
  6989. value = formatType(Math.abs(value), precision);
  6990. // If a negative value rounds to zero during formatting, treat as positive.
  6991. if (valueNegative && +value === 0) valueNegative = false;
  6992. // Compute the prefix and suffix.
  6993. valuePrefix = (valueNegative ? (sign === "(" ? sign : "-") : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
  6994. valueSuffix = valueSuffix + (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + (valueNegative && sign === "(" ? ")" : "");
  6995. // Break the formatted value into the integer “value” part that can be
  6996. // grouped, and fractional or exponential “suffix” part that is not.
  6997. if (maybeSuffix) {
  6998. i = -1, n = value.length;
  6999. while (++i < n) {
  7000. if (c = value.charCodeAt(i), 48 > c || c > 57) {
  7001. valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
  7002. value = value.slice(0, i);
  7003. break;
  7004. }
  7005. }
  7006. }
  7007. }
  7008. // If the fill character is not "0", grouping is applied before padding.
  7009. if (comma && !zero) value = group(value, Infinity);
  7010. // Compute the padding.
  7011. var length = valuePrefix.length + value.length + valueSuffix.length,
  7012. padding = length < width ? new Array(width - length + 1).join(fill) : "";
  7013. // If the fill character is "0", grouping is applied after padding.
  7014. if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
  7015. // Reconstruct the final output based on the desired alignment.
  7016. switch (align) {
  7017. case "<": value = valuePrefix + value + valueSuffix + padding; break;
  7018. case "=": value = valuePrefix + padding + value + valueSuffix; break;
  7019. case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
  7020. default: value = padding + valuePrefix + value + valueSuffix; break;
  7021. }
  7022. return numerals(value);
  7023. }
  7024. format.toString = function() {
  7025. return specifier + "";
  7026. };
  7027. return format;
  7028. }
  7029. function formatPrefix(specifier, value) {
  7030. var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)),
  7031. e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,
  7032. k = Math.pow(10, -e),
  7033. prefix = prefixes[8 + e / 3];
  7034. return function(value) {
  7035. return f(k * value) + prefix;
  7036. };
  7037. }
  7038. return {
  7039. format: newFormat,
  7040. formatPrefix: formatPrefix
  7041. };
  7042. };
  7043. var locale;
  7044. defaultLocale({
  7045. decimal: ".",
  7046. thousands: ",",
  7047. grouping: [3],
  7048. currency: ["$", ""]
  7049. });
  7050. function defaultLocale(definition) {
  7051. locale = formatLocale(definition);
  7052. exports.format = locale.format;
  7053. exports.formatPrefix = locale.formatPrefix;
  7054. return locale;
  7055. }
  7056. var precisionFixed = function(step) {
  7057. return Math.max(0, -exponent(Math.abs(step)));
  7058. };
  7059. var precisionPrefix = function(step, value) {
  7060. return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));
  7061. };
  7062. var precisionRound = function(step, max) {
  7063. step = Math.abs(step), max = Math.abs(max) - step;
  7064. return Math.max(0, exponent(max) - exponent(step)) + 1;
  7065. };
  7066. exports.formatDefaultLocale = defaultLocale;
  7067. exports.formatLocale = formatLocale;
  7068. exports.formatSpecifier = formatSpecifier;
  7069. exports.precisionFixed = precisionFixed;
  7070. exports.precisionPrefix = precisionPrefix;
  7071. exports.precisionRound = precisionRound;
  7072. Object.defineProperty(exports, '__esModule', { value: true });
  7073. })));
  7074. },{}],51:[function(require,module,exports){
  7075. // https://d3js.org/d3-geo/ Version 1.9.1. Copyright 2017 Mike Bostock.
  7076. (function (global, factory) {
  7077. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-array')) :
  7078. typeof define === 'function' && define.amd ? define(['exports', 'd3-array'], factory) :
  7079. (factory((global.d3 = global.d3 || {}),global.d3));
  7080. }(this, (function (exports,d3Array) { 'use strict';
  7081. // Adds floating point numbers with twice the normal precision.
  7082. // Reference: J. R. Shewchuk, Adaptive Precision Floating-Point Arithmetic and
  7083. // Fast Robust Geometric Predicates, Discrete & Computational Geometry 18(3)
  7084. // 305–363 (1997).
  7085. // Code adapted from GeographicLib by Charles F. F. Karney,
  7086. // http://geographiclib.sourceforge.net/
  7087. var adder = function() {
  7088. return new Adder;
  7089. };
  7090. function Adder() {
  7091. this.reset();
  7092. }
  7093. Adder.prototype = {
  7094. constructor: Adder,
  7095. reset: function() {
  7096. this.s = // rounded value
  7097. this.t = 0; // exact error
  7098. },
  7099. add: function(y) {
  7100. add(temp, y, this.t);
  7101. add(this, temp.s, this.s);
  7102. if (this.s) this.t += temp.t;
  7103. else this.s = temp.t;
  7104. },
  7105. valueOf: function() {
  7106. return this.s;
  7107. }
  7108. };
  7109. var temp = new Adder;
  7110. function add(adder, a, b) {
  7111. var x = adder.s = a + b,
  7112. bv = x - a,
  7113. av = x - bv;
  7114. adder.t = (a - av) + (b - bv);
  7115. }
  7116. var epsilon = 1e-6;
  7117. var epsilon2 = 1e-12;
  7118. var pi = Math.PI;
  7119. var halfPi = pi / 2;
  7120. var quarterPi = pi / 4;
  7121. var tau = pi * 2;
  7122. var degrees = 180 / pi;
  7123. var radians = pi / 180;
  7124. var abs = Math.abs;
  7125. var atan = Math.atan;
  7126. var atan2 = Math.atan2;
  7127. var cos = Math.cos;
  7128. var ceil = Math.ceil;
  7129. var exp = Math.exp;
  7130. var log = Math.log;
  7131. var pow = Math.pow;
  7132. var sin = Math.sin;
  7133. var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };
  7134. var sqrt = Math.sqrt;
  7135. var tan = Math.tan;
  7136. function acos(x) {
  7137. return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
  7138. }
  7139. function asin(x) {
  7140. return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);
  7141. }
  7142. function haversin(x) {
  7143. return (x = sin(x / 2)) * x;
  7144. }
  7145. function noop() {}
  7146. function streamGeometry(geometry, stream) {
  7147. if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {
  7148. streamGeometryType[geometry.type](geometry, stream);
  7149. }
  7150. }
  7151. var streamObjectType = {
  7152. Feature: function(object, stream) {
  7153. streamGeometry(object.geometry, stream);
  7154. },
  7155. FeatureCollection: function(object, stream) {
  7156. var features = object.features, i = -1, n = features.length;
  7157. while (++i < n) streamGeometry(features[i].geometry, stream);
  7158. }
  7159. };
  7160. var streamGeometryType = {
  7161. Sphere: function(object, stream) {
  7162. stream.sphere();
  7163. },
  7164. Point: function(object, stream) {
  7165. object = object.coordinates;
  7166. stream.point(object[0], object[1], object[2]);
  7167. },
  7168. MultiPoint: function(object, stream) {
  7169. var coordinates = object.coordinates, i = -1, n = coordinates.length;
  7170. while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);
  7171. },
  7172. LineString: function(object, stream) {
  7173. streamLine(object.coordinates, stream, 0);
  7174. },
  7175. MultiLineString: function(object, stream) {
  7176. var coordinates = object.coordinates, i = -1, n = coordinates.length;
  7177. while (++i < n) streamLine(coordinates[i], stream, 0);
  7178. },
  7179. Polygon: function(object, stream) {
  7180. streamPolygon(object.coordinates, stream);
  7181. },
  7182. MultiPolygon: function(object, stream) {
  7183. var coordinates = object.coordinates, i = -1, n = coordinates.length;
  7184. while (++i < n) streamPolygon(coordinates[i], stream);
  7185. },
  7186. GeometryCollection: function(object, stream) {
  7187. var geometries = object.geometries, i = -1, n = geometries.length;
  7188. while (++i < n) streamGeometry(geometries[i], stream);
  7189. }
  7190. };
  7191. function streamLine(coordinates, stream, closed) {
  7192. var i = -1, n = coordinates.length - closed, coordinate;
  7193. stream.lineStart();
  7194. while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);
  7195. stream.lineEnd();
  7196. }
  7197. function streamPolygon(coordinates, stream) {
  7198. var i = -1, n = coordinates.length;
  7199. stream.polygonStart();
  7200. while (++i < n) streamLine(coordinates[i], stream, 1);
  7201. stream.polygonEnd();
  7202. }
  7203. var geoStream = function(object, stream) {
  7204. if (object && streamObjectType.hasOwnProperty(object.type)) {
  7205. streamObjectType[object.type](object, stream);
  7206. } else {
  7207. streamGeometry(object, stream);
  7208. }
  7209. };
  7210. var areaRingSum = adder();
  7211. var areaSum = adder();
  7212. var lambda00;
  7213. var phi00;
  7214. var lambda0;
  7215. var cosPhi0;
  7216. var sinPhi0;
  7217. var areaStream = {
  7218. point: noop,
  7219. lineStart: noop,
  7220. lineEnd: noop,
  7221. polygonStart: function() {
  7222. areaRingSum.reset();
  7223. areaStream.lineStart = areaRingStart;
  7224. areaStream.lineEnd = areaRingEnd;
  7225. },
  7226. polygonEnd: function() {
  7227. var areaRing = +areaRingSum;
  7228. areaSum.add(areaRing < 0 ? tau + areaRing : areaRing);
  7229. this.lineStart = this.lineEnd = this.point = noop;
  7230. },
  7231. sphere: function() {
  7232. areaSum.add(tau);
  7233. }
  7234. };
  7235. function areaRingStart() {
  7236. areaStream.point = areaPointFirst;
  7237. }
  7238. function areaRingEnd() {
  7239. areaPoint(lambda00, phi00);
  7240. }
  7241. function areaPointFirst(lambda, phi) {
  7242. areaStream.point = areaPoint;
  7243. lambda00 = lambda, phi00 = phi;
  7244. lambda *= radians, phi *= radians;
  7245. lambda0 = lambda, cosPhi0 = cos(phi = phi / 2 + quarterPi), sinPhi0 = sin(phi);
  7246. }
  7247. function areaPoint(lambda, phi) {
  7248. lambda *= radians, phi *= radians;
  7249. phi = phi / 2 + quarterPi; // half the angular distance from south pole
  7250. // Spherical excess E for a spherical triangle with vertices: south pole,
  7251. // previous point, current point. Uses a formula derived from Cagnoli’s
  7252. // theorem. See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).
  7253. var dLambda = lambda - lambda0,
  7254. sdLambda = dLambda >= 0 ? 1 : -1,
  7255. adLambda = sdLambda * dLambda,
  7256. cosPhi = cos(phi),
  7257. sinPhi = sin(phi),
  7258. k = sinPhi0 * sinPhi,
  7259. u = cosPhi0 * cosPhi + k * cos(adLambda),
  7260. v = k * sdLambda * sin(adLambda);
  7261. areaRingSum.add(atan2(v, u));
  7262. // Advance the previous points.
  7263. lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi;
  7264. }
  7265. var area = function(object) {
  7266. areaSum.reset();
  7267. geoStream(object, areaStream);
  7268. return areaSum * 2;
  7269. };
  7270. function spherical(cartesian) {
  7271. return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];
  7272. }
  7273. function cartesian(spherical) {
  7274. var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi);
  7275. return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];
  7276. }
  7277. function cartesianDot(a, b) {
  7278. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  7279. }
  7280. function cartesianCross(a, b) {
  7281. return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
  7282. }
  7283. // TODO return a
  7284. function cartesianAddInPlace(a, b) {
  7285. a[0] += b[0], a[1] += b[1], a[2] += b[2];
  7286. }
  7287. function cartesianScale(vector, k) {
  7288. return [vector[0] * k, vector[1] * k, vector[2] * k];
  7289. }
  7290. // TODO return d
  7291. function cartesianNormalizeInPlace(d) {
  7292. var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
  7293. d[0] /= l, d[1] /= l, d[2] /= l;
  7294. }
  7295. var lambda0$1;
  7296. var phi0;
  7297. var lambda1;
  7298. var phi1;
  7299. var lambda2;
  7300. var lambda00$1;
  7301. var phi00$1;
  7302. var p0;
  7303. var deltaSum = adder();
  7304. var ranges;
  7305. var range$1;
  7306. var boundsStream = {
  7307. point: boundsPoint,
  7308. lineStart: boundsLineStart,
  7309. lineEnd: boundsLineEnd,
  7310. polygonStart: function() {
  7311. boundsStream.point = boundsRingPoint;
  7312. boundsStream.lineStart = boundsRingStart;
  7313. boundsStream.lineEnd = boundsRingEnd;
  7314. deltaSum.reset();
  7315. areaStream.polygonStart();
  7316. },
  7317. polygonEnd: function() {
  7318. areaStream.polygonEnd();
  7319. boundsStream.point = boundsPoint;
  7320. boundsStream.lineStart = boundsLineStart;
  7321. boundsStream.lineEnd = boundsLineEnd;
  7322. if (areaRingSum < 0) lambda0$1 = -(lambda1 = 180), phi0 = -(phi1 = 90);
  7323. else if (deltaSum > epsilon) phi1 = 90;
  7324. else if (deltaSum < -epsilon) phi0 = -90;
  7325. range$1[0] = lambda0$1, range$1[1] = lambda1;
  7326. }
  7327. };
  7328. function boundsPoint(lambda, phi) {
  7329. ranges.push(range$1 = [lambda0$1 = lambda, lambda1 = lambda]);
  7330. if (phi < phi0) phi0 = phi;
  7331. if (phi > phi1) phi1 = phi;
  7332. }
  7333. function linePoint(lambda, phi) {
  7334. var p = cartesian([lambda * radians, phi * radians]);
  7335. if (p0) {
  7336. var normal = cartesianCross(p0, p),
  7337. equatorial = [normal[1], -normal[0], 0],
  7338. inflection = cartesianCross(equatorial, normal);
  7339. cartesianNormalizeInPlace(inflection);
  7340. inflection = spherical(inflection);
  7341. var delta = lambda - lambda2,
  7342. sign$$1 = delta > 0 ? 1 : -1,
  7343. lambdai = inflection[0] * degrees * sign$$1,
  7344. phii,
  7345. antimeridian = abs(delta) > 180;
  7346. if (antimeridian ^ (sign$$1 * lambda2 < lambdai && lambdai < sign$$1 * lambda)) {
  7347. phii = inflection[1] * degrees;
  7348. if (phii > phi1) phi1 = phii;
  7349. } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign$$1 * lambda2 < lambdai && lambdai < sign$$1 * lambda)) {
  7350. phii = -inflection[1] * degrees;
  7351. if (phii < phi0) phi0 = phii;
  7352. } else {
  7353. if (phi < phi0) phi0 = phi;
  7354. if (phi > phi1) phi1 = phi;
  7355. }
  7356. if (antimeridian) {
  7357. if (lambda < lambda2) {
  7358. if (angle(lambda0$1, lambda) > angle(lambda0$1, lambda1)) lambda1 = lambda;
  7359. } else {
  7360. if (angle(lambda, lambda1) > angle(lambda0$1, lambda1)) lambda0$1 = lambda;
  7361. }
  7362. } else {
  7363. if (lambda1 >= lambda0$1) {
  7364. if (lambda < lambda0$1) lambda0$1 = lambda;
  7365. if (lambda > lambda1) lambda1 = lambda;
  7366. } else {
  7367. if (lambda > lambda2) {
  7368. if (angle(lambda0$1, lambda) > angle(lambda0$1, lambda1)) lambda1 = lambda;
  7369. } else {
  7370. if (angle(lambda, lambda1) > angle(lambda0$1, lambda1)) lambda0$1 = lambda;
  7371. }
  7372. }
  7373. }
  7374. } else {
  7375. ranges.push(range$1 = [lambda0$1 = lambda, lambda1 = lambda]);
  7376. }
  7377. if (phi < phi0) phi0 = phi;
  7378. if (phi > phi1) phi1 = phi;
  7379. p0 = p, lambda2 = lambda;
  7380. }
  7381. function boundsLineStart() {
  7382. boundsStream.point = linePoint;
  7383. }
  7384. function boundsLineEnd() {
  7385. range$1[0] = lambda0$1, range$1[1] = lambda1;
  7386. boundsStream.point = boundsPoint;
  7387. p0 = null;
  7388. }
  7389. function boundsRingPoint(lambda, phi) {
  7390. if (p0) {
  7391. var delta = lambda - lambda2;
  7392. deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);
  7393. } else {
  7394. lambda00$1 = lambda, phi00$1 = phi;
  7395. }
  7396. areaStream.point(lambda, phi);
  7397. linePoint(lambda, phi);
  7398. }
  7399. function boundsRingStart() {
  7400. areaStream.lineStart();
  7401. }
  7402. function boundsRingEnd() {
  7403. boundsRingPoint(lambda00$1, phi00$1);
  7404. areaStream.lineEnd();
  7405. if (abs(deltaSum) > epsilon) lambda0$1 = -(lambda1 = 180);
  7406. range$1[0] = lambda0$1, range$1[1] = lambda1;
  7407. p0 = null;
  7408. }
  7409. // Finds the left-right distance between two longitudes.
  7410. // This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want
  7411. // the distance between ±180° to be 360°.
  7412. function angle(lambda0, lambda1) {
  7413. return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;
  7414. }
  7415. function rangeCompare(a, b) {
  7416. return a[0] - b[0];
  7417. }
  7418. function rangeContains(range$$1, x) {
  7419. return range$$1[0] <= range$$1[1] ? range$$1[0] <= x && x <= range$$1[1] : x < range$$1[0] || range$$1[1] < x;
  7420. }
  7421. var bounds = function(feature) {
  7422. var i, n, a, b, merged, deltaMax, delta;
  7423. phi1 = lambda1 = -(lambda0$1 = phi0 = Infinity);
  7424. ranges = [];
  7425. geoStream(feature, boundsStream);
  7426. // First, sort ranges by their minimum longitudes.
  7427. if (n = ranges.length) {
  7428. ranges.sort(rangeCompare);
  7429. // Then, merge any ranges that overlap.
  7430. for (i = 1, a = ranges[0], merged = [a]; i < n; ++i) {
  7431. b = ranges[i];
  7432. if (rangeContains(a, b[0]) || rangeContains(a, b[1])) {
  7433. if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
  7434. if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
  7435. } else {
  7436. merged.push(a = b);
  7437. }
  7438. }
  7439. // Finally, find the largest gap between the merged ranges.
  7440. // The final bounding box will be the inverse of this gap.
  7441. for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {
  7442. b = merged[i];
  7443. if ((delta = angle(a[1], b[0])) > deltaMax) deltaMax = delta, lambda0$1 = b[0], lambda1 = a[1];
  7444. }
  7445. }
  7446. ranges = range$1 = null;
  7447. return lambda0$1 === Infinity || phi0 === Infinity
  7448. ? [[NaN, NaN], [NaN, NaN]]
  7449. : [[lambda0$1, phi0], [lambda1, phi1]];
  7450. };
  7451. var W0;
  7452. var W1;
  7453. var X0;
  7454. var Y0;
  7455. var Z0;
  7456. var X1;
  7457. var Y1;
  7458. var Z1;
  7459. var X2;
  7460. var Y2;
  7461. var Z2;
  7462. var lambda00$2;
  7463. var phi00$2;
  7464. var x0;
  7465. var y0;
  7466. var z0; // previous point
  7467. var centroidStream = {
  7468. sphere: noop,
  7469. point: centroidPoint,
  7470. lineStart: centroidLineStart,
  7471. lineEnd: centroidLineEnd,
  7472. polygonStart: function() {
  7473. centroidStream.lineStart = centroidRingStart;
  7474. centroidStream.lineEnd = centroidRingEnd;
  7475. },
  7476. polygonEnd: function() {
  7477. centroidStream.lineStart = centroidLineStart;
  7478. centroidStream.lineEnd = centroidLineEnd;
  7479. }
  7480. };
  7481. // Arithmetic mean of Cartesian vectors.
  7482. function centroidPoint(lambda, phi) {
  7483. lambda *= radians, phi *= radians;
  7484. var cosPhi = cos(phi);
  7485. centroidPointCartesian(cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi));
  7486. }
  7487. function centroidPointCartesian(x, y, z) {
  7488. ++W0;
  7489. X0 += (x - X0) / W0;
  7490. Y0 += (y - Y0) / W0;
  7491. Z0 += (z - Z0) / W0;
  7492. }
  7493. function centroidLineStart() {
  7494. centroidStream.point = centroidLinePointFirst;
  7495. }
  7496. function centroidLinePointFirst(lambda, phi) {
  7497. lambda *= radians, phi *= radians;
  7498. var cosPhi = cos(phi);
  7499. x0 = cosPhi * cos(lambda);
  7500. y0 = cosPhi * sin(lambda);
  7501. z0 = sin(phi);
  7502. centroidStream.point = centroidLinePoint;
  7503. centroidPointCartesian(x0, y0, z0);
  7504. }
  7505. function centroidLinePoint(lambda, phi) {
  7506. lambda *= radians, phi *= radians;
  7507. var cosPhi = cos(phi),
  7508. x = cosPhi * cos(lambda),
  7509. y = cosPhi * sin(lambda),
  7510. z = sin(phi),
  7511. w = atan2(sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
  7512. W1 += w;
  7513. X1 += w * (x0 + (x0 = x));
  7514. Y1 += w * (y0 + (y0 = y));
  7515. Z1 += w * (z0 + (z0 = z));
  7516. centroidPointCartesian(x0, y0, z0);
  7517. }
  7518. function centroidLineEnd() {
  7519. centroidStream.point = centroidPoint;
  7520. }
  7521. // See J. E. Brock, The Inertia Tensor for a Spherical Triangle,
  7522. // J. Applied Mechanics 42, 239 (1975).
  7523. function centroidRingStart() {
  7524. centroidStream.point = centroidRingPointFirst;
  7525. }
  7526. function centroidRingEnd() {
  7527. centroidRingPoint(lambda00$2, phi00$2);
  7528. centroidStream.point = centroidPoint;
  7529. }
  7530. function centroidRingPointFirst(lambda, phi) {
  7531. lambda00$2 = lambda, phi00$2 = phi;
  7532. lambda *= radians, phi *= radians;
  7533. centroidStream.point = centroidRingPoint;
  7534. var cosPhi = cos(phi);
  7535. x0 = cosPhi * cos(lambda);
  7536. y0 = cosPhi * sin(lambda);
  7537. z0 = sin(phi);
  7538. centroidPointCartesian(x0, y0, z0);
  7539. }
  7540. function centroidRingPoint(lambda, phi) {
  7541. lambda *= radians, phi *= radians;
  7542. var cosPhi = cos(phi),
  7543. x = cosPhi * cos(lambda),
  7544. y = cosPhi * sin(lambda),
  7545. z = sin(phi),
  7546. cx = y0 * z - z0 * y,
  7547. cy = z0 * x - x0 * z,
  7548. cz = x0 * y - y0 * x,
  7549. m = sqrt(cx * cx + cy * cy + cz * cz),
  7550. w = asin(m), // line weight = angle
  7551. v = m && -w / m; // area weight multiplier
  7552. X2 += v * cx;
  7553. Y2 += v * cy;
  7554. Z2 += v * cz;
  7555. W1 += w;
  7556. X1 += w * (x0 + (x0 = x));
  7557. Y1 += w * (y0 + (y0 = y));
  7558. Z1 += w * (z0 + (z0 = z));
  7559. centroidPointCartesian(x0, y0, z0);
  7560. }
  7561. var centroid = function(object) {
  7562. W0 = W1 =
  7563. X0 = Y0 = Z0 =
  7564. X1 = Y1 = Z1 =
  7565. X2 = Y2 = Z2 = 0;
  7566. geoStream(object, centroidStream);
  7567. var x = X2,
  7568. y = Y2,
  7569. z = Z2,
  7570. m = x * x + y * y + z * z;
  7571. // If the area-weighted ccentroid is undefined, fall back to length-weighted ccentroid.
  7572. if (m < epsilon2) {
  7573. x = X1, y = Y1, z = Z1;
  7574. // If the feature has zero length, fall back to arithmetic mean of point vectors.
  7575. if (W1 < epsilon) x = X0, y = Y0, z = Z0;
  7576. m = x * x + y * y + z * z;
  7577. // If the feature still has an undefined ccentroid, then return.
  7578. if (m < epsilon2) return [NaN, NaN];
  7579. }
  7580. return [atan2(y, x) * degrees, asin(z / sqrt(m)) * degrees];
  7581. };
  7582. var constant = function(x) {
  7583. return function() {
  7584. return x;
  7585. };
  7586. };
  7587. var compose = function(a, b) {
  7588. function compose(x, y) {
  7589. return x = a(x, y), b(x[0], x[1]);
  7590. }
  7591. if (a.invert && b.invert) compose.invert = function(x, y) {
  7592. return x = b.invert(x, y), x && a.invert(x[0], x[1]);
  7593. };
  7594. return compose;
  7595. };
  7596. function rotationIdentity(lambda, phi) {
  7597. return [lambda > pi ? lambda - tau : lambda < -pi ? lambda + tau : lambda, phi];
  7598. }
  7599. rotationIdentity.invert = rotationIdentity;
  7600. function rotateRadians(deltaLambda, deltaPhi, deltaGamma) {
  7601. return (deltaLambda %= tau) ? (deltaPhi || deltaGamma ? compose(rotationLambda(deltaLambda), rotationPhiGamma(deltaPhi, deltaGamma))
  7602. : rotationLambda(deltaLambda))
  7603. : (deltaPhi || deltaGamma ? rotationPhiGamma(deltaPhi, deltaGamma)
  7604. : rotationIdentity);
  7605. }
  7606. function forwardRotationLambda(deltaLambda) {
  7607. return function(lambda, phi) {
  7608. return lambda += deltaLambda, [lambda > pi ? lambda - tau : lambda < -pi ? lambda + tau : lambda, phi];
  7609. };
  7610. }
  7611. function rotationLambda(deltaLambda) {
  7612. var rotation = forwardRotationLambda(deltaLambda);
  7613. rotation.invert = forwardRotationLambda(-deltaLambda);
  7614. return rotation;
  7615. }
  7616. function rotationPhiGamma(deltaPhi, deltaGamma) {
  7617. var cosDeltaPhi = cos(deltaPhi),
  7618. sinDeltaPhi = sin(deltaPhi),
  7619. cosDeltaGamma = cos(deltaGamma),
  7620. sinDeltaGamma = sin(deltaGamma);
  7621. function rotation(lambda, phi) {
  7622. var cosPhi = cos(phi),
  7623. x = cos(lambda) * cosPhi,
  7624. y = sin(lambda) * cosPhi,
  7625. z = sin(phi),
  7626. k = z * cosDeltaPhi + x * sinDeltaPhi;
  7627. return [
  7628. atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi),
  7629. asin(k * cosDeltaGamma + y * sinDeltaGamma)
  7630. ];
  7631. }
  7632. rotation.invert = function(lambda, phi) {
  7633. var cosPhi = cos(phi),
  7634. x = cos(lambda) * cosPhi,
  7635. y = sin(lambda) * cosPhi,
  7636. z = sin(phi),
  7637. k = z * cosDeltaGamma - y * sinDeltaGamma;
  7638. return [
  7639. atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi),
  7640. asin(k * cosDeltaPhi - x * sinDeltaPhi)
  7641. ];
  7642. };
  7643. return rotation;
  7644. }
  7645. var rotation = function(rotate) {
  7646. rotate = rotateRadians(rotate[0] * radians, rotate[1] * radians, rotate.length > 2 ? rotate[2] * radians : 0);
  7647. function forward(coordinates) {
  7648. coordinates = rotate(coordinates[0] * radians, coordinates[1] * radians);
  7649. return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;
  7650. }
  7651. forward.invert = function(coordinates) {
  7652. coordinates = rotate.invert(coordinates[0] * radians, coordinates[1] * radians);
  7653. return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;
  7654. };
  7655. return forward;
  7656. };
  7657. // Generates a circle centered at [0°, 0°], with a given radius and precision.
  7658. function circleStream(stream, radius, delta, direction, t0, t1) {
  7659. if (!delta) return;
  7660. var cosRadius = cos(radius),
  7661. sinRadius = sin(radius),
  7662. step = direction * delta;
  7663. if (t0 == null) {
  7664. t0 = radius + direction * tau;
  7665. t1 = radius - step / 2;
  7666. } else {
  7667. t0 = circleRadius(cosRadius, t0);
  7668. t1 = circleRadius(cosRadius, t1);
  7669. if (direction > 0 ? t0 < t1 : t0 > t1) t0 += direction * tau;
  7670. }
  7671. for (var point, t = t0; direction > 0 ? t > t1 : t < t1; t -= step) {
  7672. point = spherical([cosRadius, -sinRadius * cos(t), -sinRadius * sin(t)]);
  7673. stream.point(point[0], point[1]);
  7674. }
  7675. }
  7676. // Returns the signed angle of a cartesian point relative to [cosRadius, 0, 0].
  7677. function circleRadius(cosRadius, point) {
  7678. point = cartesian(point), point[0] -= cosRadius;
  7679. cartesianNormalizeInPlace(point);
  7680. var radius = acos(-point[1]);
  7681. return ((-point[2] < 0 ? -radius : radius) + tau - epsilon) % tau;
  7682. }
  7683. var circle = function() {
  7684. var center = constant([0, 0]),
  7685. radius = constant(90),
  7686. precision = constant(6),
  7687. ring,
  7688. rotate,
  7689. stream = {point: point};
  7690. function point(x, y) {
  7691. ring.push(x = rotate(x, y));
  7692. x[0] *= degrees, x[1] *= degrees;
  7693. }
  7694. function circle() {
  7695. var c = center.apply(this, arguments),
  7696. r = radius.apply(this, arguments) * radians,
  7697. p = precision.apply(this, arguments) * radians;
  7698. ring = [];
  7699. rotate = rotateRadians(-c[0] * radians, -c[1] * radians, 0).invert;
  7700. circleStream(stream, r, p, 1);
  7701. c = {type: "Polygon", coordinates: [ring]};
  7702. ring = rotate = null;
  7703. return c;
  7704. }
  7705. circle.center = function(_) {
  7706. return arguments.length ? (center = typeof _ === "function" ? _ : constant([+_[0], +_[1]]), circle) : center;
  7707. };
  7708. circle.radius = function(_) {
  7709. return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), circle) : radius;
  7710. };
  7711. circle.precision = function(_) {
  7712. return arguments.length ? (precision = typeof _ === "function" ? _ : constant(+_), circle) : precision;
  7713. };
  7714. return circle;
  7715. };
  7716. var clipBuffer = function() {
  7717. var lines = [],
  7718. line;
  7719. return {
  7720. point: function(x, y) {
  7721. line.push([x, y]);
  7722. },
  7723. lineStart: function() {
  7724. lines.push(line = []);
  7725. },
  7726. lineEnd: noop,
  7727. rejoin: function() {
  7728. if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
  7729. },
  7730. result: function() {
  7731. var result = lines;
  7732. lines = [];
  7733. line = null;
  7734. return result;
  7735. }
  7736. };
  7737. };
  7738. var pointEqual = function(a, b) {
  7739. return abs(a[0] - b[0]) < epsilon && abs(a[1] - b[1]) < epsilon;
  7740. };
  7741. function Intersection(point, points, other, entry) {
  7742. this.x = point;
  7743. this.z = points;
  7744. this.o = other; // another intersection
  7745. this.e = entry; // is an entry?
  7746. this.v = false; // visited
  7747. this.n = this.p = null; // next & previous
  7748. }
  7749. // A generalized polygon clipping algorithm: given a polygon that has been cut
  7750. // into its visible line segments, and rejoins the segments by interpolating
  7751. // along the clip edge.
  7752. var clipRejoin = function(segments, compareIntersection, startInside, interpolate, stream) {
  7753. var subject = [],
  7754. clip = [],
  7755. i,
  7756. n;
  7757. segments.forEach(function(segment) {
  7758. if ((n = segment.length - 1) <= 0) return;
  7759. var n, p0 = segment[0], p1 = segment[n], x;
  7760. // If the first and last points of a segment are coincident, then treat as a
  7761. // closed ring. TODO if all rings are closed, then the winding order of the
  7762. // exterior ring should be checked.
  7763. if (pointEqual(p0, p1)) {
  7764. stream.lineStart();
  7765. for (i = 0; i < n; ++i) stream.point((p0 = segment[i])[0], p0[1]);
  7766. stream.lineEnd();
  7767. return;
  7768. }
  7769. subject.push(x = new Intersection(p0, segment, null, true));
  7770. clip.push(x.o = new Intersection(p0, null, x, false));
  7771. subject.push(x = new Intersection(p1, segment, null, false));
  7772. clip.push(x.o = new Intersection(p1, null, x, true));
  7773. });
  7774. if (!subject.length) return;
  7775. clip.sort(compareIntersection);
  7776. link(subject);
  7777. link(clip);
  7778. for (i = 0, n = clip.length; i < n; ++i) {
  7779. clip[i].e = startInside = !startInside;
  7780. }
  7781. var start = subject[0],
  7782. points,
  7783. point;
  7784. while (1) {
  7785. // Find first unvisited intersection.
  7786. var current = start,
  7787. isSubject = true;
  7788. while (current.v) if ((current = current.n) === start) return;
  7789. points = current.z;
  7790. stream.lineStart();
  7791. do {
  7792. current.v = current.o.v = true;
  7793. if (current.e) {
  7794. if (isSubject) {
  7795. for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]);
  7796. } else {
  7797. interpolate(current.x, current.n.x, 1, stream);
  7798. }
  7799. current = current.n;
  7800. } else {
  7801. if (isSubject) {
  7802. points = current.p.z;
  7803. for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]);
  7804. } else {
  7805. interpolate(current.x, current.p.x, -1, stream);
  7806. }
  7807. current = current.p;
  7808. }
  7809. current = current.o;
  7810. points = current.z;
  7811. isSubject = !isSubject;
  7812. } while (!current.v);
  7813. stream.lineEnd();
  7814. }
  7815. };
  7816. function link(array) {
  7817. if (!(n = array.length)) return;
  7818. var n,
  7819. i = 0,
  7820. a = array[0],
  7821. b;
  7822. while (++i < n) {
  7823. a.n = b = array[i];
  7824. b.p = a;
  7825. a = b;
  7826. }
  7827. a.n = b = array[0];
  7828. b.p = a;
  7829. }
  7830. var sum = adder();
  7831. var polygonContains = function(polygon, point) {
  7832. var lambda = point[0],
  7833. phi = point[1],
  7834. normal = [sin(lambda), -cos(lambda), 0],
  7835. angle = 0,
  7836. winding = 0;
  7837. sum.reset();
  7838. for (var i = 0, n = polygon.length; i < n; ++i) {
  7839. if (!(m = (ring = polygon[i]).length)) continue;
  7840. var ring,
  7841. m,
  7842. point0 = ring[m - 1],
  7843. lambda0 = point0[0],
  7844. phi0 = point0[1] / 2 + quarterPi,
  7845. sinPhi0 = sin(phi0),
  7846. cosPhi0 = cos(phi0);
  7847. for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) {
  7848. var point1 = ring[j],
  7849. lambda1 = point1[0],
  7850. phi1 = point1[1] / 2 + quarterPi,
  7851. sinPhi1 = sin(phi1),
  7852. cosPhi1 = cos(phi1),
  7853. delta = lambda1 - lambda0,
  7854. sign$$1 = delta >= 0 ? 1 : -1,
  7855. absDelta = sign$$1 * delta,
  7856. antimeridian = absDelta > pi,
  7857. k = sinPhi0 * sinPhi1;
  7858. sum.add(atan2(k * sign$$1 * sin(absDelta), cosPhi0 * cosPhi1 + k * cos(absDelta)));
  7859. angle += antimeridian ? delta + sign$$1 * tau : delta;
  7860. // Are the longitudes either side of the point’s meridian (lambda),
  7861. // and are the latitudes smaller than the parallel (phi)?
  7862. if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {
  7863. var arc = cartesianCross(cartesian(point0), cartesian(point1));
  7864. cartesianNormalizeInPlace(arc);
  7865. var intersection = cartesianCross(normal, arc);
  7866. cartesianNormalizeInPlace(intersection);
  7867. var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]);
  7868. if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {
  7869. winding += antimeridian ^ delta >= 0 ? 1 : -1;
  7870. }
  7871. }
  7872. }
  7873. }
  7874. // First, determine whether the South pole is inside or outside:
  7875. //
  7876. // It is inside if:
  7877. // * the polygon winds around it in a clockwise direction.
  7878. // * the polygon does not (cumulatively) wind around it, but has a negative
  7879. // (counter-clockwise) area.
  7880. //
  7881. // Second, count the (signed) number of times a segment crosses a lambda
  7882. // from the point to the South pole. If it is zero, then the point is the
  7883. // same side as the South pole.
  7884. return (angle < -epsilon || angle < epsilon && sum < -epsilon) ^ (winding & 1);
  7885. };
  7886. var clip = function(pointVisible, clipLine, interpolate, start) {
  7887. return function(sink) {
  7888. var line = clipLine(sink),
  7889. ringBuffer = clipBuffer(),
  7890. ringSink = clipLine(ringBuffer),
  7891. polygonStarted = false,
  7892. polygon,
  7893. segments,
  7894. ring;
  7895. var clip = {
  7896. point: point,
  7897. lineStart: lineStart,
  7898. lineEnd: lineEnd,
  7899. polygonStart: function() {
  7900. clip.point = pointRing;
  7901. clip.lineStart = ringStart;
  7902. clip.lineEnd = ringEnd;
  7903. segments = [];
  7904. polygon = [];
  7905. },
  7906. polygonEnd: function() {
  7907. clip.point = point;
  7908. clip.lineStart = lineStart;
  7909. clip.lineEnd = lineEnd;
  7910. segments = d3Array.merge(segments);
  7911. var startInside = polygonContains(polygon, start);
  7912. if (segments.length) {
  7913. if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
  7914. clipRejoin(segments, compareIntersection, startInside, interpolate, sink);
  7915. } else if (startInside) {
  7916. if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
  7917. sink.lineStart();
  7918. interpolate(null, null, 1, sink);
  7919. sink.lineEnd();
  7920. }
  7921. if (polygonStarted) sink.polygonEnd(), polygonStarted = false;
  7922. segments = polygon = null;
  7923. },
  7924. sphere: function() {
  7925. sink.polygonStart();
  7926. sink.lineStart();
  7927. interpolate(null, null, 1, sink);
  7928. sink.lineEnd();
  7929. sink.polygonEnd();
  7930. }
  7931. };
  7932. function point(lambda, phi) {
  7933. if (pointVisible(lambda, phi)) sink.point(lambda, phi);
  7934. }
  7935. function pointLine(lambda, phi) {
  7936. line.point(lambda, phi);
  7937. }
  7938. function lineStart() {
  7939. clip.point = pointLine;
  7940. line.lineStart();
  7941. }
  7942. function lineEnd() {
  7943. clip.point = point;
  7944. line.lineEnd();
  7945. }
  7946. function pointRing(lambda, phi) {
  7947. ring.push([lambda, phi]);
  7948. ringSink.point(lambda, phi);
  7949. }
  7950. function ringStart() {
  7951. ringSink.lineStart();
  7952. ring = [];
  7953. }
  7954. function ringEnd() {
  7955. pointRing(ring[0][0], ring[0][1]);
  7956. ringSink.lineEnd();
  7957. var clean = ringSink.clean(),
  7958. ringSegments = ringBuffer.result(),
  7959. i, n = ringSegments.length, m,
  7960. segment,
  7961. point;
  7962. ring.pop();
  7963. polygon.push(ring);
  7964. ring = null;
  7965. if (!n) return;
  7966. // No intersections.
  7967. if (clean & 1) {
  7968. segment = ringSegments[0];
  7969. if ((m = segment.length - 1) > 0) {
  7970. if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
  7971. sink.lineStart();
  7972. for (i = 0; i < m; ++i) sink.point((point = segment[i])[0], point[1]);
  7973. sink.lineEnd();
  7974. }
  7975. return;
  7976. }
  7977. // Rejoin connected segments.
  7978. // TODO reuse ringBuffer.rejoin()?
  7979. if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
  7980. segments.push(ringSegments.filter(validSegment));
  7981. }
  7982. return clip;
  7983. };
  7984. };
  7985. function validSegment(segment) {
  7986. return segment.length > 1;
  7987. }
  7988. // Intersections are sorted along the clip edge. For both antimeridian cutting
  7989. // and circle clipping, the same comparison is used.
  7990. function compareIntersection(a, b) {
  7991. return ((a = a.x)[0] < 0 ? a[1] - halfPi - epsilon : halfPi - a[1])
  7992. - ((b = b.x)[0] < 0 ? b[1] - halfPi - epsilon : halfPi - b[1]);
  7993. }
  7994. var clipAntimeridian = clip(
  7995. function() { return true; },
  7996. clipAntimeridianLine,
  7997. clipAntimeridianInterpolate,
  7998. [-pi, -halfPi]
  7999. );
  8000. // Takes a line and cuts into visible segments. Return values: 0 - there were
  8001. // intersections or the line was empty; 1 - no intersections; 2 - there were
  8002. // intersections, and the first and last segments should be rejoined.
  8003. function clipAntimeridianLine(stream) {
  8004. var lambda0 = NaN,
  8005. phi0 = NaN,
  8006. sign0 = NaN,
  8007. clean; // no intersections
  8008. return {
  8009. lineStart: function() {
  8010. stream.lineStart();
  8011. clean = 1;
  8012. },
  8013. point: function(lambda1, phi1) {
  8014. var sign1 = lambda1 > 0 ? pi : -pi,
  8015. delta = abs(lambda1 - lambda0);
  8016. if (abs(delta - pi) < epsilon) { // line crosses a pole
  8017. stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? halfPi : -halfPi);
  8018. stream.point(sign0, phi0);
  8019. stream.lineEnd();
  8020. stream.lineStart();
  8021. stream.point(sign1, phi0);
  8022. stream.point(lambda1, phi0);
  8023. clean = 0;
  8024. } else if (sign0 !== sign1 && delta >= pi) { // line crosses antimeridian
  8025. if (abs(lambda0 - sign0) < epsilon) lambda0 -= sign0 * epsilon; // handle degeneracies
  8026. if (abs(lambda1 - sign1) < epsilon) lambda1 -= sign1 * epsilon;
  8027. phi0 = clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1);
  8028. stream.point(sign0, phi0);
  8029. stream.lineEnd();
  8030. stream.lineStart();
  8031. stream.point(sign1, phi0);
  8032. clean = 0;
  8033. }
  8034. stream.point(lambda0 = lambda1, phi0 = phi1);
  8035. sign0 = sign1;
  8036. },
  8037. lineEnd: function() {
  8038. stream.lineEnd();
  8039. lambda0 = phi0 = NaN;
  8040. },
  8041. clean: function() {
  8042. return 2 - clean; // if intersections, rejoin first and last segments
  8043. }
  8044. };
  8045. }
  8046. function clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) {
  8047. var cosPhi0,
  8048. cosPhi1,
  8049. sinLambda0Lambda1 = sin(lambda0 - lambda1);
  8050. return abs(sinLambda0Lambda1) > epsilon
  8051. ? atan((sin(phi0) * (cosPhi1 = cos(phi1)) * sin(lambda1)
  8052. - sin(phi1) * (cosPhi0 = cos(phi0)) * sin(lambda0))
  8053. / (cosPhi0 * cosPhi1 * sinLambda0Lambda1))
  8054. : (phi0 + phi1) / 2;
  8055. }
  8056. function clipAntimeridianInterpolate(from, to, direction, stream) {
  8057. var phi;
  8058. if (from == null) {
  8059. phi = direction * halfPi;
  8060. stream.point(-pi, phi);
  8061. stream.point(0, phi);
  8062. stream.point(pi, phi);
  8063. stream.point(pi, 0);
  8064. stream.point(pi, -phi);
  8065. stream.point(0, -phi);
  8066. stream.point(-pi, -phi);
  8067. stream.point(-pi, 0);
  8068. stream.point(-pi, phi);
  8069. } else if (abs(from[0] - to[0]) > epsilon) {
  8070. var lambda = from[0] < to[0] ? pi : -pi;
  8071. phi = direction * lambda / 2;
  8072. stream.point(-lambda, phi);
  8073. stream.point(0, phi);
  8074. stream.point(lambda, phi);
  8075. } else {
  8076. stream.point(to[0], to[1]);
  8077. }
  8078. }
  8079. var clipCircle = function(radius) {
  8080. var cr = cos(radius),
  8081. delta = 6 * radians,
  8082. smallRadius = cr > 0,
  8083. notHemisphere = abs(cr) > epsilon; // TODO optimise for this common case
  8084. function interpolate(from, to, direction, stream) {
  8085. circleStream(stream, radius, delta, direction, from, to);
  8086. }
  8087. function visible(lambda, phi) {
  8088. return cos(lambda) * cos(phi) > cr;
  8089. }
  8090. // Takes a line and cuts into visible segments. Return values used for polygon
  8091. // clipping: 0 - there were intersections or the line was empty; 1 - no
  8092. // intersections 2 - there were intersections, and the first and last segments
  8093. // should be rejoined.
  8094. function clipLine(stream) {
  8095. var point0, // previous point
  8096. c0, // code for previous point
  8097. v0, // visibility of previous point
  8098. v00, // visibility of first point
  8099. clean; // no intersections
  8100. return {
  8101. lineStart: function() {
  8102. v00 = v0 = false;
  8103. clean = 1;
  8104. },
  8105. point: function(lambda, phi) {
  8106. var point1 = [lambda, phi],
  8107. point2,
  8108. v = visible(lambda, phi),
  8109. c = smallRadius
  8110. ? v ? 0 : code(lambda, phi)
  8111. : v ? code(lambda + (lambda < 0 ? pi : -pi), phi) : 0;
  8112. if (!point0 && (v00 = v0 = v)) stream.lineStart();
  8113. // Handle degeneracies.
  8114. // TODO ignore if not clipping polygons.
  8115. if (v !== v0) {
  8116. point2 = intersect(point0, point1);
  8117. if (!point2 || pointEqual(point0, point2) || pointEqual(point1, point2)) {
  8118. point1[0] += epsilon;
  8119. point1[1] += epsilon;
  8120. v = visible(point1[0], point1[1]);
  8121. }
  8122. }
  8123. if (v !== v0) {
  8124. clean = 0;
  8125. if (v) {
  8126. // outside going in
  8127. stream.lineStart();
  8128. point2 = intersect(point1, point0);
  8129. stream.point(point2[0], point2[1]);
  8130. } else {
  8131. // inside going out
  8132. point2 = intersect(point0, point1);
  8133. stream.point(point2[0], point2[1]);
  8134. stream.lineEnd();
  8135. }
  8136. point0 = point2;
  8137. } else if (notHemisphere && point0 && smallRadius ^ v) {
  8138. var t;
  8139. // If the codes for two points are different, or are both zero,
  8140. // and there this segment intersects with the small circle.
  8141. if (!(c & c0) && (t = intersect(point1, point0, true))) {
  8142. clean = 0;
  8143. if (smallRadius) {
  8144. stream.lineStart();
  8145. stream.point(t[0][0], t[0][1]);
  8146. stream.point(t[1][0], t[1][1]);
  8147. stream.lineEnd();
  8148. } else {
  8149. stream.point(t[1][0], t[1][1]);
  8150. stream.lineEnd();
  8151. stream.lineStart();
  8152. stream.point(t[0][0], t[0][1]);
  8153. }
  8154. }
  8155. }
  8156. if (v && (!point0 || !pointEqual(point0, point1))) {
  8157. stream.point(point1[0], point1[1]);
  8158. }
  8159. point0 = point1, v0 = v, c0 = c;
  8160. },
  8161. lineEnd: function() {
  8162. if (v0) stream.lineEnd();
  8163. point0 = null;
  8164. },
  8165. // Rejoin first and last segments if there were intersections and the first
  8166. // and last points were visible.
  8167. clean: function() {
  8168. return clean | ((v00 && v0) << 1);
  8169. }
  8170. };
  8171. }
  8172. // Intersects the great circle between a and b with the clip circle.
  8173. function intersect(a, b, two) {
  8174. var pa = cartesian(a),
  8175. pb = cartesian(b);
  8176. // We have two planes, n1.p = d1 and n2.p = d2.
  8177. // Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2).
  8178. var n1 = [1, 0, 0], // normal
  8179. n2 = cartesianCross(pa, pb),
  8180. n2n2 = cartesianDot(n2, n2),
  8181. n1n2 = n2[0], // cartesianDot(n1, n2),
  8182. determinant = n2n2 - n1n2 * n1n2;
  8183. // Two polar points.
  8184. if (!determinant) return !two && a;
  8185. var c1 = cr * n2n2 / determinant,
  8186. c2 = -cr * n1n2 / determinant,
  8187. n1xn2 = cartesianCross(n1, n2),
  8188. A = cartesianScale(n1, c1),
  8189. B = cartesianScale(n2, c2);
  8190. cartesianAddInPlace(A, B);
  8191. // Solve |p(t)|^2 = 1.
  8192. var u = n1xn2,
  8193. w = cartesianDot(A, u),
  8194. uu = cartesianDot(u, u),
  8195. t2 = w * w - uu * (cartesianDot(A, A) - 1);
  8196. if (t2 < 0) return;
  8197. var t = sqrt(t2),
  8198. q = cartesianScale(u, (-w - t) / uu);
  8199. cartesianAddInPlace(q, A);
  8200. q = spherical(q);
  8201. if (!two) return q;
  8202. // Two intersection points.
  8203. var lambda0 = a[0],
  8204. lambda1 = b[0],
  8205. phi0 = a[1],
  8206. phi1 = b[1],
  8207. z;
  8208. if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;
  8209. var delta = lambda1 - lambda0,
  8210. polar = abs(delta - pi) < epsilon,
  8211. meridian = polar || delta < epsilon;
  8212. if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;
  8213. // Check that the first point is between a and b.
  8214. if (meridian
  8215. ? polar
  8216. ? phi0 + phi1 > 0 ^ q[1] < (abs(q[0] - lambda0) < epsilon ? phi0 : phi1)
  8217. : phi0 <= q[1] && q[1] <= phi1
  8218. : delta > pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) {
  8219. var q1 = cartesianScale(u, (-w + t) / uu);
  8220. cartesianAddInPlace(q1, A);
  8221. return [q, spherical(q1)];
  8222. }
  8223. }
  8224. // Generates a 4-bit vector representing the location of a point relative to
  8225. // the small circle's bounding box.
  8226. function code(lambda, phi) {
  8227. var r = smallRadius ? radius : pi - radius,
  8228. code = 0;
  8229. if (lambda < -r) code |= 1; // left
  8230. else if (lambda > r) code |= 2; // right
  8231. if (phi < -r) code |= 4; // below
  8232. else if (phi > r) code |= 8; // above
  8233. return code;
  8234. }
  8235. return clip(visible, clipLine, interpolate, smallRadius ? [0, -radius] : [-pi, radius - pi]);
  8236. };
  8237. var clipLine = function(a, b, x0, y0, x1, y1) {
  8238. var ax = a[0],
  8239. ay = a[1],
  8240. bx = b[0],
  8241. by = b[1],
  8242. t0 = 0,
  8243. t1 = 1,
  8244. dx = bx - ax,
  8245. dy = by - ay,
  8246. r;
  8247. r = x0 - ax;
  8248. if (!dx && r > 0) return;
  8249. r /= dx;
  8250. if (dx < 0) {
  8251. if (r < t0) return;
  8252. if (r < t1) t1 = r;
  8253. } else if (dx > 0) {
  8254. if (r > t1) return;
  8255. if (r > t0) t0 = r;
  8256. }
  8257. r = x1 - ax;
  8258. if (!dx && r < 0) return;
  8259. r /= dx;
  8260. if (dx < 0) {
  8261. if (r > t1) return;
  8262. if (r > t0) t0 = r;
  8263. } else if (dx > 0) {
  8264. if (r < t0) return;
  8265. if (r < t1) t1 = r;
  8266. }
  8267. r = y0 - ay;
  8268. if (!dy && r > 0) return;
  8269. r /= dy;
  8270. if (dy < 0) {
  8271. if (r < t0) return;
  8272. if (r < t1) t1 = r;
  8273. } else if (dy > 0) {
  8274. if (r > t1) return;
  8275. if (r > t0) t0 = r;
  8276. }
  8277. r = y1 - ay;
  8278. if (!dy && r < 0) return;
  8279. r /= dy;
  8280. if (dy < 0) {
  8281. if (r > t1) return;
  8282. if (r > t0) t0 = r;
  8283. } else if (dy > 0) {
  8284. if (r < t0) return;
  8285. if (r < t1) t1 = r;
  8286. }
  8287. if (t0 > 0) a[0] = ax + t0 * dx, a[1] = ay + t0 * dy;
  8288. if (t1 < 1) b[0] = ax + t1 * dx, b[1] = ay + t1 * dy;
  8289. return true;
  8290. };
  8291. var clipMax = 1e9;
  8292. var clipMin = -clipMax;
  8293. // TODO Use d3-polygon’s polygonContains here for the ring check?
  8294. // TODO Eliminate duplicate buffering in clipBuffer and polygon.push?
  8295. function clipRectangle(x0, y0, x1, y1) {
  8296. function visible(x, y) {
  8297. return x0 <= x && x <= x1 && y0 <= y && y <= y1;
  8298. }
  8299. function interpolate(from, to, direction, stream) {
  8300. var a = 0, a1 = 0;
  8301. if (from == null
  8302. || (a = corner(from, direction)) !== (a1 = corner(to, direction))
  8303. || comparePoint(from, to) < 0 ^ direction > 0) {
  8304. do stream.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
  8305. while ((a = (a + direction + 4) % 4) !== a1);
  8306. } else {
  8307. stream.point(to[0], to[1]);
  8308. }
  8309. }
  8310. function corner(p, direction) {
  8311. return abs(p[0] - x0) < epsilon ? direction > 0 ? 0 : 3
  8312. : abs(p[0] - x1) < epsilon ? direction > 0 ? 2 : 1
  8313. : abs(p[1] - y0) < epsilon ? direction > 0 ? 1 : 0
  8314. : direction > 0 ? 3 : 2; // abs(p[1] - y1) < epsilon
  8315. }
  8316. function compareIntersection(a, b) {
  8317. return comparePoint(a.x, b.x);
  8318. }
  8319. function comparePoint(a, b) {
  8320. var ca = corner(a, 1),
  8321. cb = corner(b, 1);
  8322. return ca !== cb ? ca - cb
  8323. : ca === 0 ? b[1] - a[1]
  8324. : ca === 1 ? a[0] - b[0]
  8325. : ca === 2 ? a[1] - b[1]
  8326. : b[0] - a[0];
  8327. }
  8328. return function(stream) {
  8329. var activeStream = stream,
  8330. bufferStream = clipBuffer(),
  8331. segments,
  8332. polygon,
  8333. ring,
  8334. x__, y__, v__, // first point
  8335. x_, y_, v_, // previous point
  8336. first,
  8337. clean;
  8338. var clipStream = {
  8339. point: point,
  8340. lineStart: lineStart,
  8341. lineEnd: lineEnd,
  8342. polygonStart: polygonStart,
  8343. polygonEnd: polygonEnd
  8344. };
  8345. function point(x, y) {
  8346. if (visible(x, y)) activeStream.point(x, y);
  8347. }
  8348. function polygonInside() {
  8349. var winding = 0;
  8350. for (var i = 0, n = polygon.length; i < n; ++i) {
  8351. for (var ring = polygon[i], j = 1, m = ring.length, point = ring[0], a0, a1, b0 = point[0], b1 = point[1]; j < m; ++j) {
  8352. a0 = b0, a1 = b1, point = ring[j], b0 = point[0], b1 = point[1];
  8353. if (a1 <= y1) { if (b1 > y1 && (b0 - a0) * (y1 - a1) > (b1 - a1) * (x0 - a0)) ++winding; }
  8354. else { if (b1 <= y1 && (b0 - a0) * (y1 - a1) < (b1 - a1) * (x0 - a0)) --winding; }
  8355. }
  8356. }
  8357. return winding;
  8358. }
  8359. // Buffer geometry within a polygon and then clip it en masse.
  8360. function polygonStart() {
  8361. activeStream = bufferStream, segments = [], polygon = [], clean = true;
  8362. }
  8363. function polygonEnd() {
  8364. var startInside = polygonInside(),
  8365. cleanInside = clean && startInside,
  8366. visible = (segments = d3Array.merge(segments)).length;
  8367. if (cleanInside || visible) {
  8368. stream.polygonStart();
  8369. if (cleanInside) {
  8370. stream.lineStart();
  8371. interpolate(null, null, 1, stream);
  8372. stream.lineEnd();
  8373. }
  8374. if (visible) {
  8375. clipRejoin(segments, compareIntersection, startInside, interpolate, stream);
  8376. }
  8377. stream.polygonEnd();
  8378. }
  8379. activeStream = stream, segments = polygon = ring = null;
  8380. }
  8381. function lineStart() {
  8382. clipStream.point = linePoint;
  8383. if (polygon) polygon.push(ring = []);
  8384. first = true;
  8385. v_ = false;
  8386. x_ = y_ = NaN;
  8387. }
  8388. // TODO rather than special-case polygons, simply handle them separately.
  8389. // Ideally, coincident intersection points should be jittered to avoid
  8390. // clipping issues.
  8391. function lineEnd() {
  8392. if (segments) {
  8393. linePoint(x__, y__);
  8394. if (v__ && v_) bufferStream.rejoin();
  8395. segments.push(bufferStream.result());
  8396. }
  8397. clipStream.point = point;
  8398. if (v_) activeStream.lineEnd();
  8399. }
  8400. function linePoint(x, y) {
  8401. var v = visible(x, y);
  8402. if (polygon) ring.push([x, y]);
  8403. if (first) {
  8404. x__ = x, y__ = y, v__ = v;
  8405. first = false;
  8406. if (v) {
  8407. activeStream.lineStart();
  8408. activeStream.point(x, y);
  8409. }
  8410. } else {
  8411. if (v && v_) activeStream.point(x, y);
  8412. else {
  8413. var a = [x_ = Math.max(clipMin, Math.min(clipMax, x_)), y_ = Math.max(clipMin, Math.min(clipMax, y_))],
  8414. b = [x = Math.max(clipMin, Math.min(clipMax, x)), y = Math.max(clipMin, Math.min(clipMax, y))];
  8415. if (clipLine(a, b, x0, y0, x1, y1)) {
  8416. if (!v_) {
  8417. activeStream.lineStart();
  8418. activeStream.point(a[0], a[1]);
  8419. }
  8420. activeStream.point(b[0], b[1]);
  8421. if (!v) activeStream.lineEnd();
  8422. clean = false;
  8423. } else if (v) {
  8424. activeStream.lineStart();
  8425. activeStream.point(x, y);
  8426. clean = false;
  8427. }
  8428. }
  8429. }
  8430. x_ = x, y_ = y, v_ = v;
  8431. }
  8432. return clipStream;
  8433. };
  8434. }
  8435. var extent = function() {
  8436. var x0 = 0,
  8437. y0 = 0,
  8438. x1 = 960,
  8439. y1 = 500,
  8440. cache,
  8441. cacheStream,
  8442. clip;
  8443. return clip = {
  8444. stream: function(stream) {
  8445. return cache && cacheStream === stream ? cache : cache = clipRectangle(x0, y0, x1, y1)(cacheStream = stream);
  8446. },
  8447. extent: function(_) {
  8448. return arguments.length ? (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1], cache = cacheStream = null, clip) : [[x0, y0], [x1, y1]];
  8449. }
  8450. };
  8451. };
  8452. var lengthSum = adder();
  8453. var lambda0$2;
  8454. var sinPhi0$1;
  8455. var cosPhi0$1;
  8456. var lengthStream = {
  8457. sphere: noop,
  8458. point: noop,
  8459. lineStart: lengthLineStart,
  8460. lineEnd: noop,
  8461. polygonStart: noop,
  8462. polygonEnd: noop
  8463. };
  8464. function lengthLineStart() {
  8465. lengthStream.point = lengthPointFirst;
  8466. lengthStream.lineEnd = lengthLineEnd;
  8467. }
  8468. function lengthLineEnd() {
  8469. lengthStream.point = lengthStream.lineEnd = noop;
  8470. }
  8471. function lengthPointFirst(lambda, phi) {
  8472. lambda *= radians, phi *= radians;
  8473. lambda0$2 = lambda, sinPhi0$1 = sin(phi), cosPhi0$1 = cos(phi);
  8474. lengthStream.point = lengthPoint;
  8475. }
  8476. function lengthPoint(lambda, phi) {
  8477. lambda *= radians, phi *= radians;
  8478. var sinPhi = sin(phi),
  8479. cosPhi = cos(phi),
  8480. delta = abs(lambda - lambda0$2),
  8481. cosDelta = cos(delta),
  8482. sinDelta = sin(delta),
  8483. x = cosPhi * sinDelta,
  8484. y = cosPhi0$1 * sinPhi - sinPhi0$1 * cosPhi * cosDelta,
  8485. z = sinPhi0$1 * sinPhi + cosPhi0$1 * cosPhi * cosDelta;
  8486. lengthSum.add(atan2(sqrt(x * x + y * y), z));
  8487. lambda0$2 = lambda, sinPhi0$1 = sinPhi, cosPhi0$1 = cosPhi;
  8488. }
  8489. var length = function(object) {
  8490. lengthSum.reset();
  8491. geoStream(object, lengthStream);
  8492. return +lengthSum;
  8493. };
  8494. var coordinates = [null, null];
  8495. var object = {type: "LineString", coordinates: coordinates};
  8496. var distance = function(a, b) {
  8497. coordinates[0] = a;
  8498. coordinates[1] = b;
  8499. return length(object);
  8500. };
  8501. var containsObjectType = {
  8502. Feature: function(object, point) {
  8503. return containsGeometry(object.geometry, point);
  8504. },
  8505. FeatureCollection: function(object, point) {
  8506. var features = object.features, i = -1, n = features.length;
  8507. while (++i < n) if (containsGeometry(features[i].geometry, point)) return true;
  8508. return false;
  8509. }
  8510. };
  8511. var containsGeometryType = {
  8512. Sphere: function() {
  8513. return true;
  8514. },
  8515. Point: function(object, point) {
  8516. return containsPoint(object.coordinates, point);
  8517. },
  8518. MultiPoint: function(object, point) {
  8519. var coordinates = object.coordinates, i = -1, n = coordinates.length;
  8520. while (++i < n) if (containsPoint(coordinates[i], point)) return true;
  8521. return false;
  8522. },
  8523. LineString: function(object, point) {
  8524. return containsLine(object.coordinates, point);
  8525. },
  8526. MultiLineString: function(object, point) {
  8527. var coordinates = object.coordinates, i = -1, n = coordinates.length;
  8528. while (++i < n) if (containsLine(coordinates[i], point)) return true;
  8529. return false;
  8530. },
  8531. Polygon: function(object, point) {
  8532. return containsPolygon(object.coordinates, point);
  8533. },
  8534. MultiPolygon: function(object, point) {
  8535. var coordinates = object.coordinates, i = -1, n = coordinates.length;
  8536. while (++i < n) if (containsPolygon(coordinates[i], point)) return true;
  8537. return false;
  8538. },
  8539. GeometryCollection: function(object, point) {
  8540. var geometries = object.geometries, i = -1, n = geometries.length;
  8541. while (++i < n) if (containsGeometry(geometries[i], point)) return true;
  8542. return false;
  8543. }
  8544. };
  8545. function containsGeometry(geometry, point) {
  8546. return geometry && containsGeometryType.hasOwnProperty(geometry.type)
  8547. ? containsGeometryType[geometry.type](geometry, point)
  8548. : false;
  8549. }
  8550. function containsPoint(coordinates, point) {
  8551. return distance(coordinates, point) === 0;
  8552. }
  8553. function containsLine(coordinates, point) {
  8554. var ab = distance(coordinates[0], coordinates[1]),
  8555. ao = distance(coordinates[0], point),
  8556. ob = distance(point, coordinates[1]);
  8557. return ao + ob <= ab + epsilon;
  8558. }
  8559. function containsPolygon(coordinates, point) {
  8560. return !!polygonContains(coordinates.map(ringRadians), pointRadians(point));
  8561. }
  8562. function ringRadians(ring) {
  8563. return ring = ring.map(pointRadians), ring.pop(), ring;
  8564. }
  8565. function pointRadians(point) {
  8566. return [point[0] * radians, point[1] * radians];
  8567. }
  8568. var contains = function(object, point) {
  8569. return (object && containsObjectType.hasOwnProperty(object.type)
  8570. ? containsObjectType[object.type]
  8571. : containsGeometry)(object, point);
  8572. };
  8573. function graticuleX(y0, y1, dy) {
  8574. var y = d3Array.range(y0, y1 - epsilon, dy).concat(y1);
  8575. return function(x) { return y.map(function(y) { return [x, y]; }); };
  8576. }
  8577. function graticuleY(x0, x1, dx) {
  8578. var x = d3Array.range(x0, x1 - epsilon, dx).concat(x1);
  8579. return function(y) { return x.map(function(x) { return [x, y]; }); };
  8580. }
  8581. function graticule() {
  8582. var x1, x0, X1, X0,
  8583. y1, y0, Y1, Y0,
  8584. dx = 10, dy = dx, DX = 90, DY = 360,
  8585. x, y, X, Y,
  8586. precision = 2.5;
  8587. function graticule() {
  8588. return {type: "MultiLineString", coordinates: lines()};
  8589. }
  8590. function lines() {
  8591. return d3Array.range(ceil(X0 / DX) * DX, X1, DX).map(X)
  8592. .concat(d3Array.range(ceil(Y0 / DY) * DY, Y1, DY).map(Y))
  8593. .concat(d3Array.range(ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return abs(x % DX) > epsilon; }).map(x))
  8594. .concat(d3Array.range(ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return abs(y % DY) > epsilon; }).map(y));
  8595. }
  8596. graticule.lines = function() {
  8597. return lines().map(function(coordinates) { return {type: "LineString", coordinates: coordinates}; });
  8598. };
  8599. graticule.outline = function() {
  8600. return {
  8601. type: "Polygon",
  8602. coordinates: [
  8603. X(X0).concat(
  8604. Y(Y1).slice(1),
  8605. X(X1).reverse().slice(1),
  8606. Y(Y0).reverse().slice(1))
  8607. ]
  8608. };
  8609. };
  8610. graticule.extent = function(_) {
  8611. if (!arguments.length) return graticule.extentMinor();
  8612. return graticule.extentMajor(_).extentMinor(_);
  8613. };
  8614. graticule.extentMajor = function(_) {
  8615. if (!arguments.length) return [[X0, Y0], [X1, Y1]];
  8616. X0 = +_[0][0], X1 = +_[1][0];
  8617. Y0 = +_[0][1], Y1 = +_[1][1];
  8618. if (X0 > X1) _ = X0, X0 = X1, X1 = _;
  8619. if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
  8620. return graticule.precision(precision);
  8621. };
  8622. graticule.extentMinor = function(_) {
  8623. if (!arguments.length) return [[x0, y0], [x1, y1]];
  8624. x0 = +_[0][0], x1 = +_[1][0];
  8625. y0 = +_[0][1], y1 = +_[1][1];
  8626. if (x0 > x1) _ = x0, x0 = x1, x1 = _;
  8627. if (y0 > y1) _ = y0, y0 = y1, y1 = _;
  8628. return graticule.precision(precision);
  8629. };
  8630. graticule.step = function(_) {
  8631. if (!arguments.length) return graticule.stepMinor();
  8632. return graticule.stepMajor(_).stepMinor(_);
  8633. };
  8634. graticule.stepMajor = function(_) {
  8635. if (!arguments.length) return [DX, DY];
  8636. DX = +_[0], DY = +_[1];
  8637. return graticule;
  8638. };
  8639. graticule.stepMinor = function(_) {
  8640. if (!arguments.length) return [dx, dy];
  8641. dx = +_[0], dy = +_[1];
  8642. return graticule;
  8643. };
  8644. graticule.precision = function(_) {
  8645. if (!arguments.length) return precision;
  8646. precision = +_;
  8647. x = graticuleX(y0, y1, 90);
  8648. y = graticuleY(x0, x1, precision);
  8649. X = graticuleX(Y0, Y1, 90);
  8650. Y = graticuleY(X0, X1, precision);
  8651. return graticule;
  8652. };
  8653. return graticule
  8654. .extentMajor([[-180, -90 + epsilon], [180, 90 - epsilon]])
  8655. .extentMinor([[-180, -80 - epsilon], [180, 80 + epsilon]]);
  8656. }
  8657. function graticule10() {
  8658. return graticule()();
  8659. }
  8660. var interpolate = function(a, b) {
  8661. var x0 = a[0] * radians,
  8662. y0 = a[1] * radians,
  8663. x1 = b[0] * radians,
  8664. y1 = b[1] * radians,
  8665. cy0 = cos(y0),
  8666. sy0 = sin(y0),
  8667. cy1 = cos(y1),
  8668. sy1 = sin(y1),
  8669. kx0 = cy0 * cos(x0),
  8670. ky0 = cy0 * sin(x0),
  8671. kx1 = cy1 * cos(x1),
  8672. ky1 = cy1 * sin(x1),
  8673. d = 2 * asin(sqrt(haversin(y1 - y0) + cy0 * cy1 * haversin(x1 - x0))),
  8674. k = sin(d);
  8675. var interpolate = d ? function(t) {
  8676. var B = sin(t *= d) / k,
  8677. A = sin(d - t) / k,
  8678. x = A * kx0 + B * kx1,
  8679. y = A * ky0 + B * ky1,
  8680. z = A * sy0 + B * sy1;
  8681. return [
  8682. atan2(y, x) * degrees,
  8683. atan2(z, sqrt(x * x + y * y)) * degrees
  8684. ];
  8685. } : function() {
  8686. return [x0 * degrees, y0 * degrees];
  8687. };
  8688. interpolate.distance = d;
  8689. return interpolate;
  8690. };
  8691. var identity = function(x) {
  8692. return x;
  8693. };
  8694. var areaSum$1 = adder();
  8695. var areaRingSum$1 = adder();
  8696. var x00;
  8697. var y00;
  8698. var x0$1;
  8699. var y0$1;
  8700. var areaStream$1 = {
  8701. point: noop,
  8702. lineStart: noop,
  8703. lineEnd: noop,
  8704. polygonStart: function() {
  8705. areaStream$1.lineStart = areaRingStart$1;
  8706. areaStream$1.lineEnd = areaRingEnd$1;
  8707. },
  8708. polygonEnd: function() {
  8709. areaStream$1.lineStart = areaStream$1.lineEnd = areaStream$1.point = noop;
  8710. areaSum$1.add(abs(areaRingSum$1));
  8711. areaRingSum$1.reset();
  8712. },
  8713. result: function() {
  8714. var area = areaSum$1 / 2;
  8715. areaSum$1.reset();
  8716. return area;
  8717. }
  8718. };
  8719. function areaRingStart$1() {
  8720. areaStream$1.point = areaPointFirst$1;
  8721. }
  8722. function areaPointFirst$1(x, y) {
  8723. areaStream$1.point = areaPoint$1;
  8724. x00 = x0$1 = x, y00 = y0$1 = y;
  8725. }
  8726. function areaPoint$1(x, y) {
  8727. areaRingSum$1.add(y0$1 * x - x0$1 * y);
  8728. x0$1 = x, y0$1 = y;
  8729. }
  8730. function areaRingEnd$1() {
  8731. areaPoint$1(x00, y00);
  8732. }
  8733. var x0$2 = Infinity;
  8734. var y0$2 = x0$2;
  8735. var x1 = -x0$2;
  8736. var y1 = x1;
  8737. var boundsStream$1 = {
  8738. point: boundsPoint$1,
  8739. lineStart: noop,
  8740. lineEnd: noop,
  8741. polygonStart: noop,
  8742. polygonEnd: noop,
  8743. result: function() {
  8744. var bounds = [[x0$2, y0$2], [x1, y1]];
  8745. x1 = y1 = -(y0$2 = x0$2 = Infinity);
  8746. return bounds;
  8747. }
  8748. };
  8749. function boundsPoint$1(x, y) {
  8750. if (x < x0$2) x0$2 = x;
  8751. if (x > x1) x1 = x;
  8752. if (y < y0$2) y0$2 = y;
  8753. if (y > y1) y1 = y;
  8754. }
  8755. // TODO Enforce positive area for exterior, negative area for interior?
  8756. var X0$1 = 0;
  8757. var Y0$1 = 0;
  8758. var Z0$1 = 0;
  8759. var X1$1 = 0;
  8760. var Y1$1 = 0;
  8761. var Z1$1 = 0;
  8762. var X2$1 = 0;
  8763. var Y2$1 = 0;
  8764. var Z2$1 = 0;
  8765. var x00$1;
  8766. var y00$1;
  8767. var x0$3;
  8768. var y0$3;
  8769. var centroidStream$1 = {
  8770. point: centroidPoint$1,
  8771. lineStart: centroidLineStart$1,
  8772. lineEnd: centroidLineEnd$1,
  8773. polygonStart: function() {
  8774. centroidStream$1.lineStart = centroidRingStart$1;
  8775. centroidStream$1.lineEnd = centroidRingEnd$1;
  8776. },
  8777. polygonEnd: function() {
  8778. centroidStream$1.point = centroidPoint$1;
  8779. centroidStream$1.lineStart = centroidLineStart$1;
  8780. centroidStream$1.lineEnd = centroidLineEnd$1;
  8781. },
  8782. result: function() {
  8783. var centroid = Z2$1 ? [X2$1 / Z2$1, Y2$1 / Z2$1]
  8784. : Z1$1 ? [X1$1 / Z1$1, Y1$1 / Z1$1]
  8785. : Z0$1 ? [X0$1 / Z0$1, Y0$1 / Z0$1]
  8786. : [NaN, NaN];
  8787. X0$1 = Y0$1 = Z0$1 =
  8788. X1$1 = Y1$1 = Z1$1 =
  8789. X2$1 = Y2$1 = Z2$1 = 0;
  8790. return centroid;
  8791. }
  8792. };
  8793. function centroidPoint$1(x, y) {
  8794. X0$1 += x;
  8795. Y0$1 += y;
  8796. ++Z0$1;
  8797. }
  8798. function centroidLineStart$1() {
  8799. centroidStream$1.point = centroidPointFirstLine;
  8800. }
  8801. function centroidPointFirstLine(x, y) {
  8802. centroidStream$1.point = centroidPointLine;
  8803. centroidPoint$1(x0$3 = x, y0$3 = y);
  8804. }
  8805. function centroidPointLine(x, y) {
  8806. var dx = x - x0$3, dy = y - y0$3, z = sqrt(dx * dx + dy * dy);
  8807. X1$1 += z * (x0$3 + x) / 2;
  8808. Y1$1 += z * (y0$3 + y) / 2;
  8809. Z1$1 += z;
  8810. centroidPoint$1(x0$3 = x, y0$3 = y);
  8811. }
  8812. function centroidLineEnd$1() {
  8813. centroidStream$1.point = centroidPoint$1;
  8814. }
  8815. function centroidRingStart$1() {
  8816. centroidStream$1.point = centroidPointFirstRing;
  8817. }
  8818. function centroidRingEnd$1() {
  8819. centroidPointRing(x00$1, y00$1);
  8820. }
  8821. function centroidPointFirstRing(x, y) {
  8822. centroidStream$1.point = centroidPointRing;
  8823. centroidPoint$1(x00$1 = x0$3 = x, y00$1 = y0$3 = y);
  8824. }
  8825. function centroidPointRing(x, y) {
  8826. var dx = x - x0$3,
  8827. dy = y - y0$3,
  8828. z = sqrt(dx * dx + dy * dy);
  8829. X1$1 += z * (x0$3 + x) / 2;
  8830. Y1$1 += z * (y0$3 + y) / 2;
  8831. Z1$1 += z;
  8832. z = y0$3 * x - x0$3 * y;
  8833. X2$1 += z * (x0$3 + x);
  8834. Y2$1 += z * (y0$3 + y);
  8835. Z2$1 += z * 3;
  8836. centroidPoint$1(x0$3 = x, y0$3 = y);
  8837. }
  8838. function PathContext(context) {
  8839. this._context = context;
  8840. }
  8841. PathContext.prototype = {
  8842. _radius: 4.5,
  8843. pointRadius: function(_) {
  8844. return this._radius = _, this;
  8845. },
  8846. polygonStart: function() {
  8847. this._line = 0;
  8848. },
  8849. polygonEnd: function() {
  8850. this._line = NaN;
  8851. },
  8852. lineStart: function() {
  8853. this._point = 0;
  8854. },
  8855. lineEnd: function() {
  8856. if (this._line === 0) this._context.closePath();
  8857. this._point = NaN;
  8858. },
  8859. point: function(x, y) {
  8860. switch (this._point) {
  8861. case 0: {
  8862. this._context.moveTo(x, y);
  8863. this._point = 1;
  8864. break;
  8865. }
  8866. case 1: {
  8867. this._context.lineTo(x, y);
  8868. break;
  8869. }
  8870. default: {
  8871. this._context.moveTo(x + this._radius, y);
  8872. this._context.arc(x, y, this._radius, 0, tau);
  8873. break;
  8874. }
  8875. }
  8876. },
  8877. result: noop
  8878. };
  8879. var lengthSum$1 = adder();
  8880. var lengthRing;
  8881. var x00$2;
  8882. var y00$2;
  8883. var x0$4;
  8884. var y0$4;
  8885. var lengthStream$1 = {
  8886. point: noop,
  8887. lineStart: function() {
  8888. lengthStream$1.point = lengthPointFirst$1;
  8889. },
  8890. lineEnd: function() {
  8891. if (lengthRing) lengthPoint$1(x00$2, y00$2);
  8892. lengthStream$1.point = noop;
  8893. },
  8894. polygonStart: function() {
  8895. lengthRing = true;
  8896. },
  8897. polygonEnd: function() {
  8898. lengthRing = null;
  8899. },
  8900. result: function() {
  8901. var length = +lengthSum$1;
  8902. lengthSum$1.reset();
  8903. return length;
  8904. }
  8905. };
  8906. function lengthPointFirst$1(x, y) {
  8907. lengthStream$1.point = lengthPoint$1;
  8908. x00$2 = x0$4 = x, y00$2 = y0$4 = y;
  8909. }
  8910. function lengthPoint$1(x, y) {
  8911. x0$4 -= x, y0$4 -= y;
  8912. lengthSum$1.add(sqrt(x0$4 * x0$4 + y0$4 * y0$4));
  8913. x0$4 = x, y0$4 = y;
  8914. }
  8915. function PathString() {
  8916. this._string = [];
  8917. }
  8918. PathString.prototype = {
  8919. _radius: 4.5,
  8920. _circle: circle$1(4.5),
  8921. pointRadius: function(_) {
  8922. if ((_ = +_) !== this._radius) this._radius = _, this._circle = null;
  8923. return this;
  8924. },
  8925. polygonStart: function() {
  8926. this._line = 0;
  8927. },
  8928. polygonEnd: function() {
  8929. this._line = NaN;
  8930. },
  8931. lineStart: function() {
  8932. this._point = 0;
  8933. },
  8934. lineEnd: function() {
  8935. if (this._line === 0) this._string.push("Z");
  8936. this._point = NaN;
  8937. },
  8938. point: function(x, y) {
  8939. switch (this._point) {
  8940. case 0: {
  8941. this._string.push("M", x, ",", y);
  8942. this._point = 1;
  8943. break;
  8944. }
  8945. case 1: {
  8946. this._string.push("L", x, ",", y);
  8947. break;
  8948. }
  8949. default: {
  8950. if (this._circle == null) this._circle = circle$1(this._radius);
  8951. this._string.push("M", x, ",", y, this._circle);
  8952. break;
  8953. }
  8954. }
  8955. },
  8956. result: function() {
  8957. if (this._string.length) {
  8958. var result = this._string.join("");
  8959. this._string = [];
  8960. return result;
  8961. } else {
  8962. return null;
  8963. }
  8964. }
  8965. };
  8966. function circle$1(radius) {
  8967. return "m0," + radius
  8968. + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius
  8969. + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius
  8970. + "z";
  8971. }
  8972. var index = function(projection, context) {
  8973. var pointRadius = 4.5,
  8974. projectionStream,
  8975. contextStream;
  8976. function path(object) {
  8977. if (object) {
  8978. if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
  8979. geoStream(object, projectionStream(contextStream));
  8980. }
  8981. return contextStream.result();
  8982. }
  8983. path.area = function(object) {
  8984. geoStream(object, projectionStream(areaStream$1));
  8985. return areaStream$1.result();
  8986. };
  8987. path.measure = function(object) {
  8988. geoStream(object, projectionStream(lengthStream$1));
  8989. return lengthStream$1.result();
  8990. };
  8991. path.bounds = function(object) {
  8992. geoStream(object, projectionStream(boundsStream$1));
  8993. return boundsStream$1.result();
  8994. };
  8995. path.centroid = function(object) {
  8996. geoStream(object, projectionStream(centroidStream$1));
  8997. return centroidStream$1.result();
  8998. };
  8999. path.projection = function(_) {
  9000. return arguments.length ? (projectionStream = _ == null ? (projection = null, identity) : (projection = _).stream, path) : projection;
  9001. };
  9002. path.context = function(_) {
  9003. if (!arguments.length) return context;
  9004. contextStream = _ == null ? (context = null, new PathString) : new PathContext(context = _);
  9005. if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
  9006. return path;
  9007. };
  9008. path.pointRadius = function(_) {
  9009. if (!arguments.length) return pointRadius;
  9010. pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
  9011. return path;
  9012. };
  9013. return path.projection(projection).context(context);
  9014. };
  9015. var transform = function(methods) {
  9016. return {
  9017. stream: transformer(methods)
  9018. };
  9019. };
  9020. function transformer(methods) {
  9021. return function(stream) {
  9022. var s = new TransformStream;
  9023. for (var key in methods) s[key] = methods[key];
  9024. s.stream = stream;
  9025. return s;
  9026. };
  9027. }
  9028. function TransformStream() {}
  9029. TransformStream.prototype = {
  9030. constructor: TransformStream,
  9031. point: function(x, y) { this.stream.point(x, y); },
  9032. sphere: function() { this.stream.sphere(); },
  9033. lineStart: function() { this.stream.lineStart(); },
  9034. lineEnd: function() { this.stream.lineEnd(); },
  9035. polygonStart: function() { this.stream.polygonStart(); },
  9036. polygonEnd: function() { this.stream.polygonEnd(); }
  9037. };
  9038. function fit(projection, fitBounds, object) {
  9039. var clip = projection.clipExtent && projection.clipExtent();
  9040. projection.scale(150).translate([0, 0]);
  9041. if (clip != null) projection.clipExtent(null);
  9042. geoStream(object, projection.stream(boundsStream$1));
  9043. fitBounds(boundsStream$1.result());
  9044. if (clip != null) projection.clipExtent(clip);
  9045. return projection;
  9046. }
  9047. function fitExtent(projection, extent, object) {
  9048. return fit(projection, function(b) {
  9049. var w = extent[1][0] - extent[0][0],
  9050. h = extent[1][1] - extent[0][1],
  9051. k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])),
  9052. x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2,
  9053. y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;
  9054. projection.scale(150 * k).translate([x, y]);
  9055. }, object);
  9056. }
  9057. function fitSize(projection, size, object) {
  9058. return fitExtent(projection, [[0, 0], size], object);
  9059. }
  9060. function fitWidth(projection, width, object) {
  9061. return fit(projection, function(b) {
  9062. var w = +width,
  9063. k = w / (b[1][0] - b[0][0]),
  9064. x = (w - k * (b[1][0] + b[0][0])) / 2,
  9065. y = -k * b[0][1];
  9066. projection.scale(150 * k).translate([x, y]);
  9067. }, object);
  9068. }
  9069. function fitHeight(projection, height, object) {
  9070. return fit(projection, function(b) {
  9071. var h = +height,
  9072. k = h / (b[1][1] - b[0][1]),
  9073. x = -k * b[0][0],
  9074. y = (h - k * (b[1][1] + b[0][1])) / 2;
  9075. projection.scale(150 * k).translate([x, y]);
  9076. }, object);
  9077. }
  9078. var maxDepth = 16;
  9079. var cosMinDistance = cos(30 * radians); // cos(minimum angular distance)
  9080. var resample = function(project, delta2) {
  9081. return +delta2 ? resample$1(project, delta2) : resampleNone(project);
  9082. };
  9083. function resampleNone(project) {
  9084. return transformer({
  9085. point: function(x, y) {
  9086. x = project(x, y);
  9087. this.stream.point(x[0], x[1]);
  9088. }
  9089. });
  9090. }
  9091. function resample$1(project, delta2) {
  9092. function resampleLineTo(x0, y0, lambda0, a0, b0, c0, x1, y1, lambda1, a1, b1, c1, depth, stream) {
  9093. var dx = x1 - x0,
  9094. dy = y1 - y0,
  9095. d2 = dx * dx + dy * dy;
  9096. if (d2 > 4 * delta2 && depth--) {
  9097. var a = a0 + a1,
  9098. b = b0 + b1,
  9099. c = c0 + c1,
  9100. m = sqrt(a * a + b * b + c * c),
  9101. phi2 = asin(c /= m),
  9102. lambda2 = abs(abs(c) - 1) < epsilon || abs(lambda0 - lambda1) < epsilon ? (lambda0 + lambda1) / 2 : atan2(b, a),
  9103. p = project(lambda2, phi2),
  9104. x2 = p[0],
  9105. y2 = p[1],
  9106. dx2 = x2 - x0,
  9107. dy2 = y2 - y0,
  9108. dz = dy * dx2 - dx * dy2;
  9109. if (dz * dz / d2 > delta2 // perpendicular projected distance
  9110. || abs((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 // midpoint close to an end
  9111. || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { // angular distance
  9112. resampleLineTo(x0, y0, lambda0, a0, b0, c0, x2, y2, lambda2, a /= m, b /= m, c, depth, stream);
  9113. stream.point(x2, y2);
  9114. resampleLineTo(x2, y2, lambda2, a, b, c, x1, y1, lambda1, a1, b1, c1, depth, stream);
  9115. }
  9116. }
  9117. }
  9118. return function(stream) {
  9119. var lambda00, x00, y00, a00, b00, c00, // first point
  9120. lambda0, x0, y0, a0, b0, c0; // previous point
  9121. var resampleStream = {
  9122. point: point,
  9123. lineStart: lineStart,
  9124. lineEnd: lineEnd,
  9125. polygonStart: function() { stream.polygonStart(); resampleStream.lineStart = ringStart; },
  9126. polygonEnd: function() { stream.polygonEnd(); resampleStream.lineStart = lineStart; }
  9127. };
  9128. function point(x, y) {
  9129. x = project(x, y);
  9130. stream.point(x[0], x[1]);
  9131. }
  9132. function lineStart() {
  9133. x0 = NaN;
  9134. resampleStream.point = linePoint;
  9135. stream.lineStart();
  9136. }
  9137. function linePoint(lambda, phi) {
  9138. var c = cartesian([lambda, phi]), p = project(lambda, phi);
  9139. resampleLineTo(x0, y0, lambda0, a0, b0, c0, x0 = p[0], y0 = p[1], lambda0 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
  9140. stream.point(x0, y0);
  9141. }
  9142. function lineEnd() {
  9143. resampleStream.point = point;
  9144. stream.lineEnd();
  9145. }
  9146. function ringStart() {
  9147. lineStart();
  9148. resampleStream.point = ringPoint;
  9149. resampleStream.lineEnd = ringEnd;
  9150. }
  9151. function ringPoint(lambda, phi) {
  9152. linePoint(lambda00 = lambda, phi), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
  9153. resampleStream.point = linePoint;
  9154. }
  9155. function ringEnd() {
  9156. resampleLineTo(x0, y0, lambda0, a0, b0, c0, x00, y00, lambda00, a00, b00, c00, maxDepth, stream);
  9157. resampleStream.lineEnd = lineEnd;
  9158. lineEnd();
  9159. }
  9160. return resampleStream;
  9161. };
  9162. }
  9163. var transformRadians = transformer({
  9164. point: function(x, y) {
  9165. this.stream.point(x * radians, y * radians);
  9166. }
  9167. });
  9168. function transformRotate(rotate) {
  9169. return transformer({
  9170. point: function(x, y) {
  9171. var r = rotate(x, y);
  9172. return this.stream.point(r[0], r[1]);
  9173. }
  9174. });
  9175. }
  9176. function projection(project) {
  9177. return projectionMutator(function() { return project; })();
  9178. }
  9179. function projectionMutator(projectAt) {
  9180. var project,
  9181. k = 150, // scale
  9182. x = 480, y = 250, // translate
  9183. dx, dy, lambda = 0, phi = 0, // center
  9184. deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, projectRotate, // rotate
  9185. theta = null, preclip = clipAntimeridian, // clip angle
  9186. x0 = null, y0, x1, y1, postclip = identity, // clip extent
  9187. delta2 = 0.5, projectResample = resample(projectTransform, delta2), // precision
  9188. cache,
  9189. cacheStream;
  9190. function projection(point) {
  9191. point = projectRotate(point[0] * radians, point[1] * radians);
  9192. return [point[0] * k + dx, dy - point[1] * k];
  9193. }
  9194. function invert(point) {
  9195. point = projectRotate.invert((point[0] - dx) / k, (dy - point[1]) / k);
  9196. return point && [point[0] * degrees, point[1] * degrees];
  9197. }
  9198. function projectTransform(x, y) {
  9199. return x = project(x, y), [x[0] * k + dx, dy - x[1] * k];
  9200. }
  9201. projection.stream = function(stream) {
  9202. return cache && cacheStream === stream ? cache : cache = transformRadians(transformRotate(rotate)(preclip(projectResample(postclip(cacheStream = stream)))));
  9203. };
  9204. projection.preclip = function(_) {
  9205. return arguments.length ? (preclip = _, theta = undefined, reset()) : preclip;
  9206. };
  9207. projection.postclip = function(_) {
  9208. return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
  9209. };
  9210. projection.clipAngle = function(_) {
  9211. return arguments.length ? (preclip = +_ ? clipCircle(theta = _ * radians) : (theta = null, clipAntimeridian), reset()) : theta * degrees;
  9212. };
  9213. projection.clipExtent = function(_) {
  9214. return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];
  9215. };
  9216. projection.scale = function(_) {
  9217. return arguments.length ? (k = +_, recenter()) : k;
  9218. };
  9219. projection.translate = function(_) {
  9220. return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [x, y];
  9221. };
  9222. projection.center = function(_) {
  9223. return arguments.length ? (lambda = _[0] % 360 * radians, phi = _[1] % 360 * radians, recenter()) : [lambda * degrees, phi * degrees];
  9224. };
  9225. projection.rotate = function(_) {
  9226. return arguments.length ? (deltaLambda = _[0] % 360 * radians, deltaPhi = _[1] % 360 * radians, deltaGamma = _.length > 2 ? _[2] % 360 * radians : 0, recenter()) : [deltaLambda * degrees, deltaPhi * degrees, deltaGamma * degrees];
  9227. };
  9228. projection.precision = function(_) {
  9229. return arguments.length ? (projectResample = resample(projectTransform, delta2 = _ * _), reset()) : sqrt(delta2);
  9230. };
  9231. projection.fitExtent = function(extent, object) {
  9232. return fitExtent(projection, extent, object);
  9233. };
  9234. projection.fitSize = function(size, object) {
  9235. return fitSize(projection, size, object);
  9236. };
  9237. projection.fitWidth = function(width, object) {
  9238. return fitWidth(projection, width, object);
  9239. };
  9240. projection.fitHeight = function(height, object) {
  9241. return fitHeight(projection, height, object);
  9242. };
  9243. function recenter() {
  9244. projectRotate = compose(rotate = rotateRadians(deltaLambda, deltaPhi, deltaGamma), project);
  9245. var center = project(lambda, phi);
  9246. dx = x - center[0] * k;
  9247. dy = y + center[1] * k;
  9248. return reset();
  9249. }
  9250. function reset() {
  9251. cache = cacheStream = null;
  9252. return projection;
  9253. }
  9254. return function() {
  9255. project = projectAt.apply(this, arguments);
  9256. projection.invert = project.invert && invert;
  9257. return recenter();
  9258. };
  9259. }
  9260. function conicProjection(projectAt) {
  9261. var phi0 = 0,
  9262. phi1 = pi / 3,
  9263. m = projectionMutator(projectAt),
  9264. p = m(phi0, phi1);
  9265. p.parallels = function(_) {
  9266. return arguments.length ? m(phi0 = _[0] * radians, phi1 = _[1] * radians) : [phi0 * degrees, phi1 * degrees];
  9267. };
  9268. return p;
  9269. }
  9270. function cylindricalEqualAreaRaw(phi0) {
  9271. var cosPhi0 = cos(phi0);
  9272. function forward(lambda, phi) {
  9273. return [lambda * cosPhi0, sin(phi) / cosPhi0];
  9274. }
  9275. forward.invert = function(x, y) {
  9276. return [x / cosPhi0, asin(y * cosPhi0)];
  9277. };
  9278. return forward;
  9279. }
  9280. function conicEqualAreaRaw(y0, y1) {
  9281. var sy0 = sin(y0), n = (sy0 + sin(y1)) / 2;
  9282. // Are the parallels symmetrical around the Equator?
  9283. if (abs(n) < epsilon) return cylindricalEqualAreaRaw(y0);
  9284. var c = 1 + sy0 * (2 * n - sy0), r0 = sqrt(c) / n;
  9285. function project(x, y) {
  9286. var r = sqrt(c - 2 * n * sin(y)) / n;
  9287. return [r * sin(x *= n), r0 - r * cos(x)];
  9288. }
  9289. project.invert = function(x, y) {
  9290. var r0y = r0 - y;
  9291. return [atan2(x, abs(r0y)) / n * sign(r0y), asin((c - (x * x + r0y * r0y) * n * n) / (2 * n))];
  9292. };
  9293. return project;
  9294. }
  9295. var conicEqualArea = function() {
  9296. return conicProjection(conicEqualAreaRaw)
  9297. .scale(155.424)
  9298. .center([0, 33.6442]);
  9299. };
  9300. var albers = function() {
  9301. return conicEqualArea()
  9302. .parallels([29.5, 45.5])
  9303. .scale(1070)
  9304. .translate([480, 250])
  9305. .rotate([96, 0])
  9306. .center([-0.6, 38.7]);
  9307. };
  9308. // The projections must have mutually exclusive clip regions on the sphere,
  9309. // as this will avoid emitting interleaving lines and polygons.
  9310. function multiplex(streams) {
  9311. var n = streams.length;
  9312. return {
  9313. point: function(x, y) { var i = -1; while (++i < n) streams[i].point(x, y); },
  9314. sphere: function() { var i = -1; while (++i < n) streams[i].sphere(); },
  9315. lineStart: function() { var i = -1; while (++i < n) streams[i].lineStart(); },
  9316. lineEnd: function() { var i = -1; while (++i < n) streams[i].lineEnd(); },
  9317. polygonStart: function() { var i = -1; while (++i < n) streams[i].polygonStart(); },
  9318. polygonEnd: function() { var i = -1; while (++i < n) streams[i].polygonEnd(); }
  9319. };
  9320. }
  9321. // A composite projection for the United States, configured by default for
  9322. // 960×500. The projection also works quite well at 960×600 if you change the
  9323. // scale to 1285 and adjust the translate accordingly. The set of standard
  9324. // parallels for each region comes from USGS, which is published here:
  9325. // http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers
  9326. var albersUsa = function() {
  9327. var cache,
  9328. cacheStream,
  9329. lower48 = albers(), lower48Point,
  9330. alaska = conicEqualArea().rotate([154, 0]).center([-2, 58.5]).parallels([55, 65]), alaskaPoint, // EPSG:3338
  9331. hawaii = conicEqualArea().rotate([157, 0]).center([-3, 19.9]).parallels([8, 18]), hawaiiPoint, // ESRI:102007
  9332. point, pointStream = {point: function(x, y) { point = [x, y]; }};
  9333. function albersUsa(coordinates) {
  9334. var x = coordinates[0], y = coordinates[1];
  9335. return point = null, (lower48Point.point(x, y), point)
  9336. || (alaskaPoint.point(x, y), point)
  9337. || (hawaiiPoint.point(x, y), point);
  9338. }
  9339. albersUsa.invert = function(coordinates) {
  9340. var k = lower48.scale(),
  9341. t = lower48.translate(),
  9342. x = (coordinates[0] - t[0]) / k,
  9343. y = (coordinates[1] - t[1]) / k;
  9344. return (y >= 0.120 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska
  9345. : y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii
  9346. : lower48).invert(coordinates);
  9347. };
  9348. albersUsa.stream = function(stream) {
  9349. return cache && cacheStream === stream ? cache : cache = multiplex([lower48.stream(cacheStream = stream), alaska.stream(stream), hawaii.stream(stream)]);
  9350. };
  9351. albersUsa.precision = function(_) {
  9352. if (!arguments.length) return lower48.precision();
  9353. lower48.precision(_), alaska.precision(_), hawaii.precision(_);
  9354. return reset();
  9355. };
  9356. albersUsa.scale = function(_) {
  9357. if (!arguments.length) return lower48.scale();
  9358. lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_);
  9359. return albersUsa.translate(lower48.translate());
  9360. };
  9361. albersUsa.translate = function(_) {
  9362. if (!arguments.length) return lower48.translate();
  9363. var k = lower48.scale(), x = +_[0], y = +_[1];
  9364. lower48Point = lower48
  9365. .translate(_)
  9366. .clipExtent([[x - 0.455 * k, y - 0.238 * k], [x + 0.455 * k, y + 0.238 * k]])
  9367. .stream(pointStream);
  9368. alaskaPoint = alaska
  9369. .translate([x - 0.307 * k, y + 0.201 * k])
  9370. .clipExtent([[x - 0.425 * k + epsilon, y + 0.120 * k + epsilon], [x - 0.214 * k - epsilon, y + 0.234 * k - epsilon]])
  9371. .stream(pointStream);
  9372. hawaiiPoint = hawaii
  9373. .translate([x - 0.205 * k, y + 0.212 * k])
  9374. .clipExtent([[x - 0.214 * k + epsilon, y + 0.166 * k + epsilon], [x - 0.115 * k - epsilon, y + 0.234 * k - epsilon]])
  9375. .stream(pointStream);
  9376. return reset();
  9377. };
  9378. albersUsa.fitExtent = function(extent, object) {
  9379. return fitExtent(albersUsa, extent, object);
  9380. };
  9381. albersUsa.fitSize = function(size, object) {
  9382. return fitSize(albersUsa, size, object);
  9383. };
  9384. albersUsa.fitWidth = function(width, object) {
  9385. return fitWidth(albersUsa, width, object);
  9386. };
  9387. albersUsa.fitHeight = function(height, object) {
  9388. return fitHeight(albersUsa, height, object);
  9389. };
  9390. function reset() {
  9391. cache = cacheStream = null;
  9392. return albersUsa;
  9393. }
  9394. return albersUsa.scale(1070);
  9395. };
  9396. function azimuthalRaw(scale) {
  9397. return function(x, y) {
  9398. var cx = cos(x),
  9399. cy = cos(y),
  9400. k = scale(cx * cy);
  9401. return [
  9402. k * cy * sin(x),
  9403. k * sin(y)
  9404. ];
  9405. }
  9406. }
  9407. function azimuthalInvert(angle) {
  9408. return function(x, y) {
  9409. var z = sqrt(x * x + y * y),
  9410. c = angle(z),
  9411. sc = sin(c),
  9412. cc = cos(c);
  9413. return [
  9414. atan2(x * sc, z * cc),
  9415. asin(z && y * sc / z)
  9416. ];
  9417. }
  9418. }
  9419. var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) {
  9420. return sqrt(2 / (1 + cxcy));
  9421. });
  9422. azimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) {
  9423. return 2 * asin(z / 2);
  9424. });
  9425. var azimuthalEqualArea = function() {
  9426. return projection(azimuthalEqualAreaRaw)
  9427. .scale(124.75)
  9428. .clipAngle(180 - 1e-3);
  9429. };
  9430. var azimuthalEquidistantRaw = azimuthalRaw(function(c) {
  9431. return (c = acos(c)) && c / sin(c);
  9432. });
  9433. azimuthalEquidistantRaw.invert = azimuthalInvert(function(z) {
  9434. return z;
  9435. });
  9436. var azimuthalEquidistant = function() {
  9437. return projection(azimuthalEquidistantRaw)
  9438. .scale(79.4188)
  9439. .clipAngle(180 - 1e-3);
  9440. };
  9441. function mercatorRaw(lambda, phi) {
  9442. return [lambda, log(tan((halfPi + phi) / 2))];
  9443. }
  9444. mercatorRaw.invert = function(x, y) {
  9445. return [x, 2 * atan(exp(y)) - halfPi];
  9446. };
  9447. var mercator = function() {
  9448. return mercatorProjection(mercatorRaw)
  9449. .scale(961 / tau);
  9450. };
  9451. function mercatorProjection(project) {
  9452. var m = projection(project),
  9453. center = m.center,
  9454. scale = m.scale,
  9455. translate = m.translate,
  9456. clipExtent = m.clipExtent,
  9457. x0 = null, y0, x1, y1; // clip extent
  9458. m.scale = function(_) {
  9459. return arguments.length ? (scale(_), reclip()) : scale();
  9460. };
  9461. m.translate = function(_) {
  9462. return arguments.length ? (translate(_), reclip()) : translate();
  9463. };
  9464. m.center = function(_) {
  9465. return arguments.length ? (center(_), reclip()) : center();
  9466. };
  9467. m.clipExtent = function(_) {
  9468. return arguments.length ? (_ == null ? x0 = y0 = x1 = y1 = null : (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reclip()) : x0 == null ? null : [[x0, y0], [x1, y1]];
  9469. };
  9470. function reclip() {
  9471. var k = pi * scale(),
  9472. t = m(rotation(m.rotate()).invert([0, 0]));
  9473. return clipExtent(x0 == null
  9474. ? [[t[0] - k, t[1] - k], [t[0] + k, t[1] + k]] : project === mercatorRaw
  9475. ? [[Math.max(t[0] - k, x0), y0], [Math.min(t[0] + k, x1), y1]]
  9476. : [[x0, Math.max(t[1] - k, y0)], [x1, Math.min(t[1] + k, y1)]]);
  9477. }
  9478. return reclip();
  9479. }
  9480. function tany(y) {
  9481. return tan((halfPi + y) / 2);
  9482. }
  9483. function conicConformalRaw(y0, y1) {
  9484. var cy0 = cos(y0),
  9485. n = y0 === y1 ? sin(y0) : log(cy0 / cos(y1)) / log(tany(y1) / tany(y0)),
  9486. f = cy0 * pow(tany(y0), n) / n;
  9487. if (!n) return mercatorRaw;
  9488. function project(x, y) {
  9489. if (f > 0) { if (y < -halfPi + epsilon) y = -halfPi + epsilon; }
  9490. else { if (y > halfPi - epsilon) y = halfPi - epsilon; }
  9491. var r = f / pow(tany(y), n);
  9492. return [r * sin(n * x), f - r * cos(n * x)];
  9493. }
  9494. project.invert = function(x, y) {
  9495. var fy = f - y, r = sign(n) * sqrt(x * x + fy * fy);
  9496. return [atan2(x, abs(fy)) / n * sign(fy), 2 * atan(pow(f / r, 1 / n)) - halfPi];
  9497. };
  9498. return project;
  9499. }
  9500. var conicConformal = function() {
  9501. return conicProjection(conicConformalRaw)
  9502. .scale(109.5)
  9503. .parallels([30, 30]);
  9504. };
  9505. function equirectangularRaw(lambda, phi) {
  9506. return [lambda, phi];
  9507. }
  9508. equirectangularRaw.invert = equirectangularRaw;
  9509. var equirectangular = function() {
  9510. return projection(equirectangularRaw)
  9511. .scale(152.63);
  9512. };
  9513. function conicEquidistantRaw(y0, y1) {
  9514. var cy0 = cos(y0),
  9515. n = y0 === y1 ? sin(y0) : (cy0 - cos(y1)) / (y1 - y0),
  9516. g = cy0 / n + y0;
  9517. if (abs(n) < epsilon) return equirectangularRaw;
  9518. function project(x, y) {
  9519. var gy = g - y, nx = n * x;
  9520. return [gy * sin(nx), g - gy * cos(nx)];
  9521. }
  9522. project.invert = function(x, y) {
  9523. var gy = g - y;
  9524. return [atan2(x, abs(gy)) / n * sign(gy), g - sign(n) * sqrt(x * x + gy * gy)];
  9525. };
  9526. return project;
  9527. }
  9528. var conicEquidistant = function() {
  9529. return conicProjection(conicEquidistantRaw)
  9530. .scale(131.154)
  9531. .center([0, 13.9389]);
  9532. };
  9533. function gnomonicRaw(x, y) {
  9534. var cy = cos(y), k = cos(x) * cy;
  9535. return [cy * sin(x) / k, sin(y) / k];
  9536. }
  9537. gnomonicRaw.invert = azimuthalInvert(atan);
  9538. var gnomonic = function() {
  9539. return projection(gnomonicRaw)
  9540. .scale(144.049)
  9541. .clipAngle(60);
  9542. };
  9543. function scaleTranslate(kx, ky, tx, ty) {
  9544. return kx === 1 && ky === 1 && tx === 0 && ty === 0 ? identity : transformer({
  9545. point: function(x, y) {
  9546. this.stream.point(x * kx + tx, y * ky + ty);
  9547. }
  9548. });
  9549. }
  9550. var identity$1 = function() {
  9551. var k = 1, tx = 0, ty = 0, sx = 1, sy = 1, transform$$1 = identity, // scale, translate and reflect
  9552. x0 = null, y0, x1, y1, // clip extent
  9553. postclip = identity,
  9554. cache,
  9555. cacheStream,
  9556. projection;
  9557. function reset() {
  9558. cache = cacheStream = null;
  9559. return projection;
  9560. }
  9561. return projection = {
  9562. stream: function(stream) {
  9563. return cache && cacheStream === stream ? cache : cache = transform$$1(postclip(cacheStream = stream));
  9564. },
  9565. postclip: function(_) {
  9566. return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
  9567. },
  9568. clipExtent: function(_) {
  9569. return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];
  9570. },
  9571. scale: function(_) {
  9572. return arguments.length ? (transform$$1 = scaleTranslate((k = +_) * sx, k * sy, tx, ty), reset()) : k;
  9573. },
  9574. translate: function(_) {
  9575. return arguments.length ? (transform$$1 = scaleTranslate(k * sx, k * sy, tx = +_[0], ty = +_[1]), reset()) : [tx, ty];
  9576. },
  9577. reflectX: function(_) {
  9578. return arguments.length ? (transform$$1 = scaleTranslate(k * (sx = _ ? -1 : 1), k * sy, tx, ty), reset()) : sx < 0;
  9579. },
  9580. reflectY: function(_) {
  9581. return arguments.length ? (transform$$1 = scaleTranslate(k * sx, k * (sy = _ ? -1 : 1), tx, ty), reset()) : sy < 0;
  9582. },
  9583. fitExtent: function(extent, object) {
  9584. return fitExtent(projection, extent, object);
  9585. },
  9586. fitSize: function(size, object) {
  9587. return fitSize(projection, size, object);
  9588. },
  9589. fitWidth: function(width, object) {
  9590. return fitWidth(projection, width, object);
  9591. },
  9592. fitHeight: function(height, object) {
  9593. return fitHeight(projection, height, object);
  9594. }
  9595. };
  9596. };
  9597. function naturalEarth1Raw(lambda, phi) {
  9598. var phi2 = phi * phi, phi4 = phi2 * phi2;
  9599. return [
  9600. lambda * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (0.003971 * phi2 - 0.001529 * phi4))),
  9601. phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4)))
  9602. ];
  9603. }
  9604. naturalEarth1Raw.invert = function(x, y) {
  9605. var phi = y, i = 25, delta;
  9606. do {
  9607. var phi2 = phi * phi, phi4 = phi2 * phi2;
  9608. phi -= delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4))) - y) /
  9609. (1.007226 + phi2 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi2 - 0.005916 * 11 * phi4)));
  9610. } while (abs(delta) > epsilon && --i > 0);
  9611. return [
  9612. x / (0.8707 + (phi2 = phi * phi) * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (0.003971 - 0.001529 * phi2)))),
  9613. phi
  9614. ];
  9615. };
  9616. var naturalEarth1 = function() {
  9617. return projection(naturalEarth1Raw)
  9618. .scale(175.295);
  9619. };
  9620. function orthographicRaw(x, y) {
  9621. return [cos(y) * sin(x), sin(y)];
  9622. }
  9623. orthographicRaw.invert = azimuthalInvert(asin);
  9624. var orthographic = function() {
  9625. return projection(orthographicRaw)
  9626. .scale(249.5)
  9627. .clipAngle(90 + epsilon);
  9628. };
  9629. function stereographicRaw(x, y) {
  9630. var cy = cos(y), k = 1 + cos(x) * cy;
  9631. return [cy * sin(x) / k, sin(y) / k];
  9632. }
  9633. stereographicRaw.invert = azimuthalInvert(function(z) {
  9634. return 2 * atan(z);
  9635. });
  9636. var stereographic = function() {
  9637. return projection(stereographicRaw)
  9638. .scale(250)
  9639. .clipAngle(142);
  9640. };
  9641. function transverseMercatorRaw(lambda, phi) {
  9642. return [log(tan((halfPi + phi) / 2)), -lambda];
  9643. }
  9644. transverseMercatorRaw.invert = function(x, y) {
  9645. return [-y, 2 * atan(exp(x)) - halfPi];
  9646. };
  9647. var transverseMercator = function() {
  9648. var m = mercatorProjection(transverseMercatorRaw),
  9649. center = m.center,
  9650. rotate = m.rotate;
  9651. m.center = function(_) {
  9652. return arguments.length ? center([-_[1], _[0]]) : (_ = center(), [_[1], -_[0]]);
  9653. };
  9654. m.rotate = function(_) {
  9655. return arguments.length ? rotate([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate(), [_[0], _[1], _[2] - 90]);
  9656. };
  9657. return rotate([0, 0, 90])
  9658. .scale(159.155);
  9659. };
  9660. exports.geoArea = area;
  9661. exports.geoBounds = bounds;
  9662. exports.geoCentroid = centroid;
  9663. exports.geoCircle = circle;
  9664. exports.geoClipAntimeridian = clipAntimeridian;
  9665. exports.geoClipCircle = clipCircle;
  9666. exports.geoClipExtent = extent;
  9667. exports.geoClipRectangle = clipRectangle;
  9668. exports.geoContains = contains;
  9669. exports.geoDistance = distance;
  9670. exports.geoGraticule = graticule;
  9671. exports.geoGraticule10 = graticule10;
  9672. exports.geoInterpolate = interpolate;
  9673. exports.geoLength = length;
  9674. exports.geoPath = index;
  9675. exports.geoAlbers = albers;
  9676. exports.geoAlbersUsa = albersUsa;
  9677. exports.geoAzimuthalEqualArea = azimuthalEqualArea;
  9678. exports.geoAzimuthalEqualAreaRaw = azimuthalEqualAreaRaw;
  9679. exports.geoAzimuthalEquidistant = azimuthalEquidistant;
  9680. exports.geoAzimuthalEquidistantRaw = azimuthalEquidistantRaw;
  9681. exports.geoConicConformal = conicConformal;
  9682. exports.geoConicConformalRaw = conicConformalRaw;
  9683. exports.geoConicEqualArea = conicEqualArea;
  9684. exports.geoConicEqualAreaRaw = conicEqualAreaRaw;
  9685. exports.geoConicEquidistant = conicEquidistant;
  9686. exports.geoConicEquidistantRaw = conicEquidistantRaw;
  9687. exports.geoEquirectangular = equirectangular;
  9688. exports.geoEquirectangularRaw = equirectangularRaw;
  9689. exports.geoGnomonic = gnomonic;
  9690. exports.geoGnomonicRaw = gnomonicRaw;
  9691. exports.geoIdentity = identity$1;
  9692. exports.geoProjection = projection;
  9693. exports.geoProjectionMutator = projectionMutator;
  9694. exports.geoMercator = mercator;
  9695. exports.geoMercatorRaw = mercatorRaw;
  9696. exports.geoNaturalEarth1 = naturalEarth1;
  9697. exports.geoNaturalEarth1Raw = naturalEarth1Raw;
  9698. exports.geoOrthographic = orthographic;
  9699. exports.geoOrthographicRaw = orthographicRaw;
  9700. exports.geoStereographic = stereographic;
  9701. exports.geoStereographicRaw = stereographicRaw;
  9702. exports.geoTransverseMercator = transverseMercator;
  9703. exports.geoTransverseMercatorRaw = transverseMercatorRaw;
  9704. exports.geoRotation = rotation;
  9705. exports.geoStream = geoStream;
  9706. exports.geoTransform = transform;
  9707. Object.defineProperty(exports, '__esModule', { value: true });
  9708. })));
  9709. },{"d3-array":39}],52:[function(require,module,exports){
  9710. // https://d3js.org/d3-hierarchy/ Version 1.1.5. Copyright 2017 Mike Bostock.
  9711. (function (global, factory) {
  9712. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  9713. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  9714. (factory((global.d3 = global.d3 || {})));
  9715. }(this, (function (exports) { 'use strict';
  9716. function defaultSeparation(a, b) {
  9717. return a.parent === b.parent ? 1 : 2;
  9718. }
  9719. function meanX(children) {
  9720. return children.reduce(meanXReduce, 0) / children.length;
  9721. }
  9722. function meanXReduce(x, c) {
  9723. return x + c.x;
  9724. }
  9725. function maxY(children) {
  9726. return 1 + children.reduce(maxYReduce, 0);
  9727. }
  9728. function maxYReduce(y, c) {
  9729. return Math.max(y, c.y);
  9730. }
  9731. function leafLeft(node) {
  9732. var children;
  9733. while (children = node.children) node = children[0];
  9734. return node;
  9735. }
  9736. function leafRight(node) {
  9737. var children;
  9738. while (children = node.children) node = children[children.length - 1];
  9739. return node;
  9740. }
  9741. var cluster = function() {
  9742. var separation = defaultSeparation,
  9743. dx = 1,
  9744. dy = 1,
  9745. nodeSize = false;
  9746. function cluster(root) {
  9747. var previousNode,
  9748. x = 0;
  9749. // First walk, computing the initial x & y values.
  9750. root.eachAfter(function(node) {
  9751. var children = node.children;
  9752. if (children) {
  9753. node.x = meanX(children);
  9754. node.y = maxY(children);
  9755. } else {
  9756. node.x = previousNode ? x += separation(node, previousNode) : 0;
  9757. node.y = 0;
  9758. previousNode = node;
  9759. }
  9760. });
  9761. var left = leafLeft(root),
  9762. right = leafRight(root),
  9763. x0 = left.x - separation(left, right) / 2,
  9764. x1 = right.x + separation(right, left) / 2;
  9765. // Second walk, normalizing x & y to the desired size.
  9766. return root.eachAfter(nodeSize ? function(node) {
  9767. node.x = (node.x - root.x) * dx;
  9768. node.y = (root.y - node.y) * dy;
  9769. } : function(node) {
  9770. node.x = (node.x - x0) / (x1 - x0) * dx;
  9771. node.y = (1 - (root.y ? node.y / root.y : 1)) * dy;
  9772. });
  9773. }
  9774. cluster.separation = function(x) {
  9775. return arguments.length ? (separation = x, cluster) : separation;
  9776. };
  9777. cluster.size = function(x) {
  9778. return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? null : [dx, dy]);
  9779. };
  9780. cluster.nodeSize = function(x) {
  9781. return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? [dx, dy] : null);
  9782. };
  9783. return cluster;
  9784. };
  9785. function count(node) {
  9786. var sum = 0,
  9787. children = node.children,
  9788. i = children && children.length;
  9789. if (!i) sum = 1;
  9790. else while (--i >= 0) sum += children[i].value;
  9791. node.value = sum;
  9792. }
  9793. var node_count = function() {
  9794. return this.eachAfter(count);
  9795. };
  9796. var node_each = function(callback) {
  9797. var node = this, current, next = [node], children, i, n;
  9798. do {
  9799. current = next.reverse(), next = [];
  9800. while (node = current.pop()) {
  9801. callback(node), children = node.children;
  9802. if (children) for (i = 0, n = children.length; i < n; ++i) {
  9803. next.push(children[i]);
  9804. }
  9805. }
  9806. } while (next.length);
  9807. return this;
  9808. };
  9809. var node_eachBefore = function(callback) {
  9810. var node = this, nodes = [node], children, i;
  9811. while (node = nodes.pop()) {
  9812. callback(node), children = node.children;
  9813. if (children) for (i = children.length - 1; i >= 0; --i) {
  9814. nodes.push(children[i]);
  9815. }
  9816. }
  9817. return this;
  9818. };
  9819. var node_eachAfter = function(callback) {
  9820. var node = this, nodes = [node], next = [], children, i, n;
  9821. while (node = nodes.pop()) {
  9822. next.push(node), children = node.children;
  9823. if (children) for (i = 0, n = children.length; i < n; ++i) {
  9824. nodes.push(children[i]);
  9825. }
  9826. }
  9827. while (node = next.pop()) {
  9828. callback(node);
  9829. }
  9830. return this;
  9831. };
  9832. var node_sum = function(value) {
  9833. return this.eachAfter(function(node) {
  9834. var sum = +value(node.data) || 0,
  9835. children = node.children,
  9836. i = children && children.length;
  9837. while (--i >= 0) sum += children[i].value;
  9838. node.value = sum;
  9839. });
  9840. };
  9841. var node_sort = function(compare) {
  9842. return this.eachBefore(function(node) {
  9843. if (node.children) {
  9844. node.children.sort(compare);
  9845. }
  9846. });
  9847. };
  9848. var node_path = function(end) {
  9849. var start = this,
  9850. ancestor = leastCommonAncestor(start, end),
  9851. nodes = [start];
  9852. while (start !== ancestor) {
  9853. start = start.parent;
  9854. nodes.push(start);
  9855. }
  9856. var k = nodes.length;
  9857. while (end !== ancestor) {
  9858. nodes.splice(k, 0, end);
  9859. end = end.parent;
  9860. }
  9861. return nodes;
  9862. };
  9863. function leastCommonAncestor(a, b) {
  9864. if (a === b) return a;
  9865. var aNodes = a.ancestors(),
  9866. bNodes = b.ancestors(),
  9867. c = null;
  9868. a = aNodes.pop();
  9869. b = bNodes.pop();
  9870. while (a === b) {
  9871. c = a;
  9872. a = aNodes.pop();
  9873. b = bNodes.pop();
  9874. }
  9875. return c;
  9876. }
  9877. var node_ancestors = function() {
  9878. var node = this, nodes = [node];
  9879. while (node = node.parent) {
  9880. nodes.push(node);
  9881. }
  9882. return nodes;
  9883. };
  9884. var node_descendants = function() {
  9885. var nodes = [];
  9886. this.each(function(node) {
  9887. nodes.push(node);
  9888. });
  9889. return nodes;
  9890. };
  9891. var node_leaves = function() {
  9892. var leaves = [];
  9893. this.eachBefore(function(node) {
  9894. if (!node.children) {
  9895. leaves.push(node);
  9896. }
  9897. });
  9898. return leaves;
  9899. };
  9900. var node_links = function() {
  9901. var root = this, links = [];
  9902. root.each(function(node) {
  9903. if (node !== root) { // Don’t include the root’s parent, if any.
  9904. links.push({source: node.parent, target: node});
  9905. }
  9906. });
  9907. return links;
  9908. };
  9909. function hierarchy(data, children) {
  9910. var root = new Node(data),
  9911. valued = +data.value && (root.value = data.value),
  9912. node,
  9913. nodes = [root],
  9914. child,
  9915. childs,
  9916. i,
  9917. n;
  9918. if (children == null) children = defaultChildren;
  9919. while (node = nodes.pop()) {
  9920. if (valued) node.value = +node.data.value;
  9921. if ((childs = children(node.data)) && (n = childs.length)) {
  9922. node.children = new Array(n);
  9923. for (i = n - 1; i >= 0; --i) {
  9924. nodes.push(child = node.children[i] = new Node(childs[i]));
  9925. child.parent = node;
  9926. child.depth = node.depth + 1;
  9927. }
  9928. }
  9929. }
  9930. return root.eachBefore(computeHeight);
  9931. }
  9932. function node_copy() {
  9933. return hierarchy(this).eachBefore(copyData);
  9934. }
  9935. function defaultChildren(d) {
  9936. return d.children;
  9937. }
  9938. function copyData(node) {
  9939. node.data = node.data.data;
  9940. }
  9941. function computeHeight(node) {
  9942. var height = 0;
  9943. do node.height = height;
  9944. while ((node = node.parent) && (node.height < ++height));
  9945. }
  9946. function Node(data) {
  9947. this.data = data;
  9948. this.depth =
  9949. this.height = 0;
  9950. this.parent = null;
  9951. }
  9952. Node.prototype = hierarchy.prototype = {
  9953. constructor: Node,
  9954. count: node_count,
  9955. each: node_each,
  9956. eachAfter: node_eachAfter,
  9957. eachBefore: node_eachBefore,
  9958. sum: node_sum,
  9959. sort: node_sort,
  9960. path: node_path,
  9961. ancestors: node_ancestors,
  9962. descendants: node_descendants,
  9963. leaves: node_leaves,
  9964. links: node_links,
  9965. copy: node_copy
  9966. };
  9967. var slice = Array.prototype.slice;
  9968. function shuffle(array) {
  9969. var m = array.length,
  9970. t,
  9971. i;
  9972. while (m) {
  9973. i = Math.random() * m-- | 0;
  9974. t = array[m];
  9975. array[m] = array[i];
  9976. array[i] = t;
  9977. }
  9978. return array;
  9979. }
  9980. var enclose = function(circles) {
  9981. var i = 0, n = (circles = shuffle(slice.call(circles))).length, B = [], p, e;
  9982. while (i < n) {
  9983. p = circles[i];
  9984. if (e && enclosesWeak(e, p)) ++i;
  9985. else e = encloseBasis(B = extendBasis(B, p)), i = 0;
  9986. }
  9987. return e;
  9988. };
  9989. function extendBasis(B, p) {
  9990. var i, j;
  9991. if (enclosesWeakAll(p, B)) return [p];
  9992. // If we get here then B must have at least one element.
  9993. for (i = 0; i < B.length; ++i) {
  9994. if (enclosesNot(p, B[i])
  9995. && enclosesWeakAll(encloseBasis2(B[i], p), B)) {
  9996. return [B[i], p];
  9997. }
  9998. }
  9999. // If we get here then B must have at least two elements.
  10000. for (i = 0; i < B.length - 1; ++i) {
  10001. for (j = i + 1; j < B.length; ++j) {
  10002. if (enclosesNot(encloseBasis2(B[i], B[j]), p)
  10003. && enclosesNot(encloseBasis2(B[i], p), B[j])
  10004. && enclosesNot(encloseBasis2(B[j], p), B[i])
  10005. && enclosesWeakAll(encloseBasis3(B[i], B[j], p), B)) {
  10006. return [B[i], B[j], p];
  10007. }
  10008. }
  10009. }
  10010. // If we get here then something is very wrong.
  10011. throw new Error;
  10012. }
  10013. function enclosesNot(a, b) {
  10014. var dr = a.r - b.r, dx = b.x - a.x, dy = b.y - a.y;
  10015. return dr < 0 || dr * dr < dx * dx + dy * dy;
  10016. }
  10017. function enclosesWeak(a, b) {
  10018. var dr = a.r - b.r + 1e-6, dx = b.x - a.x, dy = b.y - a.y;
  10019. return dr > 0 && dr * dr > dx * dx + dy * dy;
  10020. }
  10021. function enclosesWeakAll(a, B) {
  10022. for (var i = 0; i < B.length; ++i) {
  10023. if (!enclosesWeak(a, B[i])) {
  10024. return false;
  10025. }
  10026. }
  10027. return true;
  10028. }
  10029. function encloseBasis(B) {
  10030. switch (B.length) {
  10031. case 1: return encloseBasis1(B[0]);
  10032. case 2: return encloseBasis2(B[0], B[1]);
  10033. case 3: return encloseBasis3(B[0], B[1], B[2]);
  10034. }
  10035. }
  10036. function encloseBasis1(a) {
  10037. return {
  10038. x: a.x,
  10039. y: a.y,
  10040. r: a.r
  10041. };
  10042. }
  10043. function encloseBasis2(a, b) {
  10044. var x1 = a.x, y1 = a.y, r1 = a.r,
  10045. x2 = b.x, y2 = b.y, r2 = b.r,
  10046. x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1,
  10047. l = Math.sqrt(x21 * x21 + y21 * y21);
  10048. return {
  10049. x: (x1 + x2 + x21 / l * r21) / 2,
  10050. y: (y1 + y2 + y21 / l * r21) / 2,
  10051. r: (l + r1 + r2) / 2
  10052. };
  10053. }
  10054. function encloseBasis3(a, b, c) {
  10055. var x1 = a.x, y1 = a.y, r1 = a.r,
  10056. x2 = b.x, y2 = b.y, r2 = b.r,
  10057. x3 = c.x, y3 = c.y, r3 = c.r,
  10058. a2 = x1 - x2,
  10059. a3 = x1 - x3,
  10060. b2 = y1 - y2,
  10061. b3 = y1 - y3,
  10062. c2 = r2 - r1,
  10063. c3 = r3 - r1,
  10064. d1 = x1 * x1 + y1 * y1 - r1 * r1,
  10065. d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2,
  10066. d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3,
  10067. ab = a3 * b2 - a2 * b3,
  10068. xa = (b2 * d3 - b3 * d2) / (ab * 2) - x1,
  10069. xb = (b3 * c2 - b2 * c3) / ab,
  10070. ya = (a3 * d2 - a2 * d3) / (ab * 2) - y1,
  10071. yb = (a2 * c3 - a3 * c2) / ab,
  10072. A = xb * xb + yb * yb - 1,
  10073. B = 2 * (r1 + xa * xb + ya * yb),
  10074. C = xa * xa + ya * ya - r1 * r1,
  10075. r = -(A ? (B + Math.sqrt(B * B - 4 * A * C)) / (2 * A) : C / B);
  10076. return {
  10077. x: x1 + xa + xb * r,
  10078. y: y1 + ya + yb * r,
  10079. r: r
  10080. };
  10081. }
  10082. function place(a, b, c) {
  10083. var ax = a.x,
  10084. ay = a.y,
  10085. da = b.r + c.r,
  10086. db = a.r + c.r,
  10087. dx = b.x - ax,
  10088. dy = b.y - ay,
  10089. dc = dx * dx + dy * dy;
  10090. if (dc) {
  10091. var x = 0.5 + ((db *= db) - (da *= da)) / (2 * dc),
  10092. y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
  10093. c.x = ax + x * dx + y * dy;
  10094. c.y = ay + x * dy - y * dx;
  10095. } else {
  10096. c.x = ax + db;
  10097. c.y = ay;
  10098. }
  10099. }
  10100. function intersects(a, b) {
  10101. var dx = b.x - a.x,
  10102. dy = b.y - a.y,
  10103. dr = a.r + b.r;
  10104. return dr * dr - 1e-6 > dx * dx + dy * dy;
  10105. }
  10106. function score(node) {
  10107. var a = node._,
  10108. b = node.next._,
  10109. ab = a.r + b.r,
  10110. dx = (a.x * b.r + b.x * a.r) / ab,
  10111. dy = (a.y * b.r + b.y * a.r) / ab;
  10112. return dx * dx + dy * dy;
  10113. }
  10114. function Node$1(circle) {
  10115. this._ = circle;
  10116. this.next = null;
  10117. this.previous = null;
  10118. }
  10119. function packEnclose(circles) {
  10120. if (!(n = circles.length)) return 0;
  10121. var a, b, c, n, aa, ca, i, j, k, sj, sk;
  10122. // Place the first circle.
  10123. a = circles[0], a.x = 0, a.y = 0;
  10124. if (!(n > 1)) return a.r;
  10125. // Place the second circle.
  10126. b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0;
  10127. if (!(n > 2)) return a.r + b.r;
  10128. // Place the third circle.
  10129. place(b, a, c = circles[2]);
  10130. // Initialize the front-chain using the first three circles a, b and c.
  10131. a = new Node$1(a), b = new Node$1(b), c = new Node$1(c);
  10132. a.next = c.previous = b;
  10133. b.next = a.previous = c;
  10134. c.next = b.previous = a;
  10135. // Attempt to place each remaining circle…
  10136. pack: for (i = 3; i < n; ++i) {
  10137. place(a._, b._, c = circles[i]), c = new Node$1(c);
  10138. // Find the closest intersecting circle on the front-chain, if any.
  10139. // “Closeness” is determined by linear distance along the front-chain.
  10140. // “Ahead” or “behind” is likewise determined by linear distance.
  10141. j = b.next, k = a.previous, sj = b._.r, sk = a._.r;
  10142. do {
  10143. if (sj <= sk) {
  10144. if (intersects(j._, c._)) {
  10145. b = j, a.next = b, b.previous = a, --i;
  10146. continue pack;
  10147. }
  10148. sj += j._.r, j = j.next;
  10149. } else {
  10150. if (intersects(k._, c._)) {
  10151. a = k, a.next = b, b.previous = a, --i;
  10152. continue pack;
  10153. }
  10154. sk += k._.r, k = k.previous;
  10155. }
  10156. } while (j !== k.next);
  10157. // Success! Insert the new circle c between a and b.
  10158. c.previous = a, c.next = b, a.next = b.previous = b = c;
  10159. // Compute the new closest circle pair to the centroid.
  10160. aa = score(a);
  10161. while ((c = c.next) !== b) {
  10162. if ((ca = score(c)) < aa) {
  10163. a = c, aa = ca;
  10164. }
  10165. }
  10166. b = a.next;
  10167. }
  10168. // Compute the enclosing circle of the front chain.
  10169. a = [b._], c = b; while ((c = c.next) !== b) a.push(c._); c = enclose(a);
  10170. // Translate the circles to put the enclosing circle around the origin.
  10171. for (i = 0; i < n; ++i) a = circles[i], a.x -= c.x, a.y -= c.y;
  10172. return c.r;
  10173. }
  10174. var siblings = function(circles) {
  10175. packEnclose(circles);
  10176. return circles;
  10177. };
  10178. function optional(f) {
  10179. return f == null ? null : required(f);
  10180. }
  10181. function required(f) {
  10182. if (typeof f !== "function") throw new Error;
  10183. return f;
  10184. }
  10185. function constantZero() {
  10186. return 0;
  10187. }
  10188. var constant = function(x) {
  10189. return function() {
  10190. return x;
  10191. };
  10192. };
  10193. function defaultRadius(d) {
  10194. return Math.sqrt(d.value);
  10195. }
  10196. var index = function() {
  10197. var radius = null,
  10198. dx = 1,
  10199. dy = 1,
  10200. padding = constantZero;
  10201. function pack(root) {
  10202. root.x = dx / 2, root.y = dy / 2;
  10203. if (radius) {
  10204. root.eachBefore(radiusLeaf(radius))
  10205. .eachAfter(packChildren(padding, 0.5))
  10206. .eachBefore(translateChild(1));
  10207. } else {
  10208. root.eachBefore(radiusLeaf(defaultRadius))
  10209. .eachAfter(packChildren(constantZero, 1))
  10210. .eachAfter(packChildren(padding, root.r / Math.min(dx, dy)))
  10211. .eachBefore(translateChild(Math.min(dx, dy) / (2 * root.r)));
  10212. }
  10213. return root;
  10214. }
  10215. pack.radius = function(x) {
  10216. return arguments.length ? (radius = optional(x), pack) : radius;
  10217. };
  10218. pack.size = function(x) {
  10219. return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [dx, dy];
  10220. };
  10221. pack.padding = function(x) {
  10222. return arguments.length ? (padding = typeof x === "function" ? x : constant(+x), pack) : padding;
  10223. };
  10224. return pack;
  10225. };
  10226. function radiusLeaf(radius) {
  10227. return function(node) {
  10228. if (!node.children) {
  10229. node.r = Math.max(0, +radius(node) || 0);
  10230. }
  10231. };
  10232. }
  10233. function packChildren(padding, k) {
  10234. return function(node) {
  10235. if (children = node.children) {
  10236. var children,
  10237. i,
  10238. n = children.length,
  10239. r = padding(node) * k || 0,
  10240. e;
  10241. if (r) for (i = 0; i < n; ++i) children[i].r += r;
  10242. e = packEnclose(children);
  10243. if (r) for (i = 0; i < n; ++i) children[i].r -= r;
  10244. node.r = e + r;
  10245. }
  10246. };
  10247. }
  10248. function translateChild(k) {
  10249. return function(node) {
  10250. var parent = node.parent;
  10251. node.r *= k;
  10252. if (parent) {
  10253. node.x = parent.x + k * node.x;
  10254. node.y = parent.y + k * node.y;
  10255. }
  10256. };
  10257. }
  10258. var roundNode = function(node) {
  10259. node.x0 = Math.round(node.x0);
  10260. node.y0 = Math.round(node.y0);
  10261. node.x1 = Math.round(node.x1);
  10262. node.y1 = Math.round(node.y1);
  10263. };
  10264. var treemapDice = function(parent, x0, y0, x1, y1) {
  10265. var nodes = parent.children,
  10266. node,
  10267. i = -1,
  10268. n = nodes.length,
  10269. k = parent.value && (x1 - x0) / parent.value;
  10270. while (++i < n) {
  10271. node = nodes[i], node.y0 = y0, node.y1 = y1;
  10272. node.x0 = x0, node.x1 = x0 += node.value * k;
  10273. }
  10274. };
  10275. var partition = function() {
  10276. var dx = 1,
  10277. dy = 1,
  10278. padding = 0,
  10279. round = false;
  10280. function partition(root) {
  10281. var n = root.height + 1;
  10282. root.x0 =
  10283. root.y0 = padding;
  10284. root.x1 = dx;
  10285. root.y1 = dy / n;
  10286. root.eachBefore(positionNode(dy, n));
  10287. if (round) root.eachBefore(roundNode);
  10288. return root;
  10289. }
  10290. function positionNode(dy, n) {
  10291. return function(node) {
  10292. if (node.children) {
  10293. treemapDice(node, node.x0, dy * (node.depth + 1) / n, node.x1, dy * (node.depth + 2) / n);
  10294. }
  10295. var x0 = node.x0,
  10296. y0 = node.y0,
  10297. x1 = node.x1 - padding,
  10298. y1 = node.y1 - padding;
  10299. if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
  10300. if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
  10301. node.x0 = x0;
  10302. node.y0 = y0;
  10303. node.x1 = x1;
  10304. node.y1 = y1;
  10305. };
  10306. }
  10307. partition.round = function(x) {
  10308. return arguments.length ? (round = !!x, partition) : round;
  10309. };
  10310. partition.size = function(x) {
  10311. return arguments.length ? (dx = +x[0], dy = +x[1], partition) : [dx, dy];
  10312. };
  10313. partition.padding = function(x) {
  10314. return arguments.length ? (padding = +x, partition) : padding;
  10315. };
  10316. return partition;
  10317. };
  10318. var keyPrefix = "$";
  10319. var preroot = {depth: -1};
  10320. var ambiguous = {};
  10321. function defaultId(d) {
  10322. return d.id;
  10323. }
  10324. function defaultParentId(d) {
  10325. return d.parentId;
  10326. }
  10327. var stratify = function() {
  10328. var id = defaultId,
  10329. parentId = defaultParentId;
  10330. function stratify(data) {
  10331. var d,
  10332. i,
  10333. n = data.length,
  10334. root,
  10335. parent,
  10336. node,
  10337. nodes = new Array(n),
  10338. nodeId,
  10339. nodeKey,
  10340. nodeByKey = {};
  10341. for (i = 0; i < n; ++i) {
  10342. d = data[i], node = nodes[i] = new Node(d);
  10343. if ((nodeId = id(d, i, data)) != null && (nodeId += "")) {
  10344. nodeKey = keyPrefix + (node.id = nodeId);
  10345. nodeByKey[nodeKey] = nodeKey in nodeByKey ? ambiguous : node;
  10346. }
  10347. }
  10348. for (i = 0; i < n; ++i) {
  10349. node = nodes[i], nodeId = parentId(data[i], i, data);
  10350. if (nodeId == null || !(nodeId += "")) {
  10351. if (root) throw new Error("multiple roots");
  10352. root = node;
  10353. } else {
  10354. parent = nodeByKey[keyPrefix + nodeId];
  10355. if (!parent) throw new Error("missing: " + nodeId);
  10356. if (parent === ambiguous) throw new Error("ambiguous: " + nodeId);
  10357. if (parent.children) parent.children.push(node);
  10358. else parent.children = [node];
  10359. node.parent = parent;
  10360. }
  10361. }
  10362. if (!root) throw new Error("no root");
  10363. root.parent = preroot;
  10364. root.eachBefore(function(node) { node.depth = node.parent.depth + 1; --n; }).eachBefore(computeHeight);
  10365. root.parent = null;
  10366. if (n > 0) throw new Error("cycle");
  10367. return root;
  10368. }
  10369. stratify.id = function(x) {
  10370. return arguments.length ? (id = required(x), stratify) : id;
  10371. };
  10372. stratify.parentId = function(x) {
  10373. return arguments.length ? (parentId = required(x), stratify) : parentId;
  10374. };
  10375. return stratify;
  10376. };
  10377. function defaultSeparation$1(a, b) {
  10378. return a.parent === b.parent ? 1 : 2;
  10379. }
  10380. // function radialSeparation(a, b) {
  10381. // return (a.parent === b.parent ? 1 : 2) / a.depth;
  10382. // }
  10383. // This function is used to traverse the left contour of a subtree (or
  10384. // subforest). It returns the successor of v on this contour. This successor is
  10385. // either given by the leftmost child of v or by the thread of v. The function
  10386. // returns null if and only if v is on the highest level of its subtree.
  10387. function nextLeft(v) {
  10388. var children = v.children;
  10389. return children ? children[0] : v.t;
  10390. }
  10391. // This function works analogously to nextLeft.
  10392. function nextRight(v) {
  10393. var children = v.children;
  10394. return children ? children[children.length - 1] : v.t;
  10395. }
  10396. // Shifts the current subtree rooted at w+. This is done by increasing
  10397. // prelim(w+) and mod(w+) by shift.
  10398. function moveSubtree(wm, wp, shift) {
  10399. var change = shift / (wp.i - wm.i);
  10400. wp.c -= change;
  10401. wp.s += shift;
  10402. wm.c += change;
  10403. wp.z += shift;
  10404. wp.m += shift;
  10405. }
  10406. // All other shifts, applied to the smaller subtrees between w- and w+, are
  10407. // performed by this function. To prepare the shifts, we have to adjust
  10408. // change(w+), shift(w+), and change(w-).
  10409. function executeShifts(v) {
  10410. var shift = 0,
  10411. change = 0,
  10412. children = v.children,
  10413. i = children.length,
  10414. w;
  10415. while (--i >= 0) {
  10416. w = children[i];
  10417. w.z += shift;
  10418. w.m += shift;
  10419. shift += w.s + (change += w.c);
  10420. }
  10421. }
  10422. // If vi-’s ancestor is a sibling of v, returns vi-’s ancestor. Otherwise,
  10423. // returns the specified (default) ancestor.
  10424. function nextAncestor(vim, v, ancestor) {
  10425. return vim.a.parent === v.parent ? vim.a : ancestor;
  10426. }
  10427. function TreeNode(node, i) {
  10428. this._ = node;
  10429. this.parent = null;
  10430. this.children = null;
  10431. this.A = null; // default ancestor
  10432. this.a = this; // ancestor
  10433. this.z = 0; // prelim
  10434. this.m = 0; // mod
  10435. this.c = 0; // change
  10436. this.s = 0; // shift
  10437. this.t = null; // thread
  10438. this.i = i; // number
  10439. }
  10440. TreeNode.prototype = Object.create(Node.prototype);
  10441. function treeRoot(root) {
  10442. var tree = new TreeNode(root, 0),
  10443. node,
  10444. nodes = [tree],
  10445. child,
  10446. children,
  10447. i,
  10448. n;
  10449. while (node = nodes.pop()) {
  10450. if (children = node._.children) {
  10451. node.children = new Array(n = children.length);
  10452. for (i = n - 1; i >= 0; --i) {
  10453. nodes.push(child = node.children[i] = new TreeNode(children[i], i));
  10454. child.parent = node;
  10455. }
  10456. }
  10457. }
  10458. (tree.parent = new TreeNode(null, 0)).children = [tree];
  10459. return tree;
  10460. }
  10461. // Node-link tree diagram using the Reingold-Tilford "tidy" algorithm
  10462. var tree = function() {
  10463. var separation = defaultSeparation$1,
  10464. dx = 1,
  10465. dy = 1,
  10466. nodeSize = null;
  10467. function tree(root) {
  10468. var t = treeRoot(root);
  10469. // Compute the layout using Buchheim et al.’s algorithm.
  10470. t.eachAfter(firstWalk), t.parent.m = -t.z;
  10471. t.eachBefore(secondWalk);
  10472. // If a fixed node size is specified, scale x and y.
  10473. if (nodeSize) root.eachBefore(sizeNode);
  10474. // If a fixed tree size is specified, scale x and y based on the extent.
  10475. // Compute the left-most, right-most, and depth-most nodes for extents.
  10476. else {
  10477. var left = root,
  10478. right = root,
  10479. bottom = root;
  10480. root.eachBefore(function(node) {
  10481. if (node.x < left.x) left = node;
  10482. if (node.x > right.x) right = node;
  10483. if (node.depth > bottom.depth) bottom = node;
  10484. });
  10485. var s = left === right ? 1 : separation(left, right) / 2,
  10486. tx = s - left.x,
  10487. kx = dx / (right.x + s + tx),
  10488. ky = dy / (bottom.depth || 1);
  10489. root.eachBefore(function(node) {
  10490. node.x = (node.x + tx) * kx;
  10491. node.y = node.depth * ky;
  10492. });
  10493. }
  10494. return root;
  10495. }
  10496. // Computes a preliminary x-coordinate for v. Before that, FIRST WALK is
  10497. // applied recursively to the children of v, as well as the function
  10498. // APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the
  10499. // node v is placed to the midpoint of its outermost children.
  10500. function firstWalk(v) {
  10501. var children = v.children,
  10502. siblings = v.parent.children,
  10503. w = v.i ? siblings[v.i - 1] : null;
  10504. if (children) {
  10505. executeShifts(v);
  10506. var midpoint = (children[0].z + children[children.length - 1].z) / 2;
  10507. if (w) {
  10508. v.z = w.z + separation(v._, w._);
  10509. v.m = v.z - midpoint;
  10510. } else {
  10511. v.z = midpoint;
  10512. }
  10513. } else if (w) {
  10514. v.z = w.z + separation(v._, w._);
  10515. }
  10516. v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
  10517. }
  10518. // Computes all real x-coordinates by summing up the modifiers recursively.
  10519. function secondWalk(v) {
  10520. v._.x = v.z + v.parent.m;
  10521. v.m += v.parent.m;
  10522. }
  10523. // The core of the algorithm. Here, a new subtree is combined with the
  10524. // previous subtrees. Threads are used to traverse the inside and outside
  10525. // contours of the left and right subtree up to the highest common level. The
  10526. // vertices used for the traversals are vi+, vi-, vo-, and vo+, where the
  10527. // superscript o means outside and i means inside, the subscript - means left
  10528. // subtree and + means right subtree. For summing up the modifiers along the
  10529. // contour, we use respective variables si+, si-, so-, and so+. Whenever two
  10530. // nodes of the inside contours conflict, we compute the left one of the
  10531. // greatest uncommon ancestors using the function ANCESTOR and call MOVE
  10532. // SUBTREE to shift the subtree and prepare the shifts of smaller subtrees.
  10533. // Finally, we add a new thread (if necessary).
  10534. function apportion(v, w, ancestor) {
  10535. if (w) {
  10536. var vip = v,
  10537. vop = v,
  10538. vim = w,
  10539. vom = vip.parent.children[0],
  10540. sip = vip.m,
  10541. sop = vop.m,
  10542. sim = vim.m,
  10543. som = vom.m,
  10544. shift;
  10545. while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) {
  10546. vom = nextLeft(vom);
  10547. vop = nextRight(vop);
  10548. vop.a = v;
  10549. shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
  10550. if (shift > 0) {
  10551. moveSubtree(nextAncestor(vim, v, ancestor), v, shift);
  10552. sip += shift;
  10553. sop += shift;
  10554. }
  10555. sim += vim.m;
  10556. sip += vip.m;
  10557. som += vom.m;
  10558. sop += vop.m;
  10559. }
  10560. if (vim && !nextRight(vop)) {
  10561. vop.t = vim;
  10562. vop.m += sim - sop;
  10563. }
  10564. if (vip && !nextLeft(vom)) {
  10565. vom.t = vip;
  10566. vom.m += sip - som;
  10567. ancestor = v;
  10568. }
  10569. }
  10570. return ancestor;
  10571. }
  10572. function sizeNode(node) {
  10573. node.x *= dx;
  10574. node.y = node.depth * dy;
  10575. }
  10576. tree.separation = function(x) {
  10577. return arguments.length ? (separation = x, tree) : separation;
  10578. };
  10579. tree.size = function(x) {
  10580. return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree) : (nodeSize ? null : [dx, dy]);
  10581. };
  10582. tree.nodeSize = function(x) {
  10583. return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree) : (nodeSize ? [dx, dy] : null);
  10584. };
  10585. return tree;
  10586. };
  10587. var treemapSlice = function(parent, x0, y0, x1, y1) {
  10588. var nodes = parent.children,
  10589. node,
  10590. i = -1,
  10591. n = nodes.length,
  10592. k = parent.value && (y1 - y0) / parent.value;
  10593. while (++i < n) {
  10594. node = nodes[i], node.x0 = x0, node.x1 = x1;
  10595. node.y0 = y0, node.y1 = y0 += node.value * k;
  10596. }
  10597. };
  10598. var phi = (1 + Math.sqrt(5)) / 2;
  10599. function squarifyRatio(ratio, parent, x0, y0, x1, y1) {
  10600. var rows = [],
  10601. nodes = parent.children,
  10602. row,
  10603. nodeValue,
  10604. i0 = 0,
  10605. i1 = 0,
  10606. n = nodes.length,
  10607. dx, dy,
  10608. value = parent.value,
  10609. sumValue,
  10610. minValue,
  10611. maxValue,
  10612. newRatio,
  10613. minRatio,
  10614. alpha,
  10615. beta;
  10616. while (i0 < n) {
  10617. dx = x1 - x0, dy = y1 - y0;
  10618. // Find the next non-empty node.
  10619. do sumValue = nodes[i1++].value; while (!sumValue && i1 < n);
  10620. minValue = maxValue = sumValue;
  10621. alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
  10622. beta = sumValue * sumValue * alpha;
  10623. minRatio = Math.max(maxValue / beta, beta / minValue);
  10624. // Keep adding nodes while the aspect ratio maintains or improves.
  10625. for (; i1 < n; ++i1) {
  10626. sumValue += nodeValue = nodes[i1].value;
  10627. if (nodeValue < minValue) minValue = nodeValue;
  10628. if (nodeValue > maxValue) maxValue = nodeValue;
  10629. beta = sumValue * sumValue * alpha;
  10630. newRatio = Math.max(maxValue / beta, beta / minValue);
  10631. if (newRatio > minRatio) { sumValue -= nodeValue; break; }
  10632. minRatio = newRatio;
  10633. }
  10634. // Position and record the row orientation.
  10635. rows.push(row = {value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1)});
  10636. if (row.dice) treemapDice(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
  10637. else treemapSlice(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
  10638. value -= sumValue, i0 = i1;
  10639. }
  10640. return rows;
  10641. }
  10642. var squarify = ((function custom(ratio) {
  10643. function squarify(parent, x0, y0, x1, y1) {
  10644. squarifyRatio(ratio, parent, x0, y0, x1, y1);
  10645. }
  10646. squarify.ratio = function(x) {
  10647. return custom((x = +x) > 1 ? x : 1);
  10648. };
  10649. return squarify;
  10650. }))(phi);
  10651. var index$1 = function() {
  10652. var tile = squarify,
  10653. round = false,
  10654. dx = 1,
  10655. dy = 1,
  10656. paddingStack = [0],
  10657. paddingInner = constantZero,
  10658. paddingTop = constantZero,
  10659. paddingRight = constantZero,
  10660. paddingBottom = constantZero,
  10661. paddingLeft = constantZero;
  10662. function treemap(root) {
  10663. root.x0 =
  10664. root.y0 = 0;
  10665. root.x1 = dx;
  10666. root.y1 = dy;
  10667. root.eachBefore(positionNode);
  10668. paddingStack = [0];
  10669. if (round) root.eachBefore(roundNode);
  10670. return root;
  10671. }
  10672. function positionNode(node) {
  10673. var p = paddingStack[node.depth],
  10674. x0 = node.x0 + p,
  10675. y0 = node.y0 + p,
  10676. x1 = node.x1 - p,
  10677. y1 = node.y1 - p;
  10678. if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
  10679. if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
  10680. node.x0 = x0;
  10681. node.y0 = y0;
  10682. node.x1 = x1;
  10683. node.y1 = y1;
  10684. if (node.children) {
  10685. p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
  10686. x0 += paddingLeft(node) - p;
  10687. y0 += paddingTop(node) - p;
  10688. x1 -= paddingRight(node) - p;
  10689. y1 -= paddingBottom(node) - p;
  10690. if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
  10691. if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
  10692. tile(node, x0, y0, x1, y1);
  10693. }
  10694. }
  10695. treemap.round = function(x) {
  10696. return arguments.length ? (round = !!x, treemap) : round;
  10697. };
  10698. treemap.size = function(x) {
  10699. return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];
  10700. };
  10701. treemap.tile = function(x) {
  10702. return arguments.length ? (tile = required(x), treemap) : tile;
  10703. };
  10704. treemap.padding = function(x) {
  10705. return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();
  10706. };
  10707. treemap.paddingInner = function(x) {
  10708. return arguments.length ? (paddingInner = typeof x === "function" ? x : constant(+x), treemap) : paddingInner;
  10709. };
  10710. treemap.paddingOuter = function(x) {
  10711. return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();
  10712. };
  10713. treemap.paddingTop = function(x) {
  10714. return arguments.length ? (paddingTop = typeof x === "function" ? x : constant(+x), treemap) : paddingTop;
  10715. };
  10716. treemap.paddingRight = function(x) {
  10717. return arguments.length ? (paddingRight = typeof x === "function" ? x : constant(+x), treemap) : paddingRight;
  10718. };
  10719. treemap.paddingBottom = function(x) {
  10720. return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant(+x), treemap) : paddingBottom;
  10721. };
  10722. treemap.paddingLeft = function(x) {
  10723. return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant(+x), treemap) : paddingLeft;
  10724. };
  10725. return treemap;
  10726. };
  10727. var binary = function(parent, x0, y0, x1, y1) {
  10728. var nodes = parent.children,
  10729. i, n = nodes.length,
  10730. sum, sums = new Array(n + 1);
  10731. for (sums[0] = sum = i = 0; i < n; ++i) {
  10732. sums[i + 1] = sum += nodes[i].value;
  10733. }
  10734. partition(0, n, parent.value, x0, y0, x1, y1);
  10735. function partition(i, j, value, x0, y0, x1, y1) {
  10736. if (i >= j - 1) {
  10737. var node = nodes[i];
  10738. node.x0 = x0, node.y0 = y0;
  10739. node.x1 = x1, node.y1 = y1;
  10740. return;
  10741. }
  10742. var valueOffset = sums[i],
  10743. valueTarget = (value / 2) + valueOffset,
  10744. k = i + 1,
  10745. hi = j - 1;
  10746. while (k < hi) {
  10747. var mid = k + hi >>> 1;
  10748. if (sums[mid] < valueTarget) k = mid + 1;
  10749. else hi = mid;
  10750. }
  10751. if ((valueTarget - sums[k - 1]) < (sums[k] - valueTarget) && i + 1 < k) --k;
  10752. var valueLeft = sums[k] - valueOffset,
  10753. valueRight = value - valueLeft;
  10754. if ((x1 - x0) > (y1 - y0)) {
  10755. var xk = (x0 * valueRight + x1 * valueLeft) / value;
  10756. partition(i, k, valueLeft, x0, y0, xk, y1);
  10757. partition(k, j, valueRight, xk, y0, x1, y1);
  10758. } else {
  10759. var yk = (y0 * valueRight + y1 * valueLeft) / value;
  10760. partition(i, k, valueLeft, x0, y0, x1, yk);
  10761. partition(k, j, valueRight, x0, yk, x1, y1);
  10762. }
  10763. }
  10764. };
  10765. var sliceDice = function(parent, x0, y0, x1, y1) {
  10766. (parent.depth & 1 ? treemapSlice : treemapDice)(parent, x0, y0, x1, y1);
  10767. };
  10768. var resquarify = ((function custom(ratio) {
  10769. function resquarify(parent, x0, y0, x1, y1) {
  10770. if ((rows = parent._squarify) && (rows.ratio === ratio)) {
  10771. var rows,
  10772. row,
  10773. nodes,
  10774. i,
  10775. j = -1,
  10776. n,
  10777. m = rows.length,
  10778. value = parent.value;
  10779. while (++j < m) {
  10780. row = rows[j], nodes = row.children;
  10781. for (i = row.value = 0, n = nodes.length; i < n; ++i) row.value += nodes[i].value;
  10782. if (row.dice) treemapDice(row, x0, y0, x1, y0 += (y1 - y0) * row.value / value);
  10783. else treemapSlice(row, x0, y0, x0 += (x1 - x0) * row.value / value, y1);
  10784. value -= row.value;
  10785. }
  10786. } else {
  10787. parent._squarify = rows = squarifyRatio(ratio, parent, x0, y0, x1, y1);
  10788. rows.ratio = ratio;
  10789. }
  10790. }
  10791. resquarify.ratio = function(x) {
  10792. return custom((x = +x) > 1 ? x : 1);
  10793. };
  10794. return resquarify;
  10795. }))(phi);
  10796. exports.cluster = cluster;
  10797. exports.hierarchy = hierarchy;
  10798. exports.pack = index;
  10799. exports.packSiblings = siblings;
  10800. exports.packEnclose = enclose;
  10801. exports.partition = partition;
  10802. exports.stratify = stratify;
  10803. exports.tree = tree;
  10804. exports.treemap = index$1;
  10805. exports.treemapBinary = binary;
  10806. exports.treemapDice = treemapDice;
  10807. exports.treemapSlice = treemapSlice;
  10808. exports.treemapSliceDice = sliceDice;
  10809. exports.treemapSquarify = squarify;
  10810. exports.treemapResquarify = resquarify;
  10811. Object.defineProperty(exports, '__esModule', { value: true });
  10812. })));
  10813. },{}],53:[function(require,module,exports){
  10814. // https://d3js.org/d3-interpolate/ Version 1.1.6. Copyright 2017 Mike Bostock.
  10815. (function (global, factory) {
  10816. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-color')) :
  10817. typeof define === 'function' && define.amd ? define(['exports', 'd3-color'], factory) :
  10818. (factory((global.d3 = global.d3 || {}),global.d3));
  10819. }(this, (function (exports,d3Color) { 'use strict';
  10820. function basis(t1, v0, v1, v2, v3) {
  10821. var t2 = t1 * t1, t3 = t2 * t1;
  10822. return ((1 - 3 * t1 + 3 * t2 - t3) * v0
  10823. + (4 - 6 * t2 + 3 * t3) * v1
  10824. + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
  10825. + t3 * v3) / 6;
  10826. }
  10827. var basis$1 = function(values) {
  10828. var n = values.length - 1;
  10829. return function(t) {
  10830. var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),
  10831. v1 = values[i],
  10832. v2 = values[i + 1],
  10833. v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,
  10834. v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
  10835. return basis((t - i / n) * n, v0, v1, v2, v3);
  10836. };
  10837. };
  10838. var basisClosed = function(values) {
  10839. var n = values.length;
  10840. return function(t) {
  10841. var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),
  10842. v0 = values[(i + n - 1) % n],
  10843. v1 = values[i % n],
  10844. v2 = values[(i + 1) % n],
  10845. v3 = values[(i + 2) % n];
  10846. return basis((t - i / n) * n, v0, v1, v2, v3);
  10847. };
  10848. };
  10849. var constant = function(x) {
  10850. return function() {
  10851. return x;
  10852. };
  10853. };
  10854. function linear(a, d) {
  10855. return function(t) {
  10856. return a + t * d;
  10857. };
  10858. }
  10859. function exponential(a, b, y) {
  10860. return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
  10861. return Math.pow(a + t * b, y);
  10862. };
  10863. }
  10864. function hue(a, b) {
  10865. var d = b - a;
  10866. return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);
  10867. }
  10868. function gamma(y) {
  10869. return (y = +y) === 1 ? nogamma : function(a, b) {
  10870. return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);
  10871. };
  10872. }
  10873. function nogamma(a, b) {
  10874. var d = b - a;
  10875. return d ? linear(a, d) : constant(isNaN(a) ? b : a);
  10876. }
  10877. var rgb$1 = ((function rgbGamma(y) {
  10878. var color$$1 = gamma(y);
  10879. function rgb$$1(start, end) {
  10880. var r = color$$1((start = d3Color.rgb(start)).r, (end = d3Color.rgb(end)).r),
  10881. g = color$$1(start.g, end.g),
  10882. b = color$$1(start.b, end.b),
  10883. opacity = nogamma(start.opacity, end.opacity);
  10884. return function(t) {
  10885. start.r = r(t);
  10886. start.g = g(t);
  10887. start.b = b(t);
  10888. start.opacity = opacity(t);
  10889. return start + "";
  10890. };
  10891. }
  10892. rgb$$1.gamma = rgbGamma;
  10893. return rgb$$1;
  10894. }))(1);
  10895. function rgbSpline(spline) {
  10896. return function(colors) {
  10897. var n = colors.length,
  10898. r = new Array(n),
  10899. g = new Array(n),
  10900. b = new Array(n),
  10901. i, color$$1;
  10902. for (i = 0; i < n; ++i) {
  10903. color$$1 = d3Color.rgb(colors[i]);
  10904. r[i] = color$$1.r || 0;
  10905. g[i] = color$$1.g || 0;
  10906. b[i] = color$$1.b || 0;
  10907. }
  10908. r = spline(r);
  10909. g = spline(g);
  10910. b = spline(b);
  10911. color$$1.opacity = 1;
  10912. return function(t) {
  10913. color$$1.r = r(t);
  10914. color$$1.g = g(t);
  10915. color$$1.b = b(t);
  10916. return color$$1 + "";
  10917. };
  10918. };
  10919. }
  10920. var rgbBasis = rgbSpline(basis$1);
  10921. var rgbBasisClosed = rgbSpline(basisClosed);
  10922. var array = function(a, b) {
  10923. var nb = b ? b.length : 0,
  10924. na = a ? Math.min(nb, a.length) : 0,
  10925. x = new Array(na),
  10926. c = new Array(nb),
  10927. i;
  10928. for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);
  10929. for (; i < nb; ++i) c[i] = b[i];
  10930. return function(t) {
  10931. for (i = 0; i < na; ++i) c[i] = x[i](t);
  10932. return c;
  10933. };
  10934. };
  10935. var date = function(a, b) {
  10936. var d = new Date;
  10937. return a = +a, b -= a, function(t) {
  10938. return d.setTime(a + b * t), d;
  10939. };
  10940. };
  10941. var number = function(a, b) {
  10942. return a = +a, b -= a, function(t) {
  10943. return a + b * t;
  10944. };
  10945. };
  10946. var object = function(a, b) {
  10947. var i = {},
  10948. c = {},
  10949. k;
  10950. if (a === null || typeof a !== "object") a = {};
  10951. if (b === null || typeof b !== "object") b = {};
  10952. for (k in b) {
  10953. if (k in a) {
  10954. i[k] = value(a[k], b[k]);
  10955. } else {
  10956. c[k] = b[k];
  10957. }
  10958. }
  10959. return function(t) {
  10960. for (k in i) c[k] = i[k](t);
  10961. return c;
  10962. };
  10963. };
  10964. var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
  10965. var reB = new RegExp(reA.source, "g");
  10966. function zero(b) {
  10967. return function() {
  10968. return b;
  10969. };
  10970. }
  10971. function one(b) {
  10972. return function(t) {
  10973. return b(t) + "";
  10974. };
  10975. }
  10976. var string = function(a, b) {
  10977. var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b
  10978. am, // current match in a
  10979. bm, // current match in b
  10980. bs, // string preceding current number in b, if any
  10981. i = -1, // index in s
  10982. s = [], // string constants and placeholders
  10983. q = []; // number interpolators
  10984. // Coerce inputs to strings.
  10985. a = a + "", b = b + "";
  10986. // Interpolate pairs of numbers in a & b.
  10987. while ((am = reA.exec(a))
  10988. && (bm = reB.exec(b))) {
  10989. if ((bs = bm.index) > bi) { // a string precedes the next number in b
  10990. bs = b.slice(bi, bs);
  10991. if (s[i]) s[i] += bs; // coalesce with previous string
  10992. else s[++i] = bs;
  10993. }
  10994. if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
  10995. if (s[i]) s[i] += bm; // coalesce with previous string
  10996. else s[++i] = bm;
  10997. } else { // interpolate non-matching numbers
  10998. s[++i] = null;
  10999. q.push({i: i, x: number(am, bm)});
  11000. }
  11001. bi = reB.lastIndex;
  11002. }
  11003. // Add remains of b.
  11004. if (bi < b.length) {
  11005. bs = b.slice(bi);
  11006. if (s[i]) s[i] += bs; // coalesce with previous string
  11007. else s[++i] = bs;
  11008. }
  11009. // Special optimization for only a single match.
  11010. // Otherwise, interpolate each of the numbers and rejoin the string.
  11011. return s.length < 2 ? (q[0]
  11012. ? one(q[0].x)
  11013. : zero(b))
  11014. : (b = q.length, function(t) {
  11015. for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
  11016. return s.join("");
  11017. });
  11018. };
  11019. var value = function(a, b) {
  11020. var t = typeof b, c;
  11021. return b == null || t === "boolean" ? constant(b)
  11022. : (t === "number" ? number
  11023. : t === "string" ? ((c = d3Color.color(b)) ? (b = c, rgb$1) : string)
  11024. : b instanceof d3Color.color ? rgb$1
  11025. : b instanceof Date ? date
  11026. : Array.isArray(b) ? array
  11027. : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object
  11028. : number)(a, b);
  11029. };
  11030. var round = function(a, b) {
  11031. return a = +a, b -= a, function(t) {
  11032. return Math.round(a + b * t);
  11033. };
  11034. };
  11035. var degrees = 180 / Math.PI;
  11036. var identity = {
  11037. translateX: 0,
  11038. translateY: 0,
  11039. rotate: 0,
  11040. skewX: 0,
  11041. scaleX: 1,
  11042. scaleY: 1
  11043. };
  11044. var decompose = function(a, b, c, d, e, f) {
  11045. var scaleX, scaleY, skewX;
  11046. if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;
  11047. if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;
  11048. if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;
  11049. if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;
  11050. return {
  11051. translateX: e,
  11052. translateY: f,
  11053. rotate: Math.atan2(b, a) * degrees,
  11054. skewX: Math.atan(skewX) * degrees,
  11055. scaleX: scaleX,
  11056. scaleY: scaleY
  11057. };
  11058. };
  11059. var cssNode;
  11060. var cssRoot;
  11061. var cssView;
  11062. var svgNode;
  11063. function parseCss(value) {
  11064. if (value === "none") return identity;
  11065. if (!cssNode) cssNode = document.createElement("DIV"), cssRoot = document.documentElement, cssView = document.defaultView;
  11066. cssNode.style.transform = value;
  11067. value = cssView.getComputedStyle(cssRoot.appendChild(cssNode), null).getPropertyValue("transform");
  11068. cssRoot.removeChild(cssNode);
  11069. value = value.slice(7, -1).split(",");
  11070. return decompose(+value[0], +value[1], +value[2], +value[3], +value[4], +value[5]);
  11071. }
  11072. function parseSvg(value) {
  11073. if (value == null) return identity;
  11074. if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g");
  11075. svgNode.setAttribute("transform", value);
  11076. if (!(value = svgNode.transform.baseVal.consolidate())) return identity;
  11077. value = value.matrix;
  11078. return decompose(value.a, value.b, value.c, value.d, value.e, value.f);
  11079. }
  11080. function interpolateTransform(parse, pxComma, pxParen, degParen) {
  11081. function pop(s) {
  11082. return s.length ? s.pop() + " " : "";
  11083. }
  11084. function translate(xa, ya, xb, yb, s, q) {
  11085. if (xa !== xb || ya !== yb) {
  11086. var i = s.push("translate(", null, pxComma, null, pxParen);
  11087. q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});
  11088. } else if (xb || yb) {
  11089. s.push("translate(" + xb + pxComma + yb + pxParen);
  11090. }
  11091. }
  11092. function rotate(a, b, s, q) {
  11093. if (a !== b) {
  11094. if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path
  11095. q.push({i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: number(a, b)});
  11096. } else if (b) {
  11097. s.push(pop(s) + "rotate(" + b + degParen);
  11098. }
  11099. }
  11100. function skewX(a, b, s, q) {
  11101. if (a !== b) {
  11102. q.push({i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: number(a, b)});
  11103. } else if (b) {
  11104. s.push(pop(s) + "skewX(" + b + degParen);
  11105. }
  11106. }
  11107. function scale(xa, ya, xb, yb, s, q) {
  11108. if (xa !== xb || ya !== yb) {
  11109. var i = s.push(pop(s) + "scale(", null, ",", null, ")");
  11110. q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});
  11111. } else if (xb !== 1 || yb !== 1) {
  11112. s.push(pop(s) + "scale(" + xb + "," + yb + ")");
  11113. }
  11114. }
  11115. return function(a, b) {
  11116. var s = [], // string constants and placeholders
  11117. q = []; // number interpolators
  11118. a = parse(a), b = parse(b);
  11119. translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);
  11120. rotate(a.rotate, b.rotate, s, q);
  11121. skewX(a.skewX, b.skewX, s, q);
  11122. scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);
  11123. a = b = null; // gc
  11124. return function(t) {
  11125. var i = -1, n = q.length, o;
  11126. while (++i < n) s[(o = q[i]).i] = o.x(t);
  11127. return s.join("");
  11128. };
  11129. };
  11130. }
  11131. var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)");
  11132. var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")");
  11133. var rho = Math.SQRT2;
  11134. var rho2 = 2;
  11135. var rho4 = 4;
  11136. var epsilon2 = 1e-12;
  11137. function cosh(x) {
  11138. return ((x = Math.exp(x)) + 1 / x) / 2;
  11139. }
  11140. function sinh(x) {
  11141. return ((x = Math.exp(x)) - 1 / x) / 2;
  11142. }
  11143. function tanh(x) {
  11144. return ((x = Math.exp(2 * x)) - 1) / (x + 1);
  11145. }
  11146. // p0 = [ux0, uy0, w0]
  11147. // p1 = [ux1, uy1, w1]
  11148. var zoom = function(p0, p1) {
  11149. var ux0 = p0[0], uy0 = p0[1], w0 = p0[2],
  11150. ux1 = p1[0], uy1 = p1[1], w1 = p1[2],
  11151. dx = ux1 - ux0,
  11152. dy = uy1 - uy0,
  11153. d2 = dx * dx + dy * dy,
  11154. i,
  11155. S;
  11156. // Special case for u0 ≅ u1.
  11157. if (d2 < epsilon2) {
  11158. S = Math.log(w1 / w0) / rho;
  11159. i = function(t) {
  11160. return [
  11161. ux0 + t * dx,
  11162. uy0 + t * dy,
  11163. w0 * Math.exp(rho * t * S)
  11164. ];
  11165. };
  11166. }
  11167. // General case.
  11168. else {
  11169. var d1 = Math.sqrt(d2),
  11170. b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1),
  11171. b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1),
  11172. r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0),
  11173. r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
  11174. S = (r1 - r0) / rho;
  11175. i = function(t) {
  11176. var s = t * S,
  11177. coshr0 = cosh(r0),
  11178. u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0));
  11179. return [
  11180. ux0 + u * dx,
  11181. uy0 + u * dy,
  11182. w0 * coshr0 / cosh(rho * s + r0)
  11183. ];
  11184. };
  11185. }
  11186. i.duration = S * 1000;
  11187. return i;
  11188. };
  11189. function hsl$1(hue$$1) {
  11190. return function(start, end) {
  11191. var h = hue$$1((start = d3Color.hsl(start)).h, (end = d3Color.hsl(end)).h),
  11192. s = nogamma(start.s, end.s),
  11193. l = nogamma(start.l, end.l),
  11194. opacity = nogamma(start.opacity, end.opacity);
  11195. return function(t) {
  11196. start.h = h(t);
  11197. start.s = s(t);
  11198. start.l = l(t);
  11199. start.opacity = opacity(t);
  11200. return start + "";
  11201. };
  11202. }
  11203. }
  11204. var hsl$2 = hsl$1(hue);
  11205. var hslLong = hsl$1(nogamma);
  11206. function lab$1(start, end) {
  11207. var l = nogamma((start = d3Color.lab(start)).l, (end = d3Color.lab(end)).l),
  11208. a = nogamma(start.a, end.a),
  11209. b = nogamma(start.b, end.b),
  11210. opacity = nogamma(start.opacity, end.opacity);
  11211. return function(t) {
  11212. start.l = l(t);
  11213. start.a = a(t);
  11214. start.b = b(t);
  11215. start.opacity = opacity(t);
  11216. return start + "";
  11217. };
  11218. }
  11219. function hcl$1(hue$$1) {
  11220. return function(start, end) {
  11221. var h = hue$$1((start = d3Color.hcl(start)).h, (end = d3Color.hcl(end)).h),
  11222. c = nogamma(start.c, end.c),
  11223. l = nogamma(start.l, end.l),
  11224. opacity = nogamma(start.opacity, end.opacity);
  11225. return function(t) {
  11226. start.h = h(t);
  11227. start.c = c(t);
  11228. start.l = l(t);
  11229. start.opacity = opacity(t);
  11230. return start + "";
  11231. };
  11232. }
  11233. }
  11234. var hcl$2 = hcl$1(hue);
  11235. var hclLong = hcl$1(nogamma);
  11236. function cubehelix$1(hue$$1) {
  11237. return (function cubehelixGamma(y) {
  11238. y = +y;
  11239. function cubehelix$$1(start, end) {
  11240. var h = hue$$1((start = d3Color.cubehelix(start)).h, (end = d3Color.cubehelix(end)).h),
  11241. s = nogamma(start.s, end.s),
  11242. l = nogamma(start.l, end.l),
  11243. opacity = nogamma(start.opacity, end.opacity);
  11244. return function(t) {
  11245. start.h = h(t);
  11246. start.s = s(t);
  11247. start.l = l(Math.pow(t, y));
  11248. start.opacity = opacity(t);
  11249. return start + "";
  11250. };
  11251. }
  11252. cubehelix$$1.gamma = cubehelixGamma;
  11253. return cubehelix$$1;
  11254. })(1);
  11255. }
  11256. var cubehelix$2 = cubehelix$1(hue);
  11257. var cubehelixLong = cubehelix$1(nogamma);
  11258. var quantize = function(interpolator, n) {
  11259. var samples = new Array(n);
  11260. for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1));
  11261. return samples;
  11262. };
  11263. exports.interpolate = value;
  11264. exports.interpolateArray = array;
  11265. exports.interpolateBasis = basis$1;
  11266. exports.interpolateBasisClosed = basisClosed;
  11267. exports.interpolateDate = date;
  11268. exports.interpolateNumber = number;
  11269. exports.interpolateObject = object;
  11270. exports.interpolateRound = round;
  11271. exports.interpolateString = string;
  11272. exports.interpolateTransformCss = interpolateTransformCss;
  11273. exports.interpolateTransformSvg = interpolateTransformSvg;
  11274. exports.interpolateZoom = zoom;
  11275. exports.interpolateRgb = rgb$1;
  11276. exports.interpolateRgbBasis = rgbBasis;
  11277. exports.interpolateRgbBasisClosed = rgbBasisClosed;
  11278. exports.interpolateHsl = hsl$2;
  11279. exports.interpolateHslLong = hslLong;
  11280. exports.interpolateLab = lab$1;
  11281. exports.interpolateHcl = hcl$2;
  11282. exports.interpolateHclLong = hclLong;
  11283. exports.interpolateCubehelix = cubehelix$2;
  11284. exports.interpolateCubehelixLong = cubehelixLong;
  11285. exports.quantize = quantize;
  11286. Object.defineProperty(exports, '__esModule', { value: true });
  11287. })));
  11288. },{"d3-color":44}],54:[function(require,module,exports){
  11289. // https://d3js.org/d3-path/ Version 1.0.5. Copyright 2017 Mike Bostock.
  11290. (function (global, factory) {
  11291. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  11292. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  11293. (factory((global.d3 = global.d3 || {})));
  11294. }(this, (function (exports) { 'use strict';
  11295. var pi = Math.PI;
  11296. var tau = 2 * pi;
  11297. var epsilon = 1e-6;
  11298. var tauEpsilon = tau - epsilon;
  11299. function Path() {
  11300. this._x0 = this._y0 = // start of current subpath
  11301. this._x1 = this._y1 = null; // end of current subpath
  11302. this._ = "";
  11303. }
  11304. function path() {
  11305. return new Path;
  11306. }
  11307. Path.prototype = path.prototype = {
  11308. constructor: Path,
  11309. moveTo: function(x, y) {
  11310. this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y);
  11311. },
  11312. closePath: function() {
  11313. if (this._x1 !== null) {
  11314. this._x1 = this._x0, this._y1 = this._y0;
  11315. this._ += "Z";
  11316. }
  11317. },
  11318. lineTo: function(x, y) {
  11319. this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y);
  11320. },
  11321. quadraticCurveTo: function(x1, y1, x, y) {
  11322. this._ += "Q" + (+x1) + "," + (+y1) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
  11323. },
  11324. bezierCurveTo: function(x1, y1, x2, y2, x, y) {
  11325. this._ += "C" + (+x1) + "," + (+y1) + "," + (+x2) + "," + (+y2) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
  11326. },
  11327. arcTo: function(x1, y1, x2, y2, r) {
  11328. x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
  11329. var x0 = this._x1,
  11330. y0 = this._y1,
  11331. x21 = x2 - x1,
  11332. y21 = y2 - y1,
  11333. x01 = x0 - x1,
  11334. y01 = y0 - y1,
  11335. l01_2 = x01 * x01 + y01 * y01;
  11336. // Is the radius negative? Error.
  11337. if (r < 0) throw new Error("negative radius: " + r);
  11338. // Is this path empty? Move to (x1,y1).
  11339. if (this._x1 === null) {
  11340. this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
  11341. }
  11342. // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.
  11343. else if (!(l01_2 > epsilon)) {}
  11344. // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?
  11345. // Equivalently, is (x1,y1) coincident with (x2,y2)?
  11346. // Or, is the radius zero? Line to (x1,y1).
  11347. else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) {
  11348. this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
  11349. }
  11350. // Otherwise, draw an arc!
  11351. else {
  11352. var x20 = x2 - x0,
  11353. y20 = y2 - y0,
  11354. l21_2 = x21 * x21 + y21 * y21,
  11355. l20_2 = x20 * x20 + y20 * y20,
  11356. l21 = Math.sqrt(l21_2),
  11357. l01 = Math.sqrt(l01_2),
  11358. l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),
  11359. t01 = l / l01,
  11360. t21 = l / l21;
  11361. // If the start tangent is not coincident with (x0,y0), line to.
  11362. if (Math.abs(t01 - 1) > epsilon) {
  11363. this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01);
  11364. }
  11365. this._ += "A" + r + "," + r + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
  11366. }
  11367. },
  11368. arc: function(x, y, r, a0, a1, ccw) {
  11369. x = +x, y = +y, r = +r;
  11370. var dx = r * Math.cos(a0),
  11371. dy = r * Math.sin(a0),
  11372. x0 = x + dx,
  11373. y0 = y + dy,
  11374. cw = 1 ^ ccw,
  11375. da = ccw ? a0 - a1 : a1 - a0;
  11376. // Is the radius negative? Error.
  11377. if (r < 0) throw new Error("negative radius: " + r);
  11378. // Is this path empty? Move to (x0,y0).
  11379. if (this._x1 === null) {
  11380. this._ += "M" + x0 + "," + y0;
  11381. }
  11382. // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).
  11383. else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {
  11384. this._ += "L" + x0 + "," + y0;
  11385. }
  11386. // Is this arc empty? We’re done.
  11387. if (!r) return;
  11388. // Does the angle go the wrong way? Flip the direction.
  11389. if (da < 0) da = da % tau + tau;
  11390. // Is this a complete circle? Draw two arcs to complete the circle.
  11391. if (da > tauEpsilon) {
  11392. this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0);
  11393. }
  11394. // Is this arc non-empty? Draw an arc!
  11395. else if (da > epsilon) {
  11396. this._ += "A" + r + "," + r + ",0," + (+(da >= pi)) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1));
  11397. }
  11398. },
  11399. rect: function(x, y, w, h) {
  11400. this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + (+w) + "v" + (+h) + "h" + (-w) + "Z";
  11401. },
  11402. toString: function() {
  11403. return this._;
  11404. }
  11405. };
  11406. exports.path = path;
  11407. Object.defineProperty(exports, '__esModule', { value: true });
  11408. })));
  11409. },{}],55:[function(require,module,exports){
  11410. // https://d3js.org/d3-polygon/ Version 1.0.3. Copyright 2017 Mike Bostock.
  11411. (function (global, factory) {
  11412. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  11413. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  11414. (factory((global.d3 = global.d3 || {})));
  11415. }(this, (function (exports) { 'use strict';
  11416. var area = function(polygon) {
  11417. var i = -1,
  11418. n = polygon.length,
  11419. a,
  11420. b = polygon[n - 1],
  11421. area = 0;
  11422. while (++i < n) {
  11423. a = b;
  11424. b = polygon[i];
  11425. area += a[1] * b[0] - a[0] * b[1];
  11426. }
  11427. return area / 2;
  11428. };
  11429. var centroid = function(polygon) {
  11430. var i = -1,
  11431. n = polygon.length,
  11432. x = 0,
  11433. y = 0,
  11434. a,
  11435. b = polygon[n - 1],
  11436. c,
  11437. k = 0;
  11438. while (++i < n) {
  11439. a = b;
  11440. b = polygon[i];
  11441. k += c = a[0] * b[1] - b[0] * a[1];
  11442. x += (a[0] + b[0]) * c;
  11443. y += (a[1] + b[1]) * c;
  11444. }
  11445. return k *= 3, [x / k, y / k];
  11446. };
  11447. // Returns the 2D cross product of AB and AC vectors, i.e., the z-component of
  11448. // the 3D cross product in a quadrant I Cartesian coordinate system (+x is
  11449. // right, +y is up). Returns a positive value if ABC is counter-clockwise,
  11450. // negative if clockwise, and zero if the points are collinear.
  11451. var cross = function(a, b, c) {
  11452. return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
  11453. };
  11454. function lexicographicOrder(a, b) {
  11455. return a[0] - b[0] || a[1] - b[1];
  11456. }
  11457. // Computes the upper convex hull per the monotone chain algorithm.
  11458. // Assumes points.length >= 3, is sorted by x, unique in y.
  11459. // Returns an array of indices into points in left-to-right order.
  11460. function computeUpperHullIndexes(points) {
  11461. var n = points.length,
  11462. indexes = [0, 1],
  11463. size = 2;
  11464. for (var i = 2; i < n; ++i) {
  11465. while (size > 1 && cross(points[indexes[size - 2]], points[indexes[size - 1]], points[i]) <= 0) --size;
  11466. indexes[size++] = i;
  11467. }
  11468. return indexes.slice(0, size); // remove popped points
  11469. }
  11470. var hull = function(points) {
  11471. if ((n = points.length) < 3) return null;
  11472. var i,
  11473. n,
  11474. sortedPoints = new Array(n),
  11475. flippedPoints = new Array(n);
  11476. for (i = 0; i < n; ++i) sortedPoints[i] = [+points[i][0], +points[i][1], i];
  11477. sortedPoints.sort(lexicographicOrder);
  11478. for (i = 0; i < n; ++i) flippedPoints[i] = [sortedPoints[i][0], -sortedPoints[i][1]];
  11479. var upperIndexes = computeUpperHullIndexes(sortedPoints),
  11480. lowerIndexes = computeUpperHullIndexes(flippedPoints);
  11481. // Construct the hull polygon, removing possible duplicate endpoints.
  11482. var skipLeft = lowerIndexes[0] === upperIndexes[0],
  11483. skipRight = lowerIndexes[lowerIndexes.length - 1] === upperIndexes[upperIndexes.length - 1],
  11484. hull = [];
  11485. // Add upper hull in right-to-l order.
  11486. // Then add lower hull in left-to-right order.
  11487. for (i = upperIndexes.length - 1; i >= 0; --i) hull.push(points[sortedPoints[upperIndexes[i]][2]]);
  11488. for (i = +skipLeft; i < lowerIndexes.length - skipRight; ++i) hull.push(points[sortedPoints[lowerIndexes[i]][2]]);
  11489. return hull;
  11490. };
  11491. var contains = function(polygon, point) {
  11492. var n = polygon.length,
  11493. p = polygon[n - 1],
  11494. x = point[0], y = point[1],
  11495. x0 = p[0], y0 = p[1],
  11496. x1, y1,
  11497. inside = false;
  11498. for (var i = 0; i < n; ++i) {
  11499. p = polygon[i], x1 = p[0], y1 = p[1];
  11500. if (((y1 > y) !== (y0 > y)) && (x < (x0 - x1) * (y - y1) / (y0 - y1) + x1)) inside = !inside;
  11501. x0 = x1, y0 = y1;
  11502. }
  11503. return inside;
  11504. };
  11505. var length = function(polygon) {
  11506. var i = -1,
  11507. n = polygon.length,
  11508. b = polygon[n - 1],
  11509. xa,
  11510. ya,
  11511. xb = b[0],
  11512. yb = b[1],
  11513. perimeter = 0;
  11514. while (++i < n) {
  11515. xa = xb;
  11516. ya = yb;
  11517. b = polygon[i];
  11518. xb = b[0];
  11519. yb = b[1];
  11520. xa -= xb;
  11521. ya -= yb;
  11522. perimeter += Math.sqrt(xa * xa + ya * ya);
  11523. }
  11524. return perimeter;
  11525. };
  11526. exports.polygonArea = area;
  11527. exports.polygonCentroid = centroid;
  11528. exports.polygonHull = hull;
  11529. exports.polygonContains = contains;
  11530. exports.polygonLength = length;
  11531. Object.defineProperty(exports, '__esModule', { value: true });
  11532. })));
  11533. },{}],56:[function(require,module,exports){
  11534. // https://d3js.org/d3-quadtree/ Version 1.0.3. Copyright 2017 Mike Bostock.
  11535. (function (global, factory) {
  11536. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  11537. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  11538. (factory((global.d3 = global.d3 || {})));
  11539. }(this, (function (exports) { 'use strict';
  11540. var tree_add = function(d) {
  11541. var x = +this._x.call(null, d),
  11542. y = +this._y.call(null, d);
  11543. return add(this.cover(x, y), x, y, d);
  11544. };
  11545. function add(tree, x, y, d) {
  11546. if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points
  11547. var parent,
  11548. node = tree._root,
  11549. leaf = {data: d},
  11550. x0 = tree._x0,
  11551. y0 = tree._y0,
  11552. x1 = tree._x1,
  11553. y1 = tree._y1,
  11554. xm,
  11555. ym,
  11556. xp,
  11557. yp,
  11558. right,
  11559. bottom,
  11560. i,
  11561. j;
  11562. // If the tree is empty, initialize the root as a leaf.
  11563. if (!node) return tree._root = leaf, tree;
  11564. // Find the existing leaf for the new point, or add it.
  11565. while (node.length) {
  11566. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  11567. if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  11568. if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree;
  11569. }
  11570. // Is the new point is exactly coincident with the existing point?
  11571. xp = +tree._x.call(null, node.data);
  11572. yp = +tree._y.call(null, node.data);
  11573. if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;
  11574. // Otherwise, split the leaf node until the old and new point are separated.
  11575. do {
  11576. parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4);
  11577. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  11578. if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  11579. } while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm)));
  11580. return parent[j] = node, parent[i] = leaf, tree;
  11581. }
  11582. function addAll(data) {
  11583. var d, i, n = data.length,
  11584. x,
  11585. y,
  11586. xz = new Array(n),
  11587. yz = new Array(n),
  11588. x0 = Infinity,
  11589. y0 = Infinity,
  11590. x1 = -Infinity,
  11591. y1 = -Infinity;
  11592. // Compute the points and their extent.
  11593. for (i = 0; i < n; ++i) {
  11594. if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue;
  11595. xz[i] = x;
  11596. yz[i] = y;
  11597. if (x < x0) x0 = x;
  11598. if (x > x1) x1 = x;
  11599. if (y < y0) y0 = y;
  11600. if (y > y1) y1 = y;
  11601. }
  11602. // If there were no (valid) points, inherit the existing extent.
  11603. if (x1 < x0) x0 = this._x0, x1 = this._x1;
  11604. if (y1 < y0) y0 = this._y0, y1 = this._y1;
  11605. // Expand the tree to cover the new points.
  11606. this.cover(x0, y0).cover(x1, y1);
  11607. // Add the new points.
  11608. for (i = 0; i < n; ++i) {
  11609. add(this, xz[i], yz[i], data[i]);
  11610. }
  11611. return this;
  11612. }
  11613. var tree_cover = function(x, y) {
  11614. if (isNaN(x = +x) || isNaN(y = +y)) return this; // ignore invalid points
  11615. var x0 = this._x0,
  11616. y0 = this._y0,
  11617. x1 = this._x1,
  11618. y1 = this._y1;
  11619. // If the quadtree has no extent, initialize them.
  11620. // Integer extent are necessary so that if we later double the extent,
  11621. // the existing quadrant boundaries don’t change due to floating point error!
  11622. if (isNaN(x0)) {
  11623. x1 = (x0 = Math.floor(x)) + 1;
  11624. y1 = (y0 = Math.floor(y)) + 1;
  11625. }
  11626. // Otherwise, double repeatedly to cover.
  11627. else if (x0 > x || x > x1 || y0 > y || y > y1) {
  11628. var z = x1 - x0,
  11629. node = this._root,
  11630. parent,
  11631. i;
  11632. switch (i = (y < (y0 + y1) / 2) << 1 | (x < (x0 + x1) / 2)) {
  11633. case 0: {
  11634. do parent = new Array(4), parent[i] = node, node = parent;
  11635. while (z *= 2, x1 = x0 + z, y1 = y0 + z, x > x1 || y > y1);
  11636. break;
  11637. }
  11638. case 1: {
  11639. do parent = new Array(4), parent[i] = node, node = parent;
  11640. while (z *= 2, x0 = x1 - z, y1 = y0 + z, x0 > x || y > y1);
  11641. break;
  11642. }
  11643. case 2: {
  11644. do parent = new Array(4), parent[i] = node, node = parent;
  11645. while (z *= 2, x1 = x0 + z, y0 = y1 - z, x > x1 || y0 > y);
  11646. break;
  11647. }
  11648. case 3: {
  11649. do parent = new Array(4), parent[i] = node, node = parent;
  11650. while (z *= 2, x0 = x1 - z, y0 = y1 - z, x0 > x || y0 > y);
  11651. break;
  11652. }
  11653. }
  11654. if (this._root && this._root.length) this._root = node;
  11655. }
  11656. // If the quadtree covers the point already, just return.
  11657. else return this;
  11658. this._x0 = x0;
  11659. this._y0 = y0;
  11660. this._x1 = x1;
  11661. this._y1 = y1;
  11662. return this;
  11663. };
  11664. var tree_data = function() {
  11665. var data = [];
  11666. this.visit(function(node) {
  11667. if (!node.length) do data.push(node.data); while (node = node.next)
  11668. });
  11669. return data;
  11670. };
  11671. var tree_extent = function(_) {
  11672. return arguments.length
  11673. ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1])
  11674. : isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]];
  11675. };
  11676. var Quad = function(node, x0, y0, x1, y1) {
  11677. this.node = node;
  11678. this.x0 = x0;
  11679. this.y0 = y0;
  11680. this.x1 = x1;
  11681. this.y1 = y1;
  11682. };
  11683. var tree_find = function(x, y, radius) {
  11684. var data,
  11685. x0 = this._x0,
  11686. y0 = this._y0,
  11687. x1,
  11688. y1,
  11689. x2,
  11690. y2,
  11691. x3 = this._x1,
  11692. y3 = this._y1,
  11693. quads = [],
  11694. node = this._root,
  11695. q,
  11696. i;
  11697. if (node) quads.push(new Quad(node, x0, y0, x3, y3));
  11698. if (radius == null) radius = Infinity;
  11699. else {
  11700. x0 = x - radius, y0 = y - radius;
  11701. x3 = x + radius, y3 = y + radius;
  11702. radius *= radius;
  11703. }
  11704. while (q = quads.pop()) {
  11705. // Stop searching if this quadrant can’t contain a closer node.
  11706. if (!(node = q.node)
  11707. || (x1 = q.x0) > x3
  11708. || (y1 = q.y0) > y3
  11709. || (x2 = q.x1) < x0
  11710. || (y2 = q.y1) < y0) continue;
  11711. // Bisect the current quadrant.
  11712. if (node.length) {
  11713. var xm = (x1 + x2) / 2,
  11714. ym = (y1 + y2) / 2;
  11715. quads.push(
  11716. new Quad(node[3], xm, ym, x2, y2),
  11717. new Quad(node[2], x1, ym, xm, y2),
  11718. new Quad(node[1], xm, y1, x2, ym),
  11719. new Quad(node[0], x1, y1, xm, ym)
  11720. );
  11721. // Visit the closest quadrant first.
  11722. if (i = (y >= ym) << 1 | (x >= xm)) {
  11723. q = quads[quads.length - 1];
  11724. quads[quads.length - 1] = quads[quads.length - 1 - i];
  11725. quads[quads.length - 1 - i] = q;
  11726. }
  11727. }
  11728. // Visit this point. (Visiting coincident points isn’t necessary!)
  11729. else {
  11730. var dx = x - +this._x.call(null, node.data),
  11731. dy = y - +this._y.call(null, node.data),
  11732. d2 = dx * dx + dy * dy;
  11733. if (d2 < radius) {
  11734. var d = Math.sqrt(radius = d2);
  11735. x0 = x - d, y0 = y - d;
  11736. x3 = x + d, y3 = y + d;
  11737. data = node.data;
  11738. }
  11739. }
  11740. }
  11741. return data;
  11742. };
  11743. var tree_remove = function(d) {
  11744. if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points
  11745. var parent,
  11746. node = this._root,
  11747. retainer,
  11748. previous,
  11749. next,
  11750. x0 = this._x0,
  11751. y0 = this._y0,
  11752. x1 = this._x1,
  11753. y1 = this._y1,
  11754. x,
  11755. y,
  11756. xm,
  11757. ym,
  11758. right,
  11759. bottom,
  11760. i,
  11761. j;
  11762. // If the tree is empty, initialize the root as a leaf.
  11763. if (!node) return this;
  11764. // Find the leaf node for the point.
  11765. // While descending, also retain the deepest parent with a non-removed sibling.
  11766. if (node.length) while (true) {
  11767. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  11768. if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  11769. if (!(parent = node, node = node[i = bottom << 1 | right])) return this;
  11770. if (!node.length) break;
  11771. if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) retainer = parent, j = i;
  11772. }
  11773. // Find the point to remove.
  11774. while (node.data !== d) if (!(previous = node, node = node.next)) return this;
  11775. if (next = node.next) delete node.next;
  11776. // If there are multiple coincident points, remove just the point.
  11777. if (previous) return (next ? previous.next = next : delete previous.next), this;
  11778. // If this is the root point, remove it.
  11779. if (!parent) return this._root = next, this;
  11780. // Remove this leaf.
  11781. next ? parent[i] = next : delete parent[i];
  11782. // If the parent now contains exactly one leaf, collapse superfluous parents.
  11783. if ((node = parent[0] || parent[1] || parent[2] || parent[3])
  11784. && node === (parent[3] || parent[2] || parent[1] || parent[0])
  11785. && !node.length) {
  11786. if (retainer) retainer[j] = node;
  11787. else this._root = node;
  11788. }
  11789. return this;
  11790. };
  11791. function removeAll(data) {
  11792. for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
  11793. return this;
  11794. }
  11795. var tree_root = function() {
  11796. return this._root;
  11797. };
  11798. var tree_size = function() {
  11799. var size = 0;
  11800. this.visit(function(node) {
  11801. if (!node.length) do ++size; while (node = node.next)
  11802. });
  11803. return size;
  11804. };
  11805. var tree_visit = function(callback) {
  11806. var quads = [], q, node = this._root, child, x0, y0, x1, y1;
  11807. if (node) quads.push(new Quad(node, this._x0, this._y0, this._x1, this._y1));
  11808. while (q = quads.pop()) {
  11809. if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
  11810. var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
  11811. if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
  11812. if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
  11813. if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
  11814. if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
  11815. }
  11816. }
  11817. return this;
  11818. };
  11819. var tree_visitAfter = function(callback) {
  11820. var quads = [], next = [], q;
  11821. if (this._root) quads.push(new Quad(this._root, this._x0, this._y0, this._x1, this._y1));
  11822. while (q = quads.pop()) {
  11823. var node = q.node;
  11824. if (node.length) {
  11825. var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
  11826. if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
  11827. if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
  11828. if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
  11829. if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
  11830. }
  11831. next.push(q);
  11832. }
  11833. while (q = next.pop()) {
  11834. callback(q.node, q.x0, q.y0, q.x1, q.y1);
  11835. }
  11836. return this;
  11837. };
  11838. function defaultX(d) {
  11839. return d[0];
  11840. }
  11841. var tree_x = function(_) {
  11842. return arguments.length ? (this._x = _, this) : this._x;
  11843. };
  11844. function defaultY(d) {
  11845. return d[1];
  11846. }
  11847. var tree_y = function(_) {
  11848. return arguments.length ? (this._y = _, this) : this._y;
  11849. };
  11850. function quadtree(nodes, x, y) {
  11851. var tree = new Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN);
  11852. return nodes == null ? tree : tree.addAll(nodes);
  11853. }
  11854. function Quadtree(x, y, x0, y0, x1, y1) {
  11855. this._x = x;
  11856. this._y = y;
  11857. this._x0 = x0;
  11858. this._y0 = y0;
  11859. this._x1 = x1;
  11860. this._y1 = y1;
  11861. this._root = undefined;
  11862. }
  11863. function leaf_copy(leaf) {
  11864. var copy = {data: leaf.data}, next = copy;
  11865. while (leaf = leaf.next) next = next.next = {data: leaf.data};
  11866. return copy;
  11867. }
  11868. var treeProto = quadtree.prototype = Quadtree.prototype;
  11869. treeProto.copy = function() {
  11870. var copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1),
  11871. node = this._root,
  11872. nodes,
  11873. child;
  11874. if (!node) return copy;
  11875. if (!node.length) return copy._root = leaf_copy(node), copy;
  11876. nodes = [{source: node, target: copy._root = new Array(4)}];
  11877. while (node = nodes.pop()) {
  11878. for (var i = 0; i < 4; ++i) {
  11879. if (child = node.source[i]) {
  11880. if (child.length) nodes.push({source: child, target: node.target[i] = new Array(4)});
  11881. else node.target[i] = leaf_copy(child);
  11882. }
  11883. }
  11884. }
  11885. return copy;
  11886. };
  11887. treeProto.add = tree_add;
  11888. treeProto.addAll = addAll;
  11889. treeProto.cover = tree_cover;
  11890. treeProto.data = tree_data;
  11891. treeProto.extent = tree_extent;
  11892. treeProto.find = tree_find;
  11893. treeProto.remove = tree_remove;
  11894. treeProto.removeAll = removeAll;
  11895. treeProto.root = tree_root;
  11896. treeProto.size = tree_size;
  11897. treeProto.visit = tree_visit;
  11898. treeProto.visitAfter = tree_visitAfter;
  11899. treeProto.x = tree_x;
  11900. treeProto.y = tree_y;
  11901. exports.quadtree = quadtree;
  11902. Object.defineProperty(exports, '__esModule', { value: true });
  11903. })));
  11904. },{}],57:[function(require,module,exports){
  11905. // https://d3js.org/d3-queue/ Version 3.0.7. Copyright 2017 Mike Bostock.
  11906. (function (global, factory) {
  11907. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  11908. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  11909. (factory((global.d3 = global.d3 || {})));
  11910. }(this, (function (exports) { 'use strict';
  11911. var slice = [].slice;
  11912. var noabort = {};
  11913. function Queue(size) {
  11914. this._size = size;
  11915. this._call =
  11916. this._error = null;
  11917. this._tasks = [];
  11918. this._data = [];
  11919. this._waiting =
  11920. this._active =
  11921. this._ended =
  11922. this._start = 0; // inside a synchronous task callback?
  11923. }
  11924. Queue.prototype = queue.prototype = {
  11925. constructor: Queue,
  11926. defer: function(callback) {
  11927. if (typeof callback !== "function") throw new Error("invalid callback");
  11928. if (this._call) throw new Error("defer after await");
  11929. if (this._error != null) return this;
  11930. var t = slice.call(arguments, 1);
  11931. t.push(callback);
  11932. ++this._waiting, this._tasks.push(t);
  11933. poke(this);
  11934. return this;
  11935. },
  11936. abort: function() {
  11937. if (this._error == null) abort(this, new Error("abort"));
  11938. return this;
  11939. },
  11940. await: function(callback) {
  11941. if (typeof callback !== "function") throw new Error("invalid callback");
  11942. if (this._call) throw new Error("multiple await");
  11943. this._call = function(error, results) { callback.apply(null, [error].concat(results)); };
  11944. maybeNotify(this);
  11945. return this;
  11946. },
  11947. awaitAll: function(callback) {
  11948. if (typeof callback !== "function") throw new Error("invalid callback");
  11949. if (this._call) throw new Error("multiple await");
  11950. this._call = callback;
  11951. maybeNotify(this);
  11952. return this;
  11953. }
  11954. };
  11955. function poke(q) {
  11956. if (!q._start) {
  11957. try { start(q); } // let the current task complete
  11958. catch (e) {
  11959. if (q._tasks[q._ended + q._active - 1]) abort(q, e); // task errored synchronously
  11960. else if (!q._data) throw e; // await callback errored synchronously
  11961. }
  11962. }
  11963. }
  11964. function start(q) {
  11965. while (q._start = q._waiting && q._active < q._size) {
  11966. var i = q._ended + q._active,
  11967. t = q._tasks[i],
  11968. j = t.length - 1,
  11969. c = t[j];
  11970. t[j] = end(q, i);
  11971. --q._waiting, ++q._active;
  11972. t = c.apply(null, t);
  11973. if (!q._tasks[i]) continue; // task finished synchronously
  11974. q._tasks[i] = t || noabort;
  11975. }
  11976. }
  11977. function end(q, i) {
  11978. return function(e, r) {
  11979. if (!q._tasks[i]) return; // ignore multiple callbacks
  11980. --q._active, ++q._ended;
  11981. q._tasks[i] = null;
  11982. if (q._error != null) return; // ignore secondary errors
  11983. if (e != null) {
  11984. abort(q, e);
  11985. } else {
  11986. q._data[i] = r;
  11987. if (q._waiting) poke(q);
  11988. else maybeNotify(q);
  11989. }
  11990. };
  11991. }
  11992. function abort(q, e) {
  11993. var i = q._tasks.length, t;
  11994. q._error = e; // ignore active callbacks
  11995. q._data = undefined; // allow gc
  11996. q._waiting = NaN; // prevent starting
  11997. while (--i >= 0) {
  11998. if (t = q._tasks[i]) {
  11999. q._tasks[i] = null;
  12000. if (t.abort) {
  12001. try { t.abort(); }
  12002. catch (e) { /* ignore */ }
  12003. }
  12004. }
  12005. }
  12006. q._active = NaN; // allow notification
  12007. maybeNotify(q);
  12008. }
  12009. function maybeNotify(q) {
  12010. if (!q._active && q._call) {
  12011. var d = q._data;
  12012. q._data = undefined; // allow gc
  12013. q._call(q._error, d);
  12014. }
  12015. }
  12016. function queue(concurrency) {
  12017. if (concurrency == null) concurrency = Infinity;
  12018. else if (!((concurrency = +concurrency) >= 1)) throw new Error("invalid concurrency");
  12019. return new Queue(concurrency);
  12020. }
  12021. exports.queue = queue;
  12022. Object.defineProperty(exports, '__esModule', { value: true });
  12023. })));
  12024. },{}],58:[function(require,module,exports){
  12025. // https://d3js.org/d3-random/ Version 1.1.0. Copyright 2017 Mike Bostock.
  12026. (function (global, factory) {
  12027. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  12028. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  12029. (factory((global.d3 = global.d3 || {})));
  12030. }(this, (function (exports) { 'use strict';
  12031. var defaultSource = function() {
  12032. return Math.random();
  12033. };
  12034. var uniform = ((function sourceRandomUniform(source) {
  12035. function randomUniform(min, max) {
  12036. min = min == null ? 0 : +min;
  12037. max = max == null ? 1 : +max;
  12038. if (arguments.length === 1) max = min, min = 0;
  12039. else max -= min;
  12040. return function() {
  12041. return source() * max + min;
  12042. };
  12043. }
  12044. randomUniform.source = sourceRandomUniform;
  12045. return randomUniform;
  12046. }))(defaultSource);
  12047. var normal = ((function sourceRandomNormal(source) {
  12048. function randomNormal(mu, sigma) {
  12049. var x, r;
  12050. mu = mu == null ? 0 : +mu;
  12051. sigma = sigma == null ? 1 : +sigma;
  12052. return function() {
  12053. var y;
  12054. // If available, use the second previously-generated uniform random.
  12055. if (x != null) y = x, x = null;
  12056. // Otherwise, generate a new x and y.
  12057. else do {
  12058. x = source() * 2 - 1;
  12059. y = source() * 2 - 1;
  12060. r = x * x + y * y;
  12061. } while (!r || r > 1);
  12062. return mu + sigma * y * Math.sqrt(-2 * Math.log(r) / r);
  12063. };
  12064. }
  12065. randomNormal.source = sourceRandomNormal;
  12066. return randomNormal;
  12067. }))(defaultSource);
  12068. var logNormal = ((function sourceRandomLogNormal(source) {
  12069. function randomLogNormal() {
  12070. var randomNormal = normal.source(source).apply(this, arguments);
  12071. return function() {
  12072. return Math.exp(randomNormal());
  12073. };
  12074. }
  12075. randomLogNormal.source = sourceRandomLogNormal;
  12076. return randomLogNormal;
  12077. }))(defaultSource);
  12078. var irwinHall = ((function sourceRandomIrwinHall(source) {
  12079. function randomIrwinHall(n) {
  12080. return function() {
  12081. for (var sum = 0, i = 0; i < n; ++i) sum += source();
  12082. return sum;
  12083. };
  12084. }
  12085. randomIrwinHall.source = sourceRandomIrwinHall;
  12086. return randomIrwinHall;
  12087. }))(defaultSource);
  12088. var bates = ((function sourceRandomBates(source) {
  12089. function randomBates(n) {
  12090. var randomIrwinHall = irwinHall.source(source)(n);
  12091. return function() {
  12092. return randomIrwinHall() / n;
  12093. };
  12094. }
  12095. randomBates.source = sourceRandomBates;
  12096. return randomBates;
  12097. }))(defaultSource);
  12098. var exponential = ((function sourceRandomExponential(source) {
  12099. function randomExponential(lambda) {
  12100. return function() {
  12101. return -Math.log(1 - source()) / lambda;
  12102. };
  12103. }
  12104. randomExponential.source = sourceRandomExponential;
  12105. return randomExponential;
  12106. }))(defaultSource);
  12107. exports.randomUniform = uniform;
  12108. exports.randomNormal = normal;
  12109. exports.randomLogNormal = logNormal;
  12110. exports.randomBates = bates;
  12111. exports.randomIrwinHall = irwinHall;
  12112. exports.randomExponential = exponential;
  12113. Object.defineProperty(exports, '__esModule', { value: true });
  12114. })));
  12115. },{}],59:[function(require,module,exports){
  12116. 'use strict';
  12117. var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
  12118. Object.defineProperty(exports, '__esModule', { value: true });
  12119. var d3Collection = require('d3-collection');
  12120. var d3Dispatch = require('d3-dispatch');
  12121. var d3Dsv = require('d3-dsv');
  12122. var request = function(url, callback) {
  12123. var request,
  12124. event = d3Dispatch.dispatch("beforesend", "progress", "load", "error"),
  12125. mimeType,
  12126. headers = d3Collection.map(),
  12127. xhr = new XMLHttpRequest,
  12128. user = null,
  12129. password = null,
  12130. response,
  12131. responseType,
  12132. timeout = 0;
  12133. // If IE does not support CORS, use XDomainRequest.
  12134. if (typeof XDomainRequest !== "undefined"
  12135. && !("withCredentials" in xhr)
  12136. && /^(http(s)?:)?\/\//.test(url)) xhr = new XDomainRequest;
  12137. "onload" in xhr
  12138. ? xhr.onload = xhr.onerror = xhr.ontimeout = respond
  12139. : xhr.onreadystatechange = function(o) { xhr.readyState > 3 && respond(o); };
  12140. function respond(o) {
  12141. var status = xhr.status, result;
  12142. if (!status && hasResponse(xhr)
  12143. || status >= 200 && status < 300
  12144. || status === 304) {
  12145. if (response) {
  12146. try {
  12147. result = response.call(request, xhr);
  12148. } catch (e) {
  12149. event.call("error", request, e);
  12150. return;
  12151. }
  12152. } else {
  12153. result = xhr;
  12154. }
  12155. event.call("load", request, result);
  12156. } else {
  12157. event.call("error", request, o);
  12158. }
  12159. }
  12160. xhr.onprogress = function(e) {
  12161. event.call("progress", request, e);
  12162. };
  12163. request = {
  12164. header: function(name, value) {
  12165. name = (name + "").toLowerCase();
  12166. if (arguments.length < 2) return headers.get(name);
  12167. if (value == null) headers.remove(name);
  12168. else headers.set(name, value + "");
  12169. return request;
  12170. },
  12171. // If mimeType is non-null and no Accept header is set, a default is used.
  12172. mimeType: function(value) {
  12173. if (!arguments.length) return mimeType;
  12174. mimeType = value == null ? null : value + "";
  12175. return request;
  12176. },
  12177. // Specifies what type the response value should take;
  12178. // for instance, arraybuffer, blob, document, or text.
  12179. responseType: function(value) {
  12180. if (!arguments.length) return responseType;
  12181. responseType = value;
  12182. return request;
  12183. },
  12184. timeout: function(value) {
  12185. if (!arguments.length) return timeout;
  12186. timeout = +value;
  12187. return request;
  12188. },
  12189. user: function(value) {
  12190. return arguments.length < 1 ? user : (user = value == null ? null : value + "", request);
  12191. },
  12192. password: function(value) {
  12193. return arguments.length < 1 ? password : (password = value == null ? null : value + "", request);
  12194. },
  12195. // Specify how to convert the response content to a specific type;
  12196. // changes the callback value on "load" events.
  12197. response: function(value) {
  12198. response = value;
  12199. return request;
  12200. },
  12201. // Alias for send("GET", …).
  12202. get: function(data, callback) {
  12203. return request.send("GET", data, callback);
  12204. },
  12205. // Alias for send("POST", …).
  12206. post: function(data, callback) {
  12207. return request.send("POST", data, callback);
  12208. },
  12209. // If callback is non-null, it will be used for error and load events.
  12210. send: function(method, data, callback) {
  12211. xhr.open(method, url, true, user, password);
  12212. if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*");
  12213. if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); });
  12214. if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType);
  12215. if (responseType != null) xhr.responseType = responseType;
  12216. if (timeout > 0) xhr.timeout = timeout;
  12217. if (callback == null && typeof data === "function") callback = data, data = null;
  12218. if (callback != null && callback.length === 1) callback = fixCallback(callback);
  12219. if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); });
  12220. event.call("beforesend", request, xhr);
  12221. xhr.send(data == null ? null : data);
  12222. return request;
  12223. },
  12224. abort: function() {
  12225. xhr.abort();
  12226. return request;
  12227. },
  12228. on: function() {
  12229. var value = event.on.apply(event, arguments);
  12230. return value === event ? request : value;
  12231. }
  12232. };
  12233. if (callback != null) {
  12234. if (typeof callback !== "function") throw new Error("invalid callback: " + callback);
  12235. return request.get(callback);
  12236. }
  12237. return request;
  12238. };
  12239. function fixCallback(callback) {
  12240. return function(error, xhr) {
  12241. callback(error == null ? xhr : null);
  12242. };
  12243. }
  12244. function hasResponse(xhr) {
  12245. var type = xhr.responseType;
  12246. return type && type !== "text"
  12247. ? xhr.response // null on error
  12248. : xhr.responseText; // "" on error
  12249. }
  12250. var type = function(defaultMimeType, response) {
  12251. return function(url, callback) {
  12252. var r = request(url).mimeType(defaultMimeType).response(response);
  12253. if (callback != null) {
  12254. if (typeof callback !== "function") throw new Error("invalid callback: " + callback);
  12255. return r.get(callback);
  12256. }
  12257. return r;
  12258. };
  12259. };
  12260. var html = type("text/html", function(xhr) {
  12261. return document.createRange().createContextualFragment(xhr.responseText);
  12262. });
  12263. var json = type("application/json", function(xhr) {
  12264. return JSON.parse(xhr.responseText);
  12265. });
  12266. var text = type("text/plain", function(xhr) {
  12267. return xhr.responseText;
  12268. });
  12269. var xml = type("application/xml", function(xhr) {
  12270. var xml = xhr.responseXML;
  12271. if (!xml) throw new Error("parse error");
  12272. return xml;
  12273. });
  12274. var dsv = function(defaultMimeType, parse) {
  12275. return function(url, row, callback) {
  12276. if (arguments.length < 3) callback = row, row = null;
  12277. var r = request(url).mimeType(defaultMimeType);
  12278. r.row = function(_) { return arguments.length ? r.response(responseOf(parse, row = _)) : row; };
  12279. r.row(row);
  12280. return callback ? r.get(callback) : r;
  12281. };
  12282. };
  12283. function responseOf(parse, row) {
  12284. return function(request$$1) {
  12285. return parse(request$$1.responseText, row);
  12286. };
  12287. }
  12288. var csv = dsv("text/csv", d3Dsv.csvParse);
  12289. var tsv = dsv("text/tab-separated-values", d3Dsv.tsvParse);
  12290. exports.request = request;
  12291. exports.html = html;
  12292. exports.json = json;
  12293. exports.text = text;
  12294. exports.xml = xml;
  12295. exports.csv = csv;
  12296. exports.tsv = tsv;
  12297. },{"d3-collection":43,"d3-dispatch":45,"d3-dsv":47,"xmlhttprequest":148}],60:[function(require,module,exports){
  12298. // https://d3js.org/d3-scale/ Version 1.0.7. Copyright 2017 Mike Bostock.
  12299. (function (global, factory) {
  12300. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-array'), require('d3-collection'), require('d3-interpolate'), require('d3-format'), require('d3-time'), require('d3-time-format'), require('d3-color')) :
  12301. typeof define === 'function' && define.amd ? define(['exports', 'd3-array', 'd3-collection', 'd3-interpolate', 'd3-format', 'd3-time', 'd3-time-format', 'd3-color'], factory) :
  12302. (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3));
  12303. }(this, (function (exports,d3Array,d3Collection,d3Interpolate,d3Format,d3Time,d3TimeFormat,d3Color) { 'use strict';
  12304. var array = Array.prototype;
  12305. var map$1 = array.map;
  12306. var slice = array.slice;
  12307. var implicit = {name: "implicit"};
  12308. function ordinal(range$$1) {
  12309. var index = d3Collection.map(),
  12310. domain = [],
  12311. unknown = implicit;
  12312. range$$1 = range$$1 == null ? [] : slice.call(range$$1);
  12313. function scale(d) {
  12314. var key = d + "", i = index.get(key);
  12315. if (!i) {
  12316. if (unknown !== implicit) return unknown;
  12317. index.set(key, i = domain.push(d));
  12318. }
  12319. return range$$1[(i - 1) % range$$1.length];
  12320. }
  12321. scale.domain = function(_) {
  12322. if (!arguments.length) return domain.slice();
  12323. domain = [], index = d3Collection.map();
  12324. var i = -1, n = _.length, d, key;
  12325. while (++i < n) if (!index.has(key = (d = _[i]) + "")) index.set(key, domain.push(d));
  12326. return scale;
  12327. };
  12328. scale.range = function(_) {
  12329. return arguments.length ? (range$$1 = slice.call(_), scale) : range$$1.slice();
  12330. };
  12331. scale.unknown = function(_) {
  12332. return arguments.length ? (unknown = _, scale) : unknown;
  12333. };
  12334. scale.copy = function() {
  12335. return ordinal()
  12336. .domain(domain)
  12337. .range(range$$1)
  12338. .unknown(unknown);
  12339. };
  12340. return scale;
  12341. }
  12342. function band() {
  12343. var scale = ordinal().unknown(undefined),
  12344. domain = scale.domain,
  12345. ordinalRange = scale.range,
  12346. range$$1 = [0, 1],
  12347. step,
  12348. bandwidth,
  12349. round = false,
  12350. paddingInner = 0,
  12351. paddingOuter = 0,
  12352. align = 0.5;
  12353. delete scale.unknown;
  12354. function rescale() {
  12355. var n = domain().length,
  12356. reverse = range$$1[1] < range$$1[0],
  12357. start = range$$1[reverse - 0],
  12358. stop = range$$1[1 - reverse];
  12359. step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
  12360. if (round) step = Math.floor(step);
  12361. start += (stop - start - step * (n - paddingInner)) * align;
  12362. bandwidth = step * (1 - paddingInner);
  12363. if (round) start = Math.round(start), bandwidth = Math.round(bandwidth);
  12364. var values = d3Array.range(n).map(function(i) { return start + step * i; });
  12365. return ordinalRange(reverse ? values.reverse() : values);
  12366. }
  12367. scale.domain = function(_) {
  12368. return arguments.length ? (domain(_), rescale()) : domain();
  12369. };
  12370. scale.range = function(_) {
  12371. return arguments.length ? (range$$1 = [+_[0], +_[1]], rescale()) : range$$1.slice();
  12372. };
  12373. scale.rangeRound = function(_) {
  12374. return range$$1 = [+_[0], +_[1]], round = true, rescale();
  12375. };
  12376. scale.bandwidth = function() {
  12377. return bandwidth;
  12378. };
  12379. scale.step = function() {
  12380. return step;
  12381. };
  12382. scale.round = function(_) {
  12383. return arguments.length ? (round = !!_, rescale()) : round;
  12384. };
  12385. scale.padding = function(_) {
  12386. return arguments.length ? (paddingInner = paddingOuter = Math.max(0, Math.min(1, _)), rescale()) : paddingInner;
  12387. };
  12388. scale.paddingInner = function(_) {
  12389. return arguments.length ? (paddingInner = Math.max(0, Math.min(1, _)), rescale()) : paddingInner;
  12390. };
  12391. scale.paddingOuter = function(_) {
  12392. return arguments.length ? (paddingOuter = Math.max(0, Math.min(1, _)), rescale()) : paddingOuter;
  12393. };
  12394. scale.align = function(_) {
  12395. return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;
  12396. };
  12397. scale.copy = function() {
  12398. return band()
  12399. .domain(domain())
  12400. .range(range$$1)
  12401. .round(round)
  12402. .paddingInner(paddingInner)
  12403. .paddingOuter(paddingOuter)
  12404. .align(align);
  12405. };
  12406. return rescale();
  12407. }
  12408. function pointish(scale) {
  12409. var copy = scale.copy;
  12410. scale.padding = scale.paddingOuter;
  12411. delete scale.paddingInner;
  12412. delete scale.paddingOuter;
  12413. scale.copy = function() {
  12414. return pointish(copy());
  12415. };
  12416. return scale;
  12417. }
  12418. function point() {
  12419. return pointish(band().paddingInner(1));
  12420. }
  12421. var constant = function(x) {
  12422. return function() {
  12423. return x;
  12424. };
  12425. };
  12426. var number = function(x) {
  12427. return +x;
  12428. };
  12429. var unit = [0, 1];
  12430. function deinterpolateLinear(a, b) {
  12431. return (b -= (a = +a))
  12432. ? function(x) { return (x - a) / b; }
  12433. : constant(b);
  12434. }
  12435. function deinterpolateClamp(deinterpolate) {
  12436. return function(a, b) {
  12437. var d = deinterpolate(a = +a, b = +b);
  12438. return function(x) { return x <= a ? 0 : x >= b ? 1 : d(x); };
  12439. };
  12440. }
  12441. function reinterpolateClamp(reinterpolate) {
  12442. return function(a, b) {
  12443. var r = reinterpolate(a = +a, b = +b);
  12444. return function(t) { return t <= 0 ? a : t >= 1 ? b : r(t); };
  12445. };
  12446. }
  12447. function bimap(domain, range$$1, deinterpolate, reinterpolate) {
  12448. var d0 = domain[0], d1 = domain[1], r0 = range$$1[0], r1 = range$$1[1];
  12449. if (d1 < d0) d0 = deinterpolate(d1, d0), r0 = reinterpolate(r1, r0);
  12450. else d0 = deinterpolate(d0, d1), r0 = reinterpolate(r0, r1);
  12451. return function(x) { return r0(d0(x)); };
  12452. }
  12453. function polymap(domain, range$$1, deinterpolate, reinterpolate) {
  12454. var j = Math.min(domain.length, range$$1.length) - 1,
  12455. d = new Array(j),
  12456. r = new Array(j),
  12457. i = -1;
  12458. // Reverse descending domains.
  12459. if (domain[j] < domain[0]) {
  12460. domain = domain.slice().reverse();
  12461. range$$1 = range$$1.slice().reverse();
  12462. }
  12463. while (++i < j) {
  12464. d[i] = deinterpolate(domain[i], domain[i + 1]);
  12465. r[i] = reinterpolate(range$$1[i], range$$1[i + 1]);
  12466. }
  12467. return function(x) {
  12468. var i = d3Array.bisect(domain, x, 1, j) - 1;
  12469. return r[i](d[i](x));
  12470. };
  12471. }
  12472. function copy(source, target) {
  12473. return target
  12474. .domain(source.domain())
  12475. .range(source.range())
  12476. .interpolate(source.interpolate())
  12477. .clamp(source.clamp());
  12478. }
  12479. // deinterpolate(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
  12480. // reinterpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding domain value x in [a,b].
  12481. function continuous(deinterpolate, reinterpolate) {
  12482. var domain = unit,
  12483. range$$1 = unit,
  12484. interpolate$$1 = d3Interpolate.interpolate,
  12485. clamp = false,
  12486. piecewise,
  12487. output,
  12488. input;
  12489. function rescale() {
  12490. piecewise = Math.min(domain.length, range$$1.length) > 2 ? polymap : bimap;
  12491. output = input = null;
  12492. return scale;
  12493. }
  12494. function scale(x) {
  12495. return (output || (output = piecewise(domain, range$$1, clamp ? deinterpolateClamp(deinterpolate) : deinterpolate, interpolate$$1)))(+x);
  12496. }
  12497. scale.invert = function(y) {
  12498. return (input || (input = piecewise(range$$1, domain, deinterpolateLinear, clamp ? reinterpolateClamp(reinterpolate) : reinterpolate)))(+y);
  12499. };
  12500. scale.domain = function(_) {
  12501. return arguments.length ? (domain = map$1.call(_, number), rescale()) : domain.slice();
  12502. };
  12503. scale.range = function(_) {
  12504. return arguments.length ? (range$$1 = slice.call(_), rescale()) : range$$1.slice();
  12505. };
  12506. scale.rangeRound = function(_) {
  12507. return range$$1 = slice.call(_), interpolate$$1 = d3Interpolate.interpolateRound, rescale();
  12508. };
  12509. scale.clamp = function(_) {
  12510. return arguments.length ? (clamp = !!_, rescale()) : clamp;
  12511. };
  12512. scale.interpolate = function(_) {
  12513. return arguments.length ? (interpolate$$1 = _, rescale()) : interpolate$$1;
  12514. };
  12515. return rescale();
  12516. }
  12517. var tickFormat = function(domain, count, specifier) {
  12518. var start = domain[0],
  12519. stop = domain[domain.length - 1],
  12520. step = d3Array.tickStep(start, stop, count == null ? 10 : count),
  12521. precision;
  12522. specifier = d3Format.formatSpecifier(specifier == null ? ",f" : specifier);
  12523. switch (specifier.type) {
  12524. case "s": {
  12525. var value = Math.max(Math.abs(start), Math.abs(stop));
  12526. if (specifier.precision == null && !isNaN(precision = d3Format.precisionPrefix(step, value))) specifier.precision = precision;
  12527. return d3Format.formatPrefix(specifier, value);
  12528. }
  12529. case "":
  12530. case "e":
  12531. case "g":
  12532. case "p":
  12533. case "r": {
  12534. if (specifier.precision == null && !isNaN(precision = d3Format.precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
  12535. break;
  12536. }
  12537. case "f":
  12538. case "%": {
  12539. if (specifier.precision == null && !isNaN(precision = d3Format.precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2;
  12540. break;
  12541. }
  12542. }
  12543. return d3Format.format(specifier);
  12544. };
  12545. function linearish(scale) {
  12546. var domain = scale.domain;
  12547. scale.ticks = function(count) {
  12548. var d = domain();
  12549. return d3Array.ticks(d[0], d[d.length - 1], count == null ? 10 : count);
  12550. };
  12551. scale.tickFormat = function(count, specifier) {
  12552. return tickFormat(domain(), count, specifier);
  12553. };
  12554. scale.nice = function(count) {
  12555. if (count == null) count = 10;
  12556. var d = domain(),
  12557. i0 = 0,
  12558. i1 = d.length - 1,
  12559. start = d[i0],
  12560. stop = d[i1],
  12561. step;
  12562. if (stop < start) {
  12563. step = start, start = stop, stop = step;
  12564. step = i0, i0 = i1, i1 = step;
  12565. }
  12566. step = d3Array.tickIncrement(start, stop, count);
  12567. if (step > 0) {
  12568. start = Math.floor(start / step) * step;
  12569. stop = Math.ceil(stop / step) * step;
  12570. step = d3Array.tickIncrement(start, stop, count);
  12571. } else if (step < 0) {
  12572. start = Math.ceil(start * step) / step;
  12573. stop = Math.floor(stop * step) / step;
  12574. step = d3Array.tickIncrement(start, stop, count);
  12575. }
  12576. if (step > 0) {
  12577. d[i0] = Math.floor(start / step) * step;
  12578. d[i1] = Math.ceil(stop / step) * step;
  12579. domain(d);
  12580. } else if (step < 0) {
  12581. d[i0] = Math.ceil(start * step) / step;
  12582. d[i1] = Math.floor(stop * step) / step;
  12583. domain(d);
  12584. }
  12585. return scale;
  12586. };
  12587. return scale;
  12588. }
  12589. function linear() {
  12590. var scale = continuous(deinterpolateLinear, d3Interpolate.interpolateNumber);
  12591. scale.copy = function() {
  12592. return copy(scale, linear());
  12593. };
  12594. return linearish(scale);
  12595. }
  12596. function identity() {
  12597. var domain = [0, 1];
  12598. function scale(x) {
  12599. return +x;
  12600. }
  12601. scale.invert = scale;
  12602. scale.domain = scale.range = function(_) {
  12603. return arguments.length ? (domain = map$1.call(_, number), scale) : domain.slice();
  12604. };
  12605. scale.copy = function() {
  12606. return identity().domain(domain);
  12607. };
  12608. return linearish(scale);
  12609. }
  12610. var nice = function(domain, interval) {
  12611. domain = domain.slice();
  12612. var i0 = 0,
  12613. i1 = domain.length - 1,
  12614. x0 = domain[i0],
  12615. x1 = domain[i1],
  12616. t;
  12617. if (x1 < x0) {
  12618. t = i0, i0 = i1, i1 = t;
  12619. t = x0, x0 = x1, x1 = t;
  12620. }
  12621. domain[i0] = interval.floor(x0);
  12622. domain[i1] = interval.ceil(x1);
  12623. return domain;
  12624. };
  12625. function deinterpolate(a, b) {
  12626. return (b = Math.log(b / a))
  12627. ? function(x) { return Math.log(x / a) / b; }
  12628. : constant(b);
  12629. }
  12630. function reinterpolate(a, b) {
  12631. return a < 0
  12632. ? function(t) { return -Math.pow(-b, t) * Math.pow(-a, 1 - t); }
  12633. : function(t) { return Math.pow(b, t) * Math.pow(a, 1 - t); };
  12634. }
  12635. function pow10(x) {
  12636. return isFinite(x) ? +("1e" + x) : x < 0 ? 0 : x;
  12637. }
  12638. function powp(base) {
  12639. return base === 10 ? pow10
  12640. : base === Math.E ? Math.exp
  12641. : function(x) { return Math.pow(base, x); };
  12642. }
  12643. function logp(base) {
  12644. return base === Math.E ? Math.log
  12645. : base === 10 && Math.log10
  12646. || base === 2 && Math.log2
  12647. || (base = Math.log(base), function(x) { return Math.log(x) / base; });
  12648. }
  12649. function reflect(f) {
  12650. return function(x) {
  12651. return -f(-x);
  12652. };
  12653. }
  12654. function log() {
  12655. var scale = continuous(deinterpolate, reinterpolate).domain([1, 10]),
  12656. domain = scale.domain,
  12657. base = 10,
  12658. logs = logp(10),
  12659. pows = powp(10);
  12660. function rescale() {
  12661. logs = logp(base), pows = powp(base);
  12662. if (domain()[0] < 0) logs = reflect(logs), pows = reflect(pows);
  12663. return scale;
  12664. }
  12665. scale.base = function(_) {
  12666. return arguments.length ? (base = +_, rescale()) : base;
  12667. };
  12668. scale.domain = function(_) {
  12669. return arguments.length ? (domain(_), rescale()) : domain();
  12670. };
  12671. scale.ticks = function(count) {
  12672. var d = domain(),
  12673. u = d[0],
  12674. v = d[d.length - 1],
  12675. r;
  12676. if (r = v < u) i = u, u = v, v = i;
  12677. var i = logs(u),
  12678. j = logs(v),
  12679. p,
  12680. k,
  12681. t,
  12682. n = count == null ? 10 : +count,
  12683. z = [];
  12684. if (!(base % 1) && j - i < n) {
  12685. i = Math.round(i) - 1, j = Math.round(j) + 1;
  12686. if (u > 0) for (; i < j; ++i) {
  12687. for (k = 1, p = pows(i); k < base; ++k) {
  12688. t = p * k;
  12689. if (t < u) continue;
  12690. if (t > v) break;
  12691. z.push(t);
  12692. }
  12693. } else for (; i < j; ++i) {
  12694. for (k = base - 1, p = pows(i); k >= 1; --k) {
  12695. t = p * k;
  12696. if (t < u) continue;
  12697. if (t > v) break;
  12698. z.push(t);
  12699. }
  12700. }
  12701. } else {
  12702. z = d3Array.ticks(i, j, Math.min(j - i, n)).map(pows);
  12703. }
  12704. return r ? z.reverse() : z;
  12705. };
  12706. scale.tickFormat = function(count, specifier) {
  12707. if (specifier == null) specifier = base === 10 ? ".0e" : ",";
  12708. if (typeof specifier !== "function") specifier = d3Format.format(specifier);
  12709. if (count === Infinity) return specifier;
  12710. if (count == null) count = 10;
  12711. var k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate?
  12712. return function(d) {
  12713. var i = d / pows(Math.round(logs(d)));
  12714. if (i * base < base - 0.5) i *= base;
  12715. return i <= k ? specifier(d) : "";
  12716. };
  12717. };
  12718. scale.nice = function() {
  12719. return domain(nice(domain(), {
  12720. floor: function(x) { return pows(Math.floor(logs(x))); },
  12721. ceil: function(x) { return pows(Math.ceil(logs(x))); }
  12722. }));
  12723. };
  12724. scale.copy = function() {
  12725. return copy(scale, log().base(base));
  12726. };
  12727. return scale;
  12728. }
  12729. function raise(x, exponent) {
  12730. return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
  12731. }
  12732. function pow() {
  12733. var exponent = 1,
  12734. scale = continuous(deinterpolate, reinterpolate),
  12735. domain = scale.domain;
  12736. function deinterpolate(a, b) {
  12737. return (b = raise(b, exponent) - (a = raise(a, exponent)))
  12738. ? function(x) { return (raise(x, exponent) - a) / b; }
  12739. : constant(b);
  12740. }
  12741. function reinterpolate(a, b) {
  12742. b = raise(b, exponent) - (a = raise(a, exponent));
  12743. return function(t) { return raise(a + b * t, 1 / exponent); };
  12744. }
  12745. scale.exponent = function(_) {
  12746. return arguments.length ? (exponent = +_, domain(domain())) : exponent;
  12747. };
  12748. scale.copy = function() {
  12749. return copy(scale, pow().exponent(exponent));
  12750. };
  12751. return linearish(scale);
  12752. }
  12753. function sqrt() {
  12754. return pow().exponent(0.5);
  12755. }
  12756. function quantile$1() {
  12757. var domain = [],
  12758. range$$1 = [],
  12759. thresholds = [];
  12760. function rescale() {
  12761. var i = 0, n = Math.max(1, range$$1.length);
  12762. thresholds = new Array(n - 1);
  12763. while (++i < n) thresholds[i - 1] = d3Array.quantile(domain, i / n);
  12764. return scale;
  12765. }
  12766. function scale(x) {
  12767. if (!isNaN(x = +x)) return range$$1[d3Array.bisect(thresholds, x)];
  12768. }
  12769. scale.invertExtent = function(y) {
  12770. var i = range$$1.indexOf(y);
  12771. return i < 0 ? [NaN, NaN] : [
  12772. i > 0 ? thresholds[i - 1] : domain[0],
  12773. i < thresholds.length ? thresholds[i] : domain[domain.length - 1]
  12774. ];
  12775. };
  12776. scale.domain = function(_) {
  12777. if (!arguments.length) return domain.slice();
  12778. domain = [];
  12779. for (var i = 0, n = _.length, d; i < n; ++i) if (d = _[i], d != null && !isNaN(d = +d)) domain.push(d);
  12780. domain.sort(d3Array.ascending);
  12781. return rescale();
  12782. };
  12783. scale.range = function(_) {
  12784. return arguments.length ? (range$$1 = slice.call(_), rescale()) : range$$1.slice();
  12785. };
  12786. scale.quantiles = function() {
  12787. return thresholds.slice();
  12788. };
  12789. scale.copy = function() {
  12790. return quantile$1()
  12791. .domain(domain)
  12792. .range(range$$1);
  12793. };
  12794. return scale;
  12795. }
  12796. function quantize() {
  12797. var x0 = 0,
  12798. x1 = 1,
  12799. n = 1,
  12800. domain = [0.5],
  12801. range$$1 = [0, 1];
  12802. function scale(x) {
  12803. if (x <= x) return range$$1[d3Array.bisect(domain, x, 0, n)];
  12804. }
  12805. function rescale() {
  12806. var i = -1;
  12807. domain = new Array(n);
  12808. while (++i < n) domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1);
  12809. return scale;
  12810. }
  12811. scale.domain = function(_) {
  12812. return arguments.length ? (x0 = +_[0], x1 = +_[1], rescale()) : [x0, x1];
  12813. };
  12814. scale.range = function(_) {
  12815. return arguments.length ? (n = (range$$1 = slice.call(_)).length - 1, rescale()) : range$$1.slice();
  12816. };
  12817. scale.invertExtent = function(y) {
  12818. var i = range$$1.indexOf(y);
  12819. return i < 0 ? [NaN, NaN]
  12820. : i < 1 ? [x0, domain[0]]
  12821. : i >= n ? [domain[n - 1], x1]
  12822. : [domain[i - 1], domain[i]];
  12823. };
  12824. scale.copy = function() {
  12825. return quantize()
  12826. .domain([x0, x1])
  12827. .range(range$$1);
  12828. };
  12829. return linearish(scale);
  12830. }
  12831. function threshold() {
  12832. var domain = [0.5],
  12833. range$$1 = [0, 1],
  12834. n = 1;
  12835. function scale(x) {
  12836. if (x <= x) return range$$1[d3Array.bisect(domain, x, 0, n)];
  12837. }
  12838. scale.domain = function(_) {
  12839. return arguments.length ? (domain = slice.call(_), n = Math.min(domain.length, range$$1.length - 1), scale) : domain.slice();
  12840. };
  12841. scale.range = function(_) {
  12842. return arguments.length ? (range$$1 = slice.call(_), n = Math.min(domain.length, range$$1.length - 1), scale) : range$$1.slice();
  12843. };
  12844. scale.invertExtent = function(y) {
  12845. var i = range$$1.indexOf(y);
  12846. return [domain[i - 1], domain[i]];
  12847. };
  12848. scale.copy = function() {
  12849. return threshold()
  12850. .domain(domain)
  12851. .range(range$$1);
  12852. };
  12853. return scale;
  12854. }
  12855. var durationSecond = 1000;
  12856. var durationMinute = durationSecond * 60;
  12857. var durationHour = durationMinute * 60;
  12858. var durationDay = durationHour * 24;
  12859. var durationWeek = durationDay * 7;
  12860. var durationMonth = durationDay * 30;
  12861. var durationYear = durationDay * 365;
  12862. function date(t) {
  12863. return new Date(t);
  12864. }
  12865. function number$1(t) {
  12866. return t instanceof Date ? +t : +new Date(+t);
  12867. }
  12868. function calendar(year, month, week, day, hour, minute, second, millisecond, format$$1) {
  12869. var scale = continuous(deinterpolateLinear, d3Interpolate.interpolateNumber),
  12870. invert = scale.invert,
  12871. domain = scale.domain;
  12872. var formatMillisecond = format$$1(".%L"),
  12873. formatSecond = format$$1(":%S"),
  12874. formatMinute = format$$1("%I:%M"),
  12875. formatHour = format$$1("%I %p"),
  12876. formatDay = format$$1("%a %d"),
  12877. formatWeek = format$$1("%b %d"),
  12878. formatMonth = format$$1("%B"),
  12879. formatYear = format$$1("%Y");
  12880. var tickIntervals = [
  12881. [second, 1, durationSecond],
  12882. [second, 5, 5 * durationSecond],
  12883. [second, 15, 15 * durationSecond],
  12884. [second, 30, 30 * durationSecond],
  12885. [minute, 1, durationMinute],
  12886. [minute, 5, 5 * durationMinute],
  12887. [minute, 15, 15 * durationMinute],
  12888. [minute, 30, 30 * durationMinute],
  12889. [ hour, 1, durationHour ],
  12890. [ hour, 3, 3 * durationHour ],
  12891. [ hour, 6, 6 * durationHour ],
  12892. [ hour, 12, 12 * durationHour ],
  12893. [ day, 1, durationDay ],
  12894. [ day, 2, 2 * durationDay ],
  12895. [ week, 1, durationWeek ],
  12896. [ month, 1, durationMonth ],
  12897. [ month, 3, 3 * durationMonth ],
  12898. [ year, 1, durationYear ]
  12899. ];
  12900. function tickFormat(date) {
  12901. return (second(date) < date ? formatMillisecond
  12902. : minute(date) < date ? formatSecond
  12903. : hour(date) < date ? formatMinute
  12904. : day(date) < date ? formatHour
  12905. : month(date) < date ? (week(date) < date ? formatDay : formatWeek)
  12906. : year(date) < date ? formatMonth
  12907. : formatYear)(date);
  12908. }
  12909. function tickInterval(interval, start, stop, step) {
  12910. if (interval == null) interval = 10;
  12911. // If a desired tick count is specified, pick a reasonable tick interval
  12912. // based on the extent of the domain and a rough estimate of tick size.
  12913. // Otherwise, assume interval is already a time interval and use it.
  12914. if (typeof interval === "number") {
  12915. var target = Math.abs(stop - start) / interval,
  12916. i = d3Array.bisector(function(i) { return i[2]; }).right(tickIntervals, target);
  12917. if (i === tickIntervals.length) {
  12918. step = d3Array.tickStep(start / durationYear, stop / durationYear, interval);
  12919. interval = year;
  12920. } else if (i) {
  12921. i = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];
  12922. step = i[1];
  12923. interval = i[0];
  12924. } else {
  12925. step = Math.max(d3Array.tickStep(start, stop, interval), 1);
  12926. interval = millisecond;
  12927. }
  12928. }
  12929. return step == null ? interval : interval.every(step);
  12930. }
  12931. scale.invert = function(y) {
  12932. return new Date(invert(y));
  12933. };
  12934. scale.domain = function(_) {
  12935. return arguments.length ? domain(map$1.call(_, number$1)) : domain().map(date);
  12936. };
  12937. scale.ticks = function(interval, step) {
  12938. var d = domain(),
  12939. t0 = d[0],
  12940. t1 = d[d.length - 1],
  12941. r = t1 < t0,
  12942. t;
  12943. if (r) t = t0, t0 = t1, t1 = t;
  12944. t = tickInterval(interval, t0, t1, step);
  12945. t = t ? t.range(t0, t1 + 1) : []; // inclusive stop
  12946. return r ? t.reverse() : t;
  12947. };
  12948. scale.tickFormat = function(count, specifier) {
  12949. return specifier == null ? tickFormat : format$$1(specifier);
  12950. };
  12951. scale.nice = function(interval, step) {
  12952. var d = domain();
  12953. return (interval = tickInterval(interval, d[0], d[d.length - 1], step))
  12954. ? domain(nice(d, interval))
  12955. : scale;
  12956. };
  12957. scale.copy = function() {
  12958. return copy(scale, calendar(year, month, week, day, hour, minute, second, millisecond, format$$1));
  12959. };
  12960. return scale;
  12961. }
  12962. var time = function() {
  12963. return calendar(d3Time.timeYear, d3Time.timeMonth, d3Time.timeWeek, d3Time.timeDay, d3Time.timeHour, d3Time.timeMinute, d3Time.timeSecond, d3Time.timeMillisecond, d3TimeFormat.timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]);
  12964. };
  12965. var utcTime = function() {
  12966. return calendar(d3Time.utcYear, d3Time.utcMonth, d3Time.utcWeek, d3Time.utcDay, d3Time.utcHour, d3Time.utcMinute, d3Time.utcSecond, d3Time.utcMillisecond, d3TimeFormat.utcFormat).domain([Date.UTC(2000, 0, 1), Date.UTC(2000, 0, 2)]);
  12967. };
  12968. var colors = function(s) {
  12969. return s.match(/.{6}/g).map(function(x) {
  12970. return "#" + x;
  12971. });
  12972. };
  12973. var category10 = colors("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf");
  12974. var category20b = colors("393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6");
  12975. var category20c = colors("3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9");
  12976. var category20 = colors("1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5");
  12977. var cubehelix$1 = d3Interpolate.interpolateCubehelixLong(d3Color.cubehelix(300, 0.5, 0.0), d3Color.cubehelix(-240, 0.5, 1.0));
  12978. var warm = d3Interpolate.interpolateCubehelixLong(d3Color.cubehelix(-100, 0.75, 0.35), d3Color.cubehelix(80, 1.50, 0.8));
  12979. var cool = d3Interpolate.interpolateCubehelixLong(d3Color.cubehelix(260, 0.75, 0.35), d3Color.cubehelix(80, 1.50, 0.8));
  12980. var rainbow = d3Color.cubehelix();
  12981. var rainbow$1 = function(t) {
  12982. if (t < 0 || t > 1) t -= Math.floor(t);
  12983. var ts = Math.abs(t - 0.5);
  12984. rainbow.h = 360 * t - 100;
  12985. rainbow.s = 1.5 - 1.5 * ts;
  12986. rainbow.l = 0.8 - 0.9 * ts;
  12987. return rainbow + "";
  12988. };
  12989. function ramp(range$$1) {
  12990. var n = range$$1.length;
  12991. return function(t) {
  12992. return range$$1[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
  12993. };
  12994. }
  12995. var viridis = ramp(colors("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));
  12996. var magma = ramp(colors("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf"));
  12997. var inferno = ramp(colors("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4"));
  12998. var plasma = ramp(colors("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));
  12999. function sequential(interpolator) {
  13000. var x0 = 0,
  13001. x1 = 1,
  13002. clamp = false;
  13003. function scale(x) {
  13004. var t = (x - x0) / (x1 - x0);
  13005. return interpolator(clamp ? Math.max(0, Math.min(1, t)) : t);
  13006. }
  13007. scale.domain = function(_) {
  13008. return arguments.length ? (x0 = +_[0], x1 = +_[1], scale) : [x0, x1];
  13009. };
  13010. scale.clamp = function(_) {
  13011. return arguments.length ? (clamp = !!_, scale) : clamp;
  13012. };
  13013. scale.interpolator = function(_) {
  13014. return arguments.length ? (interpolator = _, scale) : interpolator;
  13015. };
  13016. scale.copy = function() {
  13017. return sequential(interpolator).domain([x0, x1]).clamp(clamp);
  13018. };
  13019. return linearish(scale);
  13020. }
  13021. exports.scaleBand = band;
  13022. exports.scalePoint = point;
  13023. exports.scaleIdentity = identity;
  13024. exports.scaleLinear = linear;
  13025. exports.scaleLog = log;
  13026. exports.scaleOrdinal = ordinal;
  13027. exports.scaleImplicit = implicit;
  13028. exports.scalePow = pow;
  13029. exports.scaleSqrt = sqrt;
  13030. exports.scaleQuantile = quantile$1;
  13031. exports.scaleQuantize = quantize;
  13032. exports.scaleThreshold = threshold;
  13033. exports.scaleTime = time;
  13034. exports.scaleUtc = utcTime;
  13035. exports.schemeCategory10 = category10;
  13036. exports.schemeCategory20b = category20b;
  13037. exports.schemeCategory20c = category20c;
  13038. exports.schemeCategory20 = category20;
  13039. exports.interpolateCubehelixDefault = cubehelix$1;
  13040. exports.interpolateRainbow = rainbow$1;
  13041. exports.interpolateWarm = warm;
  13042. exports.interpolateCool = cool;
  13043. exports.interpolateViridis = viridis;
  13044. exports.interpolateMagma = magma;
  13045. exports.interpolateInferno = inferno;
  13046. exports.interpolatePlasma = plasma;
  13047. exports.scaleSequential = sequential;
  13048. Object.defineProperty(exports, '__esModule', { value: true });
  13049. })));
  13050. },{"d3-array":39,"d3-collection":43,"d3-color":44,"d3-format":50,"d3-interpolate":53,"d3-time":64,"d3-time-format":63}],61:[function(require,module,exports){
  13051. // https://d3js.org/d3-selection/ Version 1.2.0. Copyright 2017 Mike Bostock.
  13052. (function (global, factory) {
  13053. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  13054. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  13055. (factory((global.d3 = global.d3 || {})));
  13056. }(this, (function (exports) { 'use strict';
  13057. var xhtml = "http://www.w3.org/1999/xhtml";
  13058. var namespaces = {
  13059. svg: "http://www.w3.org/2000/svg",
  13060. xhtml: xhtml,
  13061. xlink: "http://www.w3.org/1999/xlink",
  13062. xml: "http://www.w3.org/XML/1998/namespace",
  13063. xmlns: "http://www.w3.org/2000/xmlns/"
  13064. };
  13065. var namespace = function(name) {
  13066. var prefix = name += "", i = prefix.indexOf(":");
  13067. if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
  13068. return namespaces.hasOwnProperty(prefix) ? {space: namespaces[prefix], local: name} : name;
  13069. };
  13070. function creatorInherit(name) {
  13071. return function() {
  13072. var document = this.ownerDocument,
  13073. uri = this.namespaceURI;
  13074. return uri === xhtml && document.documentElement.namespaceURI === xhtml
  13075. ? document.createElement(name)
  13076. : document.createElementNS(uri, name);
  13077. };
  13078. }
  13079. function creatorFixed(fullname) {
  13080. return function() {
  13081. return this.ownerDocument.createElementNS(fullname.space, fullname.local);
  13082. };
  13083. }
  13084. var creator = function(name) {
  13085. var fullname = namespace(name);
  13086. return (fullname.local
  13087. ? creatorFixed
  13088. : creatorInherit)(fullname);
  13089. };
  13090. var nextId = 0;
  13091. function local() {
  13092. return new Local;
  13093. }
  13094. function Local() {
  13095. this._ = "@" + (++nextId).toString(36);
  13096. }
  13097. Local.prototype = local.prototype = {
  13098. constructor: Local,
  13099. get: function(node) {
  13100. var id = this._;
  13101. while (!(id in node)) if (!(node = node.parentNode)) return;
  13102. return node[id];
  13103. },
  13104. set: function(node, value) {
  13105. return node[this._] = value;
  13106. },
  13107. remove: function(node) {
  13108. return this._ in node && delete node[this._];
  13109. },
  13110. toString: function() {
  13111. return this._;
  13112. }
  13113. };
  13114. var matcher = function(selector) {
  13115. return function() {
  13116. return this.matches(selector);
  13117. };
  13118. };
  13119. if (typeof document !== "undefined") {
  13120. var element = document.documentElement;
  13121. if (!element.matches) {
  13122. var vendorMatches = element.webkitMatchesSelector
  13123. || element.msMatchesSelector
  13124. || element.mozMatchesSelector
  13125. || element.oMatchesSelector;
  13126. matcher = function(selector) {
  13127. return function() {
  13128. return vendorMatches.call(this, selector);
  13129. };
  13130. };
  13131. }
  13132. }
  13133. var matcher$1 = matcher;
  13134. var filterEvents = {};
  13135. exports.event = null;
  13136. if (typeof document !== "undefined") {
  13137. var element$1 = document.documentElement;
  13138. if (!("onmouseenter" in element$1)) {
  13139. filterEvents = {mouseenter: "mouseover", mouseleave: "mouseout"};
  13140. }
  13141. }
  13142. function filterContextListener(listener, index, group) {
  13143. listener = contextListener(listener, index, group);
  13144. return function(event) {
  13145. var related = event.relatedTarget;
  13146. if (!related || (related !== this && !(related.compareDocumentPosition(this) & 8))) {
  13147. listener.call(this, event);
  13148. }
  13149. };
  13150. }
  13151. function contextListener(listener, index, group) {
  13152. return function(event1) {
  13153. var event0 = exports.event; // Events can be reentrant (e.g., focus).
  13154. exports.event = event1;
  13155. try {
  13156. listener.call(this, this.__data__, index, group);
  13157. } finally {
  13158. exports.event = event0;
  13159. }
  13160. };
  13161. }
  13162. function parseTypenames(typenames) {
  13163. return typenames.trim().split(/^|\s+/).map(function(t) {
  13164. var name = "", i = t.indexOf(".");
  13165. if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
  13166. return {type: t, name: name};
  13167. });
  13168. }
  13169. function onRemove(typename) {
  13170. return function() {
  13171. var on = this.__on;
  13172. if (!on) return;
  13173. for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {
  13174. if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
  13175. this.removeEventListener(o.type, o.listener, o.capture);
  13176. } else {
  13177. on[++i] = o;
  13178. }
  13179. }
  13180. if (++i) on.length = i;
  13181. else delete this.__on;
  13182. };
  13183. }
  13184. function onAdd(typename, value, capture) {
  13185. var wrap = filterEvents.hasOwnProperty(typename.type) ? filterContextListener : contextListener;
  13186. return function(d, i, group) {
  13187. var on = this.__on, o, listener = wrap(value, i, group);
  13188. if (on) for (var j = 0, m = on.length; j < m; ++j) {
  13189. if ((o = on[j]).type === typename.type && o.name === typename.name) {
  13190. this.removeEventListener(o.type, o.listener, o.capture);
  13191. this.addEventListener(o.type, o.listener = listener, o.capture = capture);
  13192. o.value = value;
  13193. return;
  13194. }
  13195. }
  13196. this.addEventListener(typename.type, listener, capture);
  13197. o = {type: typename.type, name: typename.name, value: value, listener: listener, capture: capture};
  13198. if (!on) this.__on = [o];
  13199. else on.push(o);
  13200. };
  13201. }
  13202. var selection_on = function(typename, value, capture) {
  13203. var typenames = parseTypenames(typename + ""), i, n = typenames.length, t;
  13204. if (arguments.length < 2) {
  13205. var on = this.node().__on;
  13206. if (on) for (var j = 0, m = on.length, o; j < m; ++j) {
  13207. for (i = 0, o = on[j]; i < n; ++i) {
  13208. if ((t = typenames[i]).type === o.type && t.name === o.name) {
  13209. return o.value;
  13210. }
  13211. }
  13212. }
  13213. return;
  13214. }
  13215. on = value ? onAdd : onRemove;
  13216. if (capture == null) capture = false;
  13217. for (i = 0; i < n; ++i) this.each(on(typenames[i], value, capture));
  13218. return this;
  13219. };
  13220. function customEvent(event1, listener, that, args) {
  13221. var event0 = exports.event;
  13222. event1.sourceEvent = exports.event;
  13223. exports.event = event1;
  13224. try {
  13225. return listener.apply(that, args);
  13226. } finally {
  13227. exports.event = event0;
  13228. }
  13229. }
  13230. var sourceEvent = function() {
  13231. var current = exports.event, source;
  13232. while (source = current.sourceEvent) current = source;
  13233. return current;
  13234. };
  13235. var point = function(node, event) {
  13236. var svg = node.ownerSVGElement || node;
  13237. if (svg.createSVGPoint) {
  13238. var point = svg.createSVGPoint();
  13239. point.x = event.clientX, point.y = event.clientY;
  13240. point = point.matrixTransform(node.getScreenCTM().inverse());
  13241. return [point.x, point.y];
  13242. }
  13243. var rect = node.getBoundingClientRect();
  13244. return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];
  13245. };
  13246. var mouse = function(node) {
  13247. var event = sourceEvent();
  13248. if (event.changedTouches) event = event.changedTouches[0];
  13249. return point(node, event);
  13250. };
  13251. function none() {}
  13252. var selector = function(selector) {
  13253. return selector == null ? none : function() {
  13254. return this.querySelector(selector);
  13255. };
  13256. };
  13257. var selection_select = function(select) {
  13258. if (typeof select !== "function") select = selector(select);
  13259. for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
  13260. for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
  13261. if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
  13262. if ("__data__" in node) subnode.__data__ = node.__data__;
  13263. subgroup[i] = subnode;
  13264. }
  13265. }
  13266. }
  13267. return new Selection(subgroups, this._parents);
  13268. };
  13269. function empty() {
  13270. return [];
  13271. }
  13272. var selectorAll = function(selector) {
  13273. return selector == null ? empty : function() {
  13274. return this.querySelectorAll(selector);
  13275. };
  13276. };
  13277. var selection_selectAll = function(select) {
  13278. if (typeof select !== "function") select = selectorAll(select);
  13279. for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
  13280. for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
  13281. if (node = group[i]) {
  13282. subgroups.push(select.call(node, node.__data__, i, group));
  13283. parents.push(node);
  13284. }
  13285. }
  13286. }
  13287. return new Selection(subgroups, parents);
  13288. };
  13289. var selection_filter = function(match) {
  13290. if (typeof match !== "function") match = matcher$1(match);
  13291. for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
  13292. for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
  13293. if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
  13294. subgroup.push(node);
  13295. }
  13296. }
  13297. }
  13298. return new Selection(subgroups, this._parents);
  13299. };
  13300. var sparse = function(update) {
  13301. return new Array(update.length);
  13302. };
  13303. var selection_enter = function() {
  13304. return new Selection(this._enter || this._groups.map(sparse), this._parents);
  13305. };
  13306. function EnterNode(parent, datum) {
  13307. this.ownerDocument = parent.ownerDocument;
  13308. this.namespaceURI = parent.namespaceURI;
  13309. this._next = null;
  13310. this._parent = parent;
  13311. this.__data__ = datum;
  13312. }
  13313. EnterNode.prototype = {
  13314. constructor: EnterNode,
  13315. appendChild: function(child) { return this._parent.insertBefore(child, this._next); },
  13316. insertBefore: function(child, next) { return this._parent.insertBefore(child, next); },
  13317. querySelector: function(selector) { return this._parent.querySelector(selector); },
  13318. querySelectorAll: function(selector) { return this._parent.querySelectorAll(selector); }
  13319. };
  13320. var constant = function(x) {
  13321. return function() {
  13322. return x;
  13323. };
  13324. };
  13325. var keyPrefix = "$"; // Protect against keys like “__proto__”.
  13326. function bindIndex(parent, group, enter, update, exit, data) {
  13327. var i = 0,
  13328. node,
  13329. groupLength = group.length,
  13330. dataLength = data.length;
  13331. // Put any non-null nodes that fit into update.
  13332. // Put any null nodes into enter.
  13333. // Put any remaining data into enter.
  13334. for (; i < dataLength; ++i) {
  13335. if (node = group[i]) {
  13336. node.__data__ = data[i];
  13337. update[i] = node;
  13338. } else {
  13339. enter[i] = new EnterNode(parent, data[i]);
  13340. }
  13341. }
  13342. // Put any non-null nodes that don’t fit into exit.
  13343. for (; i < groupLength; ++i) {
  13344. if (node = group[i]) {
  13345. exit[i] = node;
  13346. }
  13347. }
  13348. }
  13349. function bindKey(parent, group, enter, update, exit, data, key) {
  13350. var i,
  13351. node,
  13352. nodeByKeyValue = {},
  13353. groupLength = group.length,
  13354. dataLength = data.length,
  13355. keyValues = new Array(groupLength),
  13356. keyValue;
  13357. // Compute the key for each node.
  13358. // If multiple nodes have the same key, the duplicates are added to exit.
  13359. for (i = 0; i < groupLength; ++i) {
  13360. if (node = group[i]) {
  13361. keyValues[i] = keyValue = keyPrefix + key.call(node, node.__data__, i, group);
  13362. if (keyValue in nodeByKeyValue) {
  13363. exit[i] = node;
  13364. } else {
  13365. nodeByKeyValue[keyValue] = node;
  13366. }
  13367. }
  13368. }
  13369. // Compute the key for each datum.
  13370. // If there a node associated with this key, join and add it to update.
  13371. // If there is not (or the key is a duplicate), add it to enter.
  13372. for (i = 0; i < dataLength; ++i) {
  13373. keyValue = keyPrefix + key.call(parent, data[i], i, data);
  13374. if (node = nodeByKeyValue[keyValue]) {
  13375. update[i] = node;
  13376. node.__data__ = data[i];
  13377. nodeByKeyValue[keyValue] = null;
  13378. } else {
  13379. enter[i] = new EnterNode(parent, data[i]);
  13380. }
  13381. }
  13382. // Add any remaining nodes that were not bound to data to exit.
  13383. for (i = 0; i < groupLength; ++i) {
  13384. if ((node = group[i]) && (nodeByKeyValue[keyValues[i]] === node)) {
  13385. exit[i] = node;
  13386. }
  13387. }
  13388. }
  13389. var selection_data = function(value, key) {
  13390. if (!value) {
  13391. data = new Array(this.size()), j = -1;
  13392. this.each(function(d) { data[++j] = d; });
  13393. return data;
  13394. }
  13395. var bind = key ? bindKey : bindIndex,
  13396. parents = this._parents,
  13397. groups = this._groups;
  13398. if (typeof value !== "function") value = constant(value);
  13399. for (var m = groups.length, update = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
  13400. var parent = parents[j],
  13401. group = groups[j],
  13402. groupLength = group.length,
  13403. data = value.call(parent, parent && parent.__data__, j, parents),
  13404. dataLength = data.length,
  13405. enterGroup = enter[j] = new Array(dataLength),
  13406. updateGroup = update[j] = new Array(dataLength),
  13407. exitGroup = exit[j] = new Array(groupLength);
  13408. bind(parent, group, enterGroup, updateGroup, exitGroup, data, key);
  13409. // Now connect the enter nodes to their following update node, such that
  13410. // appendChild can insert the materialized enter node before this node,
  13411. // rather than at the end of the parent node.
  13412. for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
  13413. if (previous = enterGroup[i0]) {
  13414. if (i0 >= i1) i1 = i0 + 1;
  13415. while (!(next = updateGroup[i1]) && ++i1 < dataLength);
  13416. previous._next = next || null;
  13417. }
  13418. }
  13419. }
  13420. update = new Selection(update, parents);
  13421. update._enter = enter;
  13422. update._exit = exit;
  13423. return update;
  13424. };
  13425. var selection_exit = function() {
  13426. return new Selection(this._exit || this._groups.map(sparse), this._parents);
  13427. };
  13428. var selection_merge = function(selection) {
  13429. for (var groups0 = this._groups, groups1 = selection._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
  13430. for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
  13431. if (node = group0[i] || group1[i]) {
  13432. merge[i] = node;
  13433. }
  13434. }
  13435. }
  13436. for (; j < m0; ++j) {
  13437. merges[j] = groups0[j];
  13438. }
  13439. return new Selection(merges, this._parents);
  13440. };
  13441. var selection_order = function() {
  13442. for (var groups = this._groups, j = -1, m = groups.length; ++j < m;) {
  13443. for (var group = groups[j], i = group.length - 1, next = group[i], node; --i >= 0;) {
  13444. if (node = group[i]) {
  13445. if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
  13446. next = node;
  13447. }
  13448. }
  13449. }
  13450. return this;
  13451. };
  13452. var selection_sort = function(compare) {
  13453. if (!compare) compare = ascending;
  13454. function compareNode(a, b) {
  13455. return a && b ? compare(a.__data__, b.__data__) : !a - !b;
  13456. }
  13457. for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
  13458. for (var group = groups[j], n = group.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {
  13459. if (node = group[i]) {
  13460. sortgroup[i] = node;
  13461. }
  13462. }
  13463. sortgroup.sort(compareNode);
  13464. }
  13465. return new Selection(sortgroups, this._parents).order();
  13466. };
  13467. function ascending(a, b) {
  13468. return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
  13469. }
  13470. var selection_call = function() {
  13471. var callback = arguments[0];
  13472. arguments[0] = this;
  13473. callback.apply(null, arguments);
  13474. return this;
  13475. };
  13476. var selection_nodes = function() {
  13477. var nodes = new Array(this.size()), i = -1;
  13478. this.each(function() { nodes[++i] = this; });
  13479. return nodes;
  13480. };
  13481. var selection_node = function() {
  13482. for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
  13483. for (var group = groups[j], i = 0, n = group.length; i < n; ++i) {
  13484. var node = group[i];
  13485. if (node) return node;
  13486. }
  13487. }
  13488. return null;
  13489. };
  13490. var selection_size = function() {
  13491. var size = 0;
  13492. this.each(function() { ++size; });
  13493. return size;
  13494. };
  13495. var selection_empty = function() {
  13496. return !this.node();
  13497. };
  13498. var selection_each = function(callback) {
  13499. for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
  13500. for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
  13501. if (node = group[i]) callback.call(node, node.__data__, i, group);
  13502. }
  13503. }
  13504. return this;
  13505. };
  13506. function attrRemove(name) {
  13507. return function() {
  13508. this.removeAttribute(name);
  13509. };
  13510. }
  13511. function attrRemoveNS(fullname) {
  13512. return function() {
  13513. this.removeAttributeNS(fullname.space, fullname.local);
  13514. };
  13515. }
  13516. function attrConstant(name, value) {
  13517. return function() {
  13518. this.setAttribute(name, value);
  13519. };
  13520. }
  13521. function attrConstantNS(fullname, value) {
  13522. return function() {
  13523. this.setAttributeNS(fullname.space, fullname.local, value);
  13524. };
  13525. }
  13526. function attrFunction(name, value) {
  13527. return function() {
  13528. var v = value.apply(this, arguments);
  13529. if (v == null) this.removeAttribute(name);
  13530. else this.setAttribute(name, v);
  13531. };
  13532. }
  13533. function attrFunctionNS(fullname, value) {
  13534. return function() {
  13535. var v = value.apply(this, arguments);
  13536. if (v == null) this.removeAttributeNS(fullname.space, fullname.local);
  13537. else this.setAttributeNS(fullname.space, fullname.local, v);
  13538. };
  13539. }
  13540. var selection_attr = function(name, value) {
  13541. var fullname = namespace(name);
  13542. if (arguments.length < 2) {
  13543. var node = this.node();
  13544. return fullname.local
  13545. ? node.getAttributeNS(fullname.space, fullname.local)
  13546. : node.getAttribute(fullname);
  13547. }
  13548. return this.each((value == null
  13549. ? (fullname.local ? attrRemoveNS : attrRemove) : (typeof value === "function"
  13550. ? (fullname.local ? attrFunctionNS : attrFunction)
  13551. : (fullname.local ? attrConstantNS : attrConstant)))(fullname, value));
  13552. };
  13553. var defaultView = function(node) {
  13554. return (node.ownerDocument && node.ownerDocument.defaultView) // node is a Node
  13555. || (node.document && node) // node is a Window
  13556. || node.defaultView; // node is a Document
  13557. };
  13558. function styleRemove(name) {
  13559. return function() {
  13560. this.style.removeProperty(name);
  13561. };
  13562. }
  13563. function styleConstant(name, value, priority) {
  13564. return function() {
  13565. this.style.setProperty(name, value, priority);
  13566. };
  13567. }
  13568. function styleFunction(name, value, priority) {
  13569. return function() {
  13570. var v = value.apply(this, arguments);
  13571. if (v == null) this.style.removeProperty(name);
  13572. else this.style.setProperty(name, v, priority);
  13573. };
  13574. }
  13575. var selection_style = function(name, value, priority) {
  13576. return arguments.length > 1
  13577. ? this.each((value == null
  13578. ? styleRemove : typeof value === "function"
  13579. ? styleFunction
  13580. : styleConstant)(name, value, priority == null ? "" : priority))
  13581. : styleValue(this.node(), name);
  13582. };
  13583. function styleValue(node, name) {
  13584. return node.style.getPropertyValue(name)
  13585. || defaultView(node).getComputedStyle(node, null).getPropertyValue(name);
  13586. }
  13587. function propertyRemove(name) {
  13588. return function() {
  13589. delete this[name];
  13590. };
  13591. }
  13592. function propertyConstant(name, value) {
  13593. return function() {
  13594. this[name] = value;
  13595. };
  13596. }
  13597. function propertyFunction(name, value) {
  13598. return function() {
  13599. var v = value.apply(this, arguments);
  13600. if (v == null) delete this[name];
  13601. else this[name] = v;
  13602. };
  13603. }
  13604. var selection_property = function(name, value) {
  13605. return arguments.length > 1
  13606. ? this.each((value == null
  13607. ? propertyRemove : typeof value === "function"
  13608. ? propertyFunction
  13609. : propertyConstant)(name, value))
  13610. : this.node()[name];
  13611. };
  13612. function classArray(string) {
  13613. return string.trim().split(/^|\s+/);
  13614. }
  13615. function classList(node) {
  13616. return node.classList || new ClassList(node);
  13617. }
  13618. function ClassList(node) {
  13619. this._node = node;
  13620. this._names = classArray(node.getAttribute("class") || "");
  13621. }
  13622. ClassList.prototype = {
  13623. add: function(name) {
  13624. var i = this._names.indexOf(name);
  13625. if (i < 0) {
  13626. this._names.push(name);
  13627. this._node.setAttribute("class", this._names.join(" "));
  13628. }
  13629. },
  13630. remove: function(name) {
  13631. var i = this._names.indexOf(name);
  13632. if (i >= 0) {
  13633. this._names.splice(i, 1);
  13634. this._node.setAttribute("class", this._names.join(" "));
  13635. }
  13636. },
  13637. contains: function(name) {
  13638. return this._names.indexOf(name) >= 0;
  13639. }
  13640. };
  13641. function classedAdd(node, names) {
  13642. var list = classList(node), i = -1, n = names.length;
  13643. while (++i < n) list.add(names[i]);
  13644. }
  13645. function classedRemove(node, names) {
  13646. var list = classList(node), i = -1, n = names.length;
  13647. while (++i < n) list.remove(names[i]);
  13648. }
  13649. function classedTrue(names) {
  13650. return function() {
  13651. classedAdd(this, names);
  13652. };
  13653. }
  13654. function classedFalse(names) {
  13655. return function() {
  13656. classedRemove(this, names);
  13657. };
  13658. }
  13659. function classedFunction(names, value) {
  13660. return function() {
  13661. (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
  13662. };
  13663. }
  13664. var selection_classed = function(name, value) {
  13665. var names = classArray(name + "");
  13666. if (arguments.length < 2) {
  13667. var list = classList(this.node()), i = -1, n = names.length;
  13668. while (++i < n) if (!list.contains(names[i])) return false;
  13669. return true;
  13670. }
  13671. return this.each((typeof value === "function"
  13672. ? classedFunction : value
  13673. ? classedTrue
  13674. : classedFalse)(names, value));
  13675. };
  13676. function textRemove() {
  13677. this.textContent = "";
  13678. }
  13679. function textConstant(value) {
  13680. return function() {
  13681. this.textContent = value;
  13682. };
  13683. }
  13684. function textFunction(value) {
  13685. return function() {
  13686. var v = value.apply(this, arguments);
  13687. this.textContent = v == null ? "" : v;
  13688. };
  13689. }
  13690. var selection_text = function(value) {
  13691. return arguments.length
  13692. ? this.each(value == null
  13693. ? textRemove : (typeof value === "function"
  13694. ? textFunction
  13695. : textConstant)(value))
  13696. : this.node().textContent;
  13697. };
  13698. function htmlRemove() {
  13699. this.innerHTML = "";
  13700. }
  13701. function htmlConstant(value) {
  13702. return function() {
  13703. this.innerHTML = value;
  13704. };
  13705. }
  13706. function htmlFunction(value) {
  13707. return function() {
  13708. var v = value.apply(this, arguments);
  13709. this.innerHTML = v == null ? "" : v;
  13710. };
  13711. }
  13712. var selection_html = function(value) {
  13713. return arguments.length
  13714. ? this.each(value == null
  13715. ? htmlRemove : (typeof value === "function"
  13716. ? htmlFunction
  13717. : htmlConstant)(value))
  13718. : this.node().innerHTML;
  13719. };
  13720. function raise() {
  13721. if (this.nextSibling) this.parentNode.appendChild(this);
  13722. }
  13723. var selection_raise = function() {
  13724. return this.each(raise);
  13725. };
  13726. function lower() {
  13727. if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);
  13728. }
  13729. var selection_lower = function() {
  13730. return this.each(lower);
  13731. };
  13732. var selection_append = function(name) {
  13733. var create = typeof name === "function" ? name : creator(name);
  13734. return this.select(function() {
  13735. return this.appendChild(create.apply(this, arguments));
  13736. });
  13737. };
  13738. function constantNull() {
  13739. return null;
  13740. }
  13741. var selection_insert = function(name, before) {
  13742. var create = typeof name === "function" ? name : creator(name),
  13743. select = before == null ? constantNull : typeof before === "function" ? before : selector(before);
  13744. return this.select(function() {
  13745. return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);
  13746. });
  13747. };
  13748. function remove() {
  13749. var parent = this.parentNode;
  13750. if (parent) parent.removeChild(this);
  13751. }
  13752. var selection_remove = function() {
  13753. return this.each(remove);
  13754. };
  13755. var selection_datum = function(value) {
  13756. return arguments.length
  13757. ? this.property("__data__", value)
  13758. : this.node().__data__;
  13759. };
  13760. function dispatchEvent(node, type, params) {
  13761. var window = defaultView(node),
  13762. event = window.CustomEvent;
  13763. if (typeof event === "function") {
  13764. event = new event(type, params);
  13765. } else {
  13766. event = window.document.createEvent("Event");
  13767. if (params) event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;
  13768. else event.initEvent(type, false, false);
  13769. }
  13770. node.dispatchEvent(event);
  13771. }
  13772. function dispatchConstant(type, params) {
  13773. return function() {
  13774. return dispatchEvent(this, type, params);
  13775. };
  13776. }
  13777. function dispatchFunction(type, params) {
  13778. return function() {
  13779. return dispatchEvent(this, type, params.apply(this, arguments));
  13780. };
  13781. }
  13782. var selection_dispatch = function(type, params) {
  13783. return this.each((typeof params === "function"
  13784. ? dispatchFunction
  13785. : dispatchConstant)(type, params));
  13786. };
  13787. var root = [null];
  13788. function Selection(groups, parents) {
  13789. this._groups = groups;
  13790. this._parents = parents;
  13791. }
  13792. function selection() {
  13793. return new Selection([[document.documentElement]], root);
  13794. }
  13795. Selection.prototype = selection.prototype = {
  13796. constructor: Selection,
  13797. select: selection_select,
  13798. selectAll: selection_selectAll,
  13799. filter: selection_filter,
  13800. data: selection_data,
  13801. enter: selection_enter,
  13802. exit: selection_exit,
  13803. merge: selection_merge,
  13804. order: selection_order,
  13805. sort: selection_sort,
  13806. call: selection_call,
  13807. nodes: selection_nodes,
  13808. node: selection_node,
  13809. size: selection_size,
  13810. empty: selection_empty,
  13811. each: selection_each,
  13812. attr: selection_attr,
  13813. style: selection_style,
  13814. property: selection_property,
  13815. classed: selection_classed,
  13816. text: selection_text,
  13817. html: selection_html,
  13818. raise: selection_raise,
  13819. lower: selection_lower,
  13820. append: selection_append,
  13821. insert: selection_insert,
  13822. remove: selection_remove,
  13823. datum: selection_datum,
  13824. on: selection_on,
  13825. dispatch: selection_dispatch
  13826. };
  13827. var select = function(selector) {
  13828. return typeof selector === "string"
  13829. ? new Selection([[document.querySelector(selector)]], [document.documentElement])
  13830. : new Selection([[selector]], root);
  13831. };
  13832. var selectAll = function(selector) {
  13833. return typeof selector === "string"
  13834. ? new Selection([document.querySelectorAll(selector)], [document.documentElement])
  13835. : new Selection([selector == null ? [] : selector], root);
  13836. };
  13837. var touch = function(node, touches, identifier) {
  13838. if (arguments.length < 3) identifier = touches, touches = sourceEvent().changedTouches;
  13839. for (var i = 0, n = touches ? touches.length : 0, touch; i < n; ++i) {
  13840. if ((touch = touches[i]).identifier === identifier) {
  13841. return point(node, touch);
  13842. }
  13843. }
  13844. return null;
  13845. };
  13846. var touches = function(node, touches) {
  13847. if (touches == null) touches = sourceEvent().touches;
  13848. for (var i = 0, n = touches ? touches.length : 0, points = new Array(n); i < n; ++i) {
  13849. points[i] = point(node, touches[i]);
  13850. }
  13851. return points;
  13852. };
  13853. exports.creator = creator;
  13854. exports.local = local;
  13855. exports.matcher = matcher$1;
  13856. exports.mouse = mouse;
  13857. exports.namespace = namespace;
  13858. exports.namespaces = namespaces;
  13859. exports.clientPoint = point;
  13860. exports.select = select;
  13861. exports.selectAll = selectAll;
  13862. exports.selection = selection;
  13863. exports.selector = selector;
  13864. exports.selectorAll = selectorAll;
  13865. exports.style = styleValue;
  13866. exports.touch = touch;
  13867. exports.touches = touches;
  13868. exports.window = defaultView;
  13869. exports.customEvent = customEvent;
  13870. Object.defineProperty(exports, '__esModule', { value: true });
  13871. })));
  13872. },{}],62:[function(require,module,exports){
  13873. // https://d3js.org/d3-shape/ Version 1.2.0. Copyright 2017 Mike Bostock.
  13874. (function (global, factory) {
  13875. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-path')) :
  13876. typeof define === 'function' && define.amd ? define(['exports', 'd3-path'], factory) :
  13877. (factory((global.d3 = global.d3 || {}),global.d3));
  13878. }(this, (function (exports,d3Path) { 'use strict';
  13879. var constant = function(x) {
  13880. return function constant() {
  13881. return x;
  13882. };
  13883. };
  13884. var abs = Math.abs;
  13885. var atan2 = Math.atan2;
  13886. var cos = Math.cos;
  13887. var max = Math.max;
  13888. var min = Math.min;
  13889. var sin = Math.sin;
  13890. var sqrt = Math.sqrt;
  13891. var epsilon = 1e-12;
  13892. var pi = Math.PI;
  13893. var halfPi = pi / 2;
  13894. var tau = 2 * pi;
  13895. function acos(x) {
  13896. return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
  13897. }
  13898. function asin(x) {
  13899. return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x);
  13900. }
  13901. function arcInnerRadius(d) {
  13902. return d.innerRadius;
  13903. }
  13904. function arcOuterRadius(d) {
  13905. return d.outerRadius;
  13906. }
  13907. function arcStartAngle(d) {
  13908. return d.startAngle;
  13909. }
  13910. function arcEndAngle(d) {
  13911. return d.endAngle;
  13912. }
  13913. function arcPadAngle(d) {
  13914. return d && d.padAngle; // Note: optional!
  13915. }
  13916. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  13917. var x10 = x1 - x0, y10 = y1 - y0,
  13918. x32 = x3 - x2, y32 = y3 - y2,
  13919. t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / (y32 * x10 - x32 * y10);
  13920. return [x0 + t * x10, y0 + t * y10];
  13921. }
  13922. // Compute perpendicular offset line of length rc.
  13923. // http://mathworld.wolfram.com/Circle-LineIntersection.html
  13924. function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
  13925. var x01 = x0 - x1,
  13926. y01 = y0 - y1,
  13927. lo = (cw ? rc : -rc) / sqrt(x01 * x01 + y01 * y01),
  13928. ox = lo * y01,
  13929. oy = -lo * x01,
  13930. x11 = x0 + ox,
  13931. y11 = y0 + oy,
  13932. x10 = x1 + ox,
  13933. y10 = y1 + oy,
  13934. x00 = (x11 + x10) / 2,
  13935. y00 = (y11 + y10) / 2,
  13936. dx = x10 - x11,
  13937. dy = y10 - y11,
  13938. d2 = dx * dx + dy * dy,
  13939. r = r1 - rc,
  13940. D = x11 * y10 - x10 * y11,
  13941. d = (dy < 0 ? -1 : 1) * sqrt(max(0, r * r * d2 - D * D)),
  13942. cx0 = (D * dy - dx * d) / d2,
  13943. cy0 = (-D * dx - dy * d) / d2,
  13944. cx1 = (D * dy + dx * d) / d2,
  13945. cy1 = (-D * dx + dy * d) / d2,
  13946. dx0 = cx0 - x00,
  13947. dy0 = cy0 - y00,
  13948. dx1 = cx1 - x00,
  13949. dy1 = cy1 - y00;
  13950. // Pick the closer of the two intersection points.
  13951. // TODO Is there a faster way to determine which intersection to use?
  13952. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
  13953. return {
  13954. cx: cx0,
  13955. cy: cy0,
  13956. x01: -ox,
  13957. y01: -oy,
  13958. x11: cx0 * (r1 / r - 1),
  13959. y11: cy0 * (r1 / r - 1)
  13960. };
  13961. }
  13962. var arc = function() {
  13963. var innerRadius = arcInnerRadius,
  13964. outerRadius = arcOuterRadius,
  13965. cornerRadius = constant(0),
  13966. padRadius = null,
  13967. startAngle = arcStartAngle,
  13968. endAngle = arcEndAngle,
  13969. padAngle = arcPadAngle,
  13970. context = null;
  13971. function arc() {
  13972. var buffer,
  13973. r,
  13974. r0 = +innerRadius.apply(this, arguments),
  13975. r1 = +outerRadius.apply(this, arguments),
  13976. a0 = startAngle.apply(this, arguments) - halfPi,
  13977. a1 = endAngle.apply(this, arguments) - halfPi,
  13978. da = abs(a1 - a0),
  13979. cw = a1 > a0;
  13980. if (!context) context = buffer = d3Path.path();
  13981. // Ensure that the outer radius is always larger than the inner radius.
  13982. if (r1 < r0) r = r1, r1 = r0, r0 = r;
  13983. // Is it a point?
  13984. if (!(r1 > epsilon)) context.moveTo(0, 0);
  13985. // Or is it a circle or annulus?
  13986. else if (da > tau - epsilon) {
  13987. context.moveTo(r1 * cos(a0), r1 * sin(a0));
  13988. context.arc(0, 0, r1, a0, a1, !cw);
  13989. if (r0 > epsilon) {
  13990. context.moveTo(r0 * cos(a1), r0 * sin(a1));
  13991. context.arc(0, 0, r0, a1, a0, cw);
  13992. }
  13993. }
  13994. // Or is it a circular or annular sector?
  13995. else {
  13996. var a01 = a0,
  13997. a11 = a1,
  13998. a00 = a0,
  13999. a10 = a1,
  14000. da0 = da,
  14001. da1 = da,
  14002. ap = padAngle.apply(this, arguments) / 2,
  14003. rp = (ap > epsilon) && (padRadius ? +padRadius.apply(this, arguments) : sqrt(r0 * r0 + r1 * r1)),
  14004. rc = min(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)),
  14005. rc0 = rc,
  14006. rc1 = rc,
  14007. t0,
  14008. t1;
  14009. // Apply padding? Note that since r1 ≥ r0, da1 ≥ da0.
  14010. if (rp > epsilon) {
  14011. var p0 = asin(rp / r0 * sin(ap)),
  14012. p1 = asin(rp / r1 * sin(ap));
  14013. if ((da0 -= p0 * 2) > epsilon) p0 *= (cw ? 1 : -1), a00 += p0, a10 -= p0;
  14014. else da0 = 0, a00 = a10 = (a0 + a1) / 2;
  14015. if ((da1 -= p1 * 2) > epsilon) p1 *= (cw ? 1 : -1), a01 += p1, a11 -= p1;
  14016. else da1 = 0, a01 = a11 = (a0 + a1) / 2;
  14017. }
  14018. var x01 = r1 * cos(a01),
  14019. y01 = r1 * sin(a01),
  14020. x10 = r0 * cos(a10),
  14021. y10 = r0 * sin(a10);
  14022. // Apply rounded corners?
  14023. if (rc > epsilon) {
  14024. var x11 = r1 * cos(a11),
  14025. y11 = r1 * sin(a11),
  14026. x00 = r0 * cos(a00),
  14027. y00 = r0 * sin(a00);
  14028. // Restrict the corner radius according to the sector angle.
  14029. if (da < pi) {
  14030. var oc = da0 > epsilon ? intersect(x01, y01, x00, y00, x11, y11, x10, y10) : [x10, y10],
  14031. ax = x01 - oc[0],
  14032. ay = y01 - oc[1],
  14033. bx = x11 - oc[0],
  14034. by = y11 - oc[1],
  14035. kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2),
  14036. lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
  14037. rc0 = min(rc, (r0 - lc) / (kc - 1));
  14038. rc1 = min(rc, (r1 - lc) / (kc + 1));
  14039. }
  14040. }
  14041. // Is the sector collapsed to a line?
  14042. if (!(da1 > epsilon)) context.moveTo(x01, y01);
  14043. // Does the sector’s outer ring have rounded corners?
  14044. else if (rc1 > epsilon) {
  14045. t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
  14046. t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);
  14047. context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01);
  14048. // Have the corners merged?
  14049. if (rc1 < rc) context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);
  14050. // Otherwise, draw the two corners and the ring.
  14051. else {
  14052. context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
  14053. context.arc(0, 0, r1, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw);
  14054. context.arc(t1.cx, t1.cy, rc1, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
  14055. }
  14056. }
  14057. // Or is the outer ring just a circular arc?
  14058. else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);
  14059. // Is there no inner ring, and it’s a circular sector?
  14060. // Or perhaps it’s an annular sector collapsed due to padding?
  14061. if (!(r0 > epsilon) || !(da0 > epsilon)) context.lineTo(x10, y10);
  14062. // Does the sector’s inner ring (or point) have rounded corners?
  14063. else if (rc0 > epsilon) {
  14064. t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
  14065. t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);
  14066. context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01);
  14067. // Have the corners merged?
  14068. if (rc0 < rc) context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);
  14069. // Otherwise, draw the two corners and the ring.
  14070. else {
  14071. context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
  14072. context.arc(0, 0, r0, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw);
  14073. context.arc(t1.cx, t1.cy, rc0, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
  14074. }
  14075. }
  14076. // Or is the inner ring just a circular arc?
  14077. else context.arc(0, 0, r0, a10, a00, cw);
  14078. }
  14079. context.closePath();
  14080. if (buffer) return context = null, buffer + "" || null;
  14081. }
  14082. arc.centroid = function() {
  14083. var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2,
  14084. a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi / 2;
  14085. return [cos(a) * r, sin(a) * r];
  14086. };
  14087. arc.innerRadius = function(_) {
  14088. return arguments.length ? (innerRadius = typeof _ === "function" ? _ : constant(+_), arc) : innerRadius;
  14089. };
  14090. arc.outerRadius = function(_) {
  14091. return arguments.length ? (outerRadius = typeof _ === "function" ? _ : constant(+_), arc) : outerRadius;
  14092. };
  14093. arc.cornerRadius = function(_) {
  14094. return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : constant(+_), arc) : cornerRadius;
  14095. };
  14096. arc.padRadius = function(_) {
  14097. return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : constant(+_), arc) : padRadius;
  14098. };
  14099. arc.startAngle = function(_) {
  14100. return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant(+_), arc) : startAngle;
  14101. };
  14102. arc.endAngle = function(_) {
  14103. return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant(+_), arc) : endAngle;
  14104. };
  14105. arc.padAngle = function(_) {
  14106. return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant(+_), arc) : padAngle;
  14107. };
  14108. arc.context = function(_) {
  14109. return arguments.length ? ((context = _ == null ? null : _), arc) : context;
  14110. };
  14111. return arc;
  14112. };
  14113. function Linear(context) {
  14114. this._context = context;
  14115. }
  14116. Linear.prototype = {
  14117. areaStart: function() {
  14118. this._line = 0;
  14119. },
  14120. areaEnd: function() {
  14121. this._line = NaN;
  14122. },
  14123. lineStart: function() {
  14124. this._point = 0;
  14125. },
  14126. lineEnd: function() {
  14127. if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
  14128. this._line = 1 - this._line;
  14129. },
  14130. point: function(x, y) {
  14131. x = +x, y = +y;
  14132. switch (this._point) {
  14133. case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
  14134. case 1: this._point = 2; // proceed
  14135. default: this._context.lineTo(x, y); break;
  14136. }
  14137. }
  14138. };
  14139. var curveLinear = function(context) {
  14140. return new Linear(context);
  14141. };
  14142. function x(p) {
  14143. return p[0];
  14144. }
  14145. function y(p) {
  14146. return p[1];
  14147. }
  14148. var line = function() {
  14149. var x$$1 = x,
  14150. y$$1 = y,
  14151. defined = constant(true),
  14152. context = null,
  14153. curve = curveLinear,
  14154. output = null;
  14155. function line(data) {
  14156. var i,
  14157. n = data.length,
  14158. d,
  14159. defined0 = false,
  14160. buffer;
  14161. if (context == null) output = curve(buffer = d3Path.path());
  14162. for (i = 0; i <= n; ++i) {
  14163. if (!(i < n && defined(d = data[i], i, data)) === defined0) {
  14164. if (defined0 = !defined0) output.lineStart();
  14165. else output.lineEnd();
  14166. }
  14167. if (defined0) output.point(+x$$1(d, i, data), +y$$1(d, i, data));
  14168. }
  14169. if (buffer) return output = null, buffer + "" || null;
  14170. }
  14171. line.x = function(_) {
  14172. return arguments.length ? (x$$1 = typeof _ === "function" ? _ : constant(+_), line) : x$$1;
  14173. };
  14174. line.y = function(_) {
  14175. return arguments.length ? (y$$1 = typeof _ === "function" ? _ : constant(+_), line) : y$$1;
  14176. };
  14177. line.defined = function(_) {
  14178. return arguments.length ? (defined = typeof _ === "function" ? _ : constant(!!_), line) : defined;
  14179. };
  14180. line.curve = function(_) {
  14181. return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
  14182. };
  14183. line.context = function(_) {
  14184. return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
  14185. };
  14186. return line;
  14187. };
  14188. var area = function() {
  14189. var x0 = x,
  14190. x1 = null,
  14191. y0 = constant(0),
  14192. y1 = y,
  14193. defined = constant(true),
  14194. context = null,
  14195. curve = curveLinear,
  14196. output = null;
  14197. function area(data) {
  14198. var i,
  14199. j,
  14200. k,
  14201. n = data.length,
  14202. d,
  14203. defined0 = false,
  14204. buffer,
  14205. x0z = new Array(n),
  14206. y0z = new Array(n);
  14207. if (context == null) output = curve(buffer = d3Path.path());
  14208. for (i = 0; i <= n; ++i) {
  14209. if (!(i < n && defined(d = data[i], i, data)) === defined0) {
  14210. if (defined0 = !defined0) {
  14211. j = i;
  14212. output.areaStart();
  14213. output.lineStart();
  14214. } else {
  14215. output.lineEnd();
  14216. output.lineStart();
  14217. for (k = i - 1; k >= j; --k) {
  14218. output.point(x0z[k], y0z[k]);
  14219. }
  14220. output.lineEnd();
  14221. output.areaEnd();
  14222. }
  14223. }
  14224. if (defined0) {
  14225. x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);
  14226. output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);
  14227. }
  14228. }
  14229. if (buffer) return output = null, buffer + "" || null;
  14230. }
  14231. function arealine() {
  14232. return line().defined(defined).curve(curve).context(context);
  14233. }
  14234. area.x = function(_) {
  14235. return arguments.length ? (x0 = typeof _ === "function" ? _ : constant(+_), x1 = null, area) : x0;
  14236. };
  14237. area.x0 = function(_) {
  14238. return arguments.length ? (x0 = typeof _ === "function" ? _ : constant(+_), area) : x0;
  14239. };
  14240. area.x1 = function(_) {
  14241. return arguments.length ? (x1 = _ == null ? null : typeof _ === "function" ? _ : constant(+_), area) : x1;
  14242. };
  14243. area.y = function(_) {
  14244. return arguments.length ? (y0 = typeof _ === "function" ? _ : constant(+_), y1 = null, area) : y0;
  14245. };
  14246. area.y0 = function(_) {
  14247. return arguments.length ? (y0 = typeof _ === "function" ? _ : constant(+_), area) : y0;
  14248. };
  14249. area.y1 = function(_) {
  14250. return arguments.length ? (y1 = _ == null ? null : typeof _ === "function" ? _ : constant(+_), area) : y1;
  14251. };
  14252. area.lineX0 =
  14253. area.lineY0 = function() {
  14254. return arealine().x(x0).y(y0);
  14255. };
  14256. area.lineY1 = function() {
  14257. return arealine().x(x0).y(y1);
  14258. };
  14259. area.lineX1 = function() {
  14260. return arealine().x(x1).y(y0);
  14261. };
  14262. area.defined = function(_) {
  14263. return arguments.length ? (defined = typeof _ === "function" ? _ : constant(!!_), area) : defined;
  14264. };
  14265. area.curve = function(_) {
  14266. return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve;
  14267. };
  14268. area.context = function(_) {
  14269. return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context;
  14270. };
  14271. return area;
  14272. };
  14273. var descending = function(a, b) {
  14274. return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
  14275. };
  14276. var identity = function(d) {
  14277. return d;
  14278. };
  14279. var pie = function() {
  14280. var value = identity,
  14281. sortValues = descending,
  14282. sort = null,
  14283. startAngle = constant(0),
  14284. endAngle = constant(tau),
  14285. padAngle = constant(0);
  14286. function pie(data) {
  14287. var i,
  14288. n = data.length,
  14289. j,
  14290. k,
  14291. sum = 0,
  14292. index = new Array(n),
  14293. arcs = new Array(n),
  14294. a0 = +startAngle.apply(this, arguments),
  14295. da = Math.min(tau, Math.max(-tau, endAngle.apply(this, arguments) - a0)),
  14296. a1,
  14297. p = Math.min(Math.abs(da) / n, padAngle.apply(this, arguments)),
  14298. pa = p * (da < 0 ? -1 : 1),
  14299. v;
  14300. for (i = 0; i < n; ++i) {
  14301. if ((v = arcs[index[i] = i] = +value(data[i], i, data)) > 0) {
  14302. sum += v;
  14303. }
  14304. }
  14305. // Optionally sort the arcs by previously-computed values or by data.
  14306. if (sortValues != null) index.sort(function(i, j) { return sortValues(arcs[i], arcs[j]); });
  14307. else if (sort != null) index.sort(function(i, j) { return sort(data[i], data[j]); });
  14308. // Compute the arcs! They are stored in the original data's order.
  14309. for (i = 0, k = sum ? (da - n * pa) / sum : 0; i < n; ++i, a0 = a1) {
  14310. j = index[i], v = arcs[j], a1 = a0 + (v > 0 ? v * k : 0) + pa, arcs[j] = {
  14311. data: data[j],
  14312. index: i,
  14313. value: v,
  14314. startAngle: a0,
  14315. endAngle: a1,
  14316. padAngle: p
  14317. };
  14318. }
  14319. return arcs;
  14320. }
  14321. pie.value = function(_) {
  14322. return arguments.length ? (value = typeof _ === "function" ? _ : constant(+_), pie) : value;
  14323. };
  14324. pie.sortValues = function(_) {
  14325. return arguments.length ? (sortValues = _, sort = null, pie) : sortValues;
  14326. };
  14327. pie.sort = function(_) {
  14328. return arguments.length ? (sort = _, sortValues = null, pie) : sort;
  14329. };
  14330. pie.startAngle = function(_) {
  14331. return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant(+_), pie) : startAngle;
  14332. };
  14333. pie.endAngle = function(_) {
  14334. return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant(+_), pie) : endAngle;
  14335. };
  14336. pie.padAngle = function(_) {
  14337. return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant(+_), pie) : padAngle;
  14338. };
  14339. return pie;
  14340. };
  14341. var curveRadialLinear = curveRadial(curveLinear);
  14342. function Radial(curve) {
  14343. this._curve = curve;
  14344. }
  14345. Radial.prototype = {
  14346. areaStart: function() {
  14347. this._curve.areaStart();
  14348. },
  14349. areaEnd: function() {
  14350. this._curve.areaEnd();
  14351. },
  14352. lineStart: function() {
  14353. this._curve.lineStart();
  14354. },
  14355. lineEnd: function() {
  14356. this._curve.lineEnd();
  14357. },
  14358. point: function(a, r) {
  14359. this._curve.point(r * Math.sin(a), r * -Math.cos(a));
  14360. }
  14361. };
  14362. function curveRadial(curve) {
  14363. function radial(context) {
  14364. return new Radial(curve(context));
  14365. }
  14366. radial._curve = curve;
  14367. return radial;
  14368. }
  14369. function lineRadial(l) {
  14370. var c = l.curve;
  14371. l.angle = l.x, delete l.x;
  14372. l.radius = l.y, delete l.y;
  14373. l.curve = function(_) {
  14374. return arguments.length ? c(curveRadial(_)) : c()._curve;
  14375. };
  14376. return l;
  14377. }
  14378. var lineRadial$1 = function() {
  14379. return lineRadial(line().curve(curveRadialLinear));
  14380. };
  14381. var areaRadial = function() {
  14382. var a = area().curve(curveRadialLinear),
  14383. c = a.curve,
  14384. x0 = a.lineX0,
  14385. x1 = a.lineX1,
  14386. y0 = a.lineY0,
  14387. y1 = a.lineY1;
  14388. a.angle = a.x, delete a.x;
  14389. a.startAngle = a.x0, delete a.x0;
  14390. a.endAngle = a.x1, delete a.x1;
  14391. a.radius = a.y, delete a.y;
  14392. a.innerRadius = a.y0, delete a.y0;
  14393. a.outerRadius = a.y1, delete a.y1;
  14394. a.lineStartAngle = function() { return lineRadial(x0()); }, delete a.lineX0;
  14395. a.lineEndAngle = function() { return lineRadial(x1()); }, delete a.lineX1;
  14396. a.lineInnerRadius = function() { return lineRadial(y0()); }, delete a.lineY0;
  14397. a.lineOuterRadius = function() { return lineRadial(y1()); }, delete a.lineY1;
  14398. a.curve = function(_) {
  14399. return arguments.length ? c(curveRadial(_)) : c()._curve;
  14400. };
  14401. return a;
  14402. };
  14403. var pointRadial = function(x, y) {
  14404. return [(y = +y) * Math.cos(x -= Math.PI / 2), y * Math.sin(x)];
  14405. };
  14406. var slice = Array.prototype.slice;
  14407. function linkSource(d) {
  14408. return d.source;
  14409. }
  14410. function linkTarget(d) {
  14411. return d.target;
  14412. }
  14413. function link(curve) {
  14414. var source = linkSource,
  14415. target = linkTarget,
  14416. x$$1 = x,
  14417. y$$1 = y,
  14418. context = null;
  14419. function link() {
  14420. var buffer, argv = slice.call(arguments), s = source.apply(this, argv), t = target.apply(this, argv);
  14421. if (!context) context = buffer = d3Path.path();
  14422. curve(context, +x$$1.apply(this, (argv[0] = s, argv)), +y$$1.apply(this, argv), +x$$1.apply(this, (argv[0] = t, argv)), +y$$1.apply(this, argv));
  14423. if (buffer) return context = null, buffer + "" || null;
  14424. }
  14425. link.source = function(_) {
  14426. return arguments.length ? (source = _, link) : source;
  14427. };
  14428. link.target = function(_) {
  14429. return arguments.length ? (target = _, link) : target;
  14430. };
  14431. link.x = function(_) {
  14432. return arguments.length ? (x$$1 = typeof _ === "function" ? _ : constant(+_), link) : x$$1;
  14433. };
  14434. link.y = function(_) {
  14435. return arguments.length ? (y$$1 = typeof _ === "function" ? _ : constant(+_), link) : y$$1;
  14436. };
  14437. link.context = function(_) {
  14438. return arguments.length ? ((context = _ == null ? null : _), link) : context;
  14439. };
  14440. return link;
  14441. }
  14442. function curveHorizontal(context, x0, y0, x1, y1) {
  14443. context.moveTo(x0, y0);
  14444. context.bezierCurveTo(x0 = (x0 + x1) / 2, y0, x0, y1, x1, y1);
  14445. }
  14446. function curveVertical(context, x0, y0, x1, y1) {
  14447. context.moveTo(x0, y0);
  14448. context.bezierCurveTo(x0, y0 = (y0 + y1) / 2, x1, y0, x1, y1);
  14449. }
  14450. function curveRadial$1(context, x0, y0, x1, y1) {
  14451. var p0 = pointRadial(x0, y0),
  14452. p1 = pointRadial(x0, y0 = (y0 + y1) / 2),
  14453. p2 = pointRadial(x1, y0),
  14454. p3 = pointRadial(x1, y1);
  14455. context.moveTo(p0[0], p0[1]);
  14456. context.bezierCurveTo(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);
  14457. }
  14458. function linkHorizontal() {
  14459. return link(curveHorizontal);
  14460. }
  14461. function linkVertical() {
  14462. return link(curveVertical);
  14463. }
  14464. function linkRadial() {
  14465. var l = link(curveRadial$1);
  14466. l.angle = l.x, delete l.x;
  14467. l.radius = l.y, delete l.y;
  14468. return l;
  14469. }
  14470. var circle = {
  14471. draw: function(context, size) {
  14472. var r = Math.sqrt(size / pi);
  14473. context.moveTo(r, 0);
  14474. context.arc(0, 0, r, 0, tau);
  14475. }
  14476. };
  14477. var cross = {
  14478. draw: function(context, size) {
  14479. var r = Math.sqrt(size / 5) / 2;
  14480. context.moveTo(-3 * r, -r);
  14481. context.lineTo(-r, -r);
  14482. context.lineTo(-r, -3 * r);
  14483. context.lineTo(r, -3 * r);
  14484. context.lineTo(r, -r);
  14485. context.lineTo(3 * r, -r);
  14486. context.lineTo(3 * r, r);
  14487. context.lineTo(r, r);
  14488. context.lineTo(r, 3 * r);
  14489. context.lineTo(-r, 3 * r);
  14490. context.lineTo(-r, r);
  14491. context.lineTo(-3 * r, r);
  14492. context.closePath();
  14493. }
  14494. };
  14495. var tan30 = Math.sqrt(1 / 3);
  14496. var tan30_2 = tan30 * 2;
  14497. var diamond = {
  14498. draw: function(context, size) {
  14499. var y = Math.sqrt(size / tan30_2),
  14500. x = y * tan30;
  14501. context.moveTo(0, -y);
  14502. context.lineTo(x, 0);
  14503. context.lineTo(0, y);
  14504. context.lineTo(-x, 0);
  14505. context.closePath();
  14506. }
  14507. };
  14508. var ka = 0.89081309152928522810;
  14509. var kr = Math.sin(pi / 10) / Math.sin(7 * pi / 10);
  14510. var kx = Math.sin(tau / 10) * kr;
  14511. var ky = -Math.cos(tau / 10) * kr;
  14512. var star = {
  14513. draw: function(context, size) {
  14514. var r = Math.sqrt(size * ka),
  14515. x = kx * r,
  14516. y = ky * r;
  14517. context.moveTo(0, -r);
  14518. context.lineTo(x, y);
  14519. for (var i = 1; i < 5; ++i) {
  14520. var a = tau * i / 5,
  14521. c = Math.cos(a),
  14522. s = Math.sin(a);
  14523. context.lineTo(s * r, -c * r);
  14524. context.lineTo(c * x - s * y, s * x + c * y);
  14525. }
  14526. context.closePath();
  14527. }
  14528. };
  14529. var square = {
  14530. draw: function(context, size) {
  14531. var w = Math.sqrt(size),
  14532. x = -w / 2;
  14533. context.rect(x, x, w, w);
  14534. }
  14535. };
  14536. var sqrt3 = Math.sqrt(3);
  14537. var triangle = {
  14538. draw: function(context, size) {
  14539. var y = -Math.sqrt(size / (sqrt3 * 3));
  14540. context.moveTo(0, y * 2);
  14541. context.lineTo(-sqrt3 * y, -y);
  14542. context.lineTo(sqrt3 * y, -y);
  14543. context.closePath();
  14544. }
  14545. };
  14546. var c = -0.5;
  14547. var s = Math.sqrt(3) / 2;
  14548. var k = 1 / Math.sqrt(12);
  14549. var a = (k / 2 + 1) * 3;
  14550. var wye = {
  14551. draw: function(context, size) {
  14552. var r = Math.sqrt(size / a),
  14553. x0 = r / 2,
  14554. y0 = r * k,
  14555. x1 = x0,
  14556. y1 = r * k + r,
  14557. x2 = -x1,
  14558. y2 = y1;
  14559. context.moveTo(x0, y0);
  14560. context.lineTo(x1, y1);
  14561. context.lineTo(x2, y2);
  14562. context.lineTo(c * x0 - s * y0, s * x0 + c * y0);
  14563. context.lineTo(c * x1 - s * y1, s * x1 + c * y1);
  14564. context.lineTo(c * x2 - s * y2, s * x2 + c * y2);
  14565. context.lineTo(c * x0 + s * y0, c * y0 - s * x0);
  14566. context.lineTo(c * x1 + s * y1, c * y1 - s * x1);
  14567. context.lineTo(c * x2 + s * y2, c * y2 - s * x2);
  14568. context.closePath();
  14569. }
  14570. };
  14571. var symbols = [
  14572. circle,
  14573. cross,
  14574. diamond,
  14575. square,
  14576. star,
  14577. triangle,
  14578. wye
  14579. ];
  14580. var symbol = function() {
  14581. var type = constant(circle),
  14582. size = constant(64),
  14583. context = null;
  14584. function symbol() {
  14585. var buffer;
  14586. if (!context) context = buffer = d3Path.path();
  14587. type.apply(this, arguments).draw(context, +size.apply(this, arguments));
  14588. if (buffer) return context = null, buffer + "" || null;
  14589. }
  14590. symbol.type = function(_) {
  14591. return arguments.length ? (type = typeof _ === "function" ? _ : constant(_), symbol) : type;
  14592. };
  14593. symbol.size = function(_) {
  14594. return arguments.length ? (size = typeof _ === "function" ? _ : constant(+_), symbol) : size;
  14595. };
  14596. symbol.context = function(_) {
  14597. return arguments.length ? (context = _ == null ? null : _, symbol) : context;
  14598. };
  14599. return symbol;
  14600. };
  14601. var noop = function() {};
  14602. function point(that, x, y) {
  14603. that._context.bezierCurveTo(
  14604. (2 * that._x0 + that._x1) / 3,
  14605. (2 * that._y0 + that._y1) / 3,
  14606. (that._x0 + 2 * that._x1) / 3,
  14607. (that._y0 + 2 * that._y1) / 3,
  14608. (that._x0 + 4 * that._x1 + x) / 6,
  14609. (that._y0 + 4 * that._y1 + y) / 6
  14610. );
  14611. }
  14612. function Basis(context) {
  14613. this._context = context;
  14614. }
  14615. Basis.prototype = {
  14616. areaStart: function() {
  14617. this._line = 0;
  14618. },
  14619. areaEnd: function() {
  14620. this._line = NaN;
  14621. },
  14622. lineStart: function() {
  14623. this._x0 = this._x1 =
  14624. this._y0 = this._y1 = NaN;
  14625. this._point = 0;
  14626. },
  14627. lineEnd: function() {
  14628. switch (this._point) {
  14629. case 3: point(this, this._x1, this._y1); // proceed
  14630. case 2: this._context.lineTo(this._x1, this._y1); break;
  14631. }
  14632. if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
  14633. this._line = 1 - this._line;
  14634. },
  14635. point: function(x, y) {
  14636. x = +x, y = +y;
  14637. switch (this._point) {
  14638. case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
  14639. case 1: this._point = 2; break;
  14640. case 2: this._point = 3; this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6); // proceed
  14641. default: point(this, x, y); break;
  14642. }
  14643. this._x0 = this._x1, this._x1 = x;
  14644. this._y0 = this._y1, this._y1 = y;
  14645. }
  14646. };
  14647. var basis = function(context) {
  14648. return new Basis(context);
  14649. };
  14650. function BasisClosed(context) {
  14651. this._context = context;
  14652. }
  14653. BasisClosed.prototype = {
  14654. areaStart: noop,
  14655. areaEnd: noop,
  14656. lineStart: function() {
  14657. this._x0 = this._x1 = this._x2 = this._x3 = this._x4 =
  14658. this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;
  14659. this._point = 0;
  14660. },
  14661. lineEnd: function() {
  14662. switch (this._point) {
  14663. case 1: {
  14664. this._context.moveTo(this._x2, this._y2);
  14665. this._context.closePath();
  14666. break;
  14667. }
  14668. case 2: {
  14669. this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);
  14670. this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);
  14671. this._context.closePath();
  14672. break;
  14673. }
  14674. case 3: {
  14675. this.point(this._x2, this._y2);
  14676. this.point(this._x3, this._y3);
  14677. this.point(this._x4, this._y4);
  14678. break;
  14679. }
  14680. }
  14681. },
  14682. point: function(x, y) {
  14683. x = +x, y = +y;
  14684. switch (this._point) {
  14685. case 0: this._point = 1; this._x2 = x, this._y2 = y; break;
  14686. case 1: this._point = 2; this._x3 = x, this._y3 = y; break;
  14687. case 2: this._point = 3; this._x4 = x, this._y4 = y; this._context.moveTo((this._x0 + 4 * this._x1 + x) / 6, (this._y0 + 4 * this._y1 + y) / 6); break;
  14688. default: point(this, x, y); break;
  14689. }
  14690. this._x0 = this._x1, this._x1 = x;
  14691. this._y0 = this._y1, this._y1 = y;
  14692. }
  14693. };
  14694. var basisClosed = function(context) {
  14695. return new BasisClosed(context);
  14696. };
  14697. function BasisOpen(context) {
  14698. this._context = context;
  14699. }
  14700. BasisOpen.prototype = {
  14701. areaStart: function() {
  14702. this._line = 0;
  14703. },
  14704. areaEnd: function() {
  14705. this._line = NaN;
  14706. },
  14707. lineStart: function() {
  14708. this._x0 = this._x1 =
  14709. this._y0 = this._y1 = NaN;
  14710. this._point = 0;
  14711. },
  14712. lineEnd: function() {
  14713. if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
  14714. this._line = 1 - this._line;
  14715. },
  14716. point: function(x, y) {
  14717. x = +x, y = +y;
  14718. switch (this._point) {
  14719. case 0: this._point = 1; break;
  14720. case 1: this._point = 2; break;
  14721. case 2: this._point = 3; var x0 = (this._x0 + 4 * this._x1 + x) / 6, y0 = (this._y0 + 4 * this._y1 + y) / 6; this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0); break;
  14722. case 3: this._point = 4; // proceed
  14723. default: point(this, x, y); break;
  14724. }
  14725. this._x0 = this._x1, this._x1 = x;
  14726. this._y0 = this._y1, this._y1 = y;
  14727. }
  14728. };
  14729. var basisOpen = function(context) {
  14730. return new BasisOpen(context);
  14731. };
  14732. function Bundle(context, beta) {
  14733. this._basis = new Basis(context);
  14734. this._beta = beta;
  14735. }
  14736. Bundle.prototype = {
  14737. lineStart: function() {
  14738. this._x = [];
  14739. this._y = [];
  14740. this._basis.lineStart();
  14741. },
  14742. lineEnd: function() {
  14743. var x = this._x,
  14744. y = this._y,
  14745. j = x.length - 1;
  14746. if (j > 0) {
  14747. var x0 = x[0],
  14748. y0 = y[0],
  14749. dx = x[j] - x0,
  14750. dy = y[j] - y0,
  14751. i = -1,
  14752. t;
  14753. while (++i <= j) {
  14754. t = i / j;
  14755. this._basis.point(
  14756. this._beta * x[i] + (1 - this._beta) * (x0 + t * dx),
  14757. this._beta * y[i] + (1 - this._beta) * (y0 + t * dy)
  14758. );
  14759. }
  14760. }
  14761. this._x = this._y = null;
  14762. this._basis.lineEnd();
  14763. },
  14764. point: function(x, y) {
  14765. this._x.push(+x);
  14766. this._y.push(+y);
  14767. }
  14768. };
  14769. var bundle = ((function custom(beta) {
  14770. function bundle(context) {
  14771. return beta === 1 ? new Basis(context) : new Bundle(context, beta);
  14772. }
  14773. bundle.beta = function(beta) {
  14774. return custom(+beta);
  14775. };
  14776. return bundle;
  14777. }))(0.85);
  14778. function point$1(that, x, y) {
  14779. that._context.bezierCurveTo(
  14780. that._x1 + that._k * (that._x2 - that._x0),
  14781. that._y1 + that._k * (that._y2 - that._y0),
  14782. that._x2 + that._k * (that._x1 - x),
  14783. that._y2 + that._k * (that._y1 - y),
  14784. that._x2,
  14785. that._y2
  14786. );
  14787. }
  14788. function Cardinal(context, tension) {
  14789. this._context = context;
  14790. this._k = (1 - tension) / 6;
  14791. }
  14792. Cardinal.prototype = {
  14793. areaStart: function() {
  14794. this._line = 0;
  14795. },
  14796. areaEnd: function() {
  14797. this._line = NaN;
  14798. },
  14799. lineStart: function() {
  14800. this._x0 = this._x1 = this._x2 =
  14801. this._y0 = this._y1 = this._y2 = NaN;
  14802. this._point = 0;
  14803. },
  14804. lineEnd: function() {
  14805. switch (this._point) {
  14806. case 2: this._context.lineTo(this._x2, this._y2); break;
  14807. case 3: point$1(this, this._x1, this._y1); break;
  14808. }
  14809. if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
  14810. this._line = 1 - this._line;
  14811. },
  14812. point: function(x, y) {
  14813. x = +x, y = +y;
  14814. switch (this._point) {
  14815. case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
  14816. case 1: this._point = 2; this._x1 = x, this._y1 = y; break;
  14817. case 2: this._point = 3; // proceed
  14818. default: point$1(this, x, y); break;
  14819. }
  14820. this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
  14821. this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  14822. }
  14823. };
  14824. var cardinal = ((function custom(tension) {
  14825. function cardinal(context) {
  14826. return new Cardinal(context, tension);
  14827. }
  14828. cardinal.tension = function(tension) {
  14829. return custom(+tension);
  14830. };
  14831. return cardinal;
  14832. }))(0);
  14833. function CardinalClosed(context, tension) {
  14834. this._context = context;
  14835. this._k = (1 - tension) / 6;
  14836. }
  14837. CardinalClosed.prototype = {
  14838. areaStart: noop,
  14839. areaEnd: noop,
  14840. lineStart: function() {
  14841. this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =
  14842. this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
  14843. this._point = 0;
  14844. },
  14845. lineEnd: function() {
  14846. switch (this._point) {
  14847. case 1: {
  14848. this._context.moveTo(this._x3, this._y3);
  14849. this._context.closePath();
  14850. break;
  14851. }
  14852. case 2: {
  14853. this._context.lineTo(this._x3, this._y3);
  14854. this._context.closePath();
  14855. break;
  14856. }
  14857. case 3: {
  14858. this.point(this._x3, this._y3);
  14859. this.point(this._x4, this._y4);
  14860. this.point(this._x5, this._y5);
  14861. break;
  14862. }
  14863. }
  14864. },
  14865. point: function(x, y) {
  14866. x = +x, y = +y;
  14867. switch (this._point) {
  14868. case 0: this._point = 1; this._x3 = x, this._y3 = y; break;
  14869. case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;
  14870. case 2: this._point = 3; this._x5 = x, this._y5 = y; break;
  14871. default: point$1(this, x, y); break;
  14872. }
  14873. this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
  14874. this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  14875. }
  14876. };
  14877. var cardinalClosed = ((function custom(tension) {
  14878. function cardinal(context) {
  14879. return new CardinalClosed(context, tension);
  14880. }
  14881. cardinal.tension = function(tension) {
  14882. return custom(+tension);
  14883. };
  14884. return cardinal;
  14885. }))(0);
  14886. function CardinalOpen(context, tension) {
  14887. this._context = context;
  14888. this._k = (1 - tension) / 6;
  14889. }
  14890. CardinalOpen.prototype = {
  14891. areaStart: function() {
  14892. this._line = 0;
  14893. },
  14894. areaEnd: function() {
  14895. this._line = NaN;
  14896. },
  14897. lineStart: function() {
  14898. this._x0 = this._x1 = this._x2 =
  14899. this._y0 = this._y1 = this._y2 = NaN;
  14900. this._point = 0;
  14901. },
  14902. lineEnd: function() {
  14903. if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
  14904. this._line = 1 - this._line;
  14905. },
  14906. point: function(x, y) {
  14907. x = +x, y = +y;
  14908. switch (this._point) {
  14909. case 0: this._point = 1; break;
  14910. case 1: this._point = 2; break;
  14911. case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;
  14912. case 3: this._point = 4; // proceed
  14913. default: point$1(this, x, y); break;
  14914. }
  14915. this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
  14916. this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  14917. }
  14918. };
  14919. var cardinalOpen = ((function custom(tension) {
  14920. function cardinal(context) {
  14921. return new CardinalOpen(context, tension);
  14922. }
  14923. cardinal.tension = function(tension) {
  14924. return custom(+tension);
  14925. };
  14926. return cardinal;
  14927. }))(0);
  14928. function point$2(that, x, y) {
  14929. var x1 = that._x1,
  14930. y1 = that._y1,
  14931. x2 = that._x2,
  14932. y2 = that._y2;
  14933. if (that._l01_a > epsilon) {
  14934. var a = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a,
  14935. n = 3 * that._l01_a * (that._l01_a + that._l12_a);
  14936. x1 = (x1 * a - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n;
  14937. y1 = (y1 * a - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;
  14938. }
  14939. if (that._l23_a > epsilon) {
  14940. var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a,
  14941. m = 3 * that._l23_a * (that._l23_a + that._l12_a);
  14942. x2 = (x2 * b + that._x1 * that._l23_2a - x * that._l12_2a) / m;
  14943. y2 = (y2 * b + that._y1 * that._l23_2a - y * that._l12_2a) / m;
  14944. }
  14945. that._context.bezierCurveTo(x1, y1, x2, y2, that._x2, that._y2);
  14946. }
  14947. function CatmullRom(context, alpha) {
  14948. this._context = context;
  14949. this._alpha = alpha;
  14950. }
  14951. CatmullRom.prototype = {
  14952. areaStart: function() {
  14953. this._line = 0;
  14954. },
  14955. areaEnd: function() {
  14956. this._line = NaN;
  14957. },
  14958. lineStart: function() {
  14959. this._x0 = this._x1 = this._x2 =
  14960. this._y0 = this._y1 = this._y2 = NaN;
  14961. this._l01_a = this._l12_a = this._l23_a =
  14962. this._l01_2a = this._l12_2a = this._l23_2a =
  14963. this._point = 0;
  14964. },
  14965. lineEnd: function() {
  14966. switch (this._point) {
  14967. case 2: this._context.lineTo(this._x2, this._y2); break;
  14968. case 3: this.point(this._x2, this._y2); break;
  14969. }
  14970. if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
  14971. this._line = 1 - this._line;
  14972. },
  14973. point: function(x, y) {
  14974. x = +x, y = +y;
  14975. if (this._point) {
  14976. var x23 = this._x2 - x,
  14977. y23 = this._y2 - y;
  14978. this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
  14979. }
  14980. switch (this._point) {
  14981. case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
  14982. case 1: this._point = 2; break;
  14983. case 2: this._point = 3; // proceed
  14984. default: point$2(this, x, y); break;
  14985. }
  14986. this._l01_a = this._l12_a, this._l12_a = this._l23_a;
  14987. this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
  14988. this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
  14989. this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  14990. }
  14991. };
  14992. var catmullRom = ((function custom(alpha) {
  14993. function catmullRom(context) {
  14994. return alpha ? new CatmullRom(context, alpha) : new Cardinal(context, 0);
  14995. }
  14996. catmullRom.alpha = function(alpha) {
  14997. return custom(+alpha);
  14998. };
  14999. return catmullRom;
  15000. }))(0.5);
  15001. function CatmullRomClosed(context, alpha) {
  15002. this._context = context;
  15003. this._alpha = alpha;
  15004. }
  15005. CatmullRomClosed.prototype = {
  15006. areaStart: noop,
  15007. areaEnd: noop,
  15008. lineStart: function() {
  15009. this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =
  15010. this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
  15011. this._l01_a = this._l12_a = this._l23_a =
  15012. this._l01_2a = this._l12_2a = this._l23_2a =
  15013. this._point = 0;
  15014. },
  15015. lineEnd: function() {
  15016. switch (this._point) {
  15017. case 1: {
  15018. this._context.moveTo(this._x3, this._y3);
  15019. this._context.closePath();
  15020. break;
  15021. }
  15022. case 2: {
  15023. this._context.lineTo(this._x3, this._y3);
  15024. this._context.closePath();
  15025. break;
  15026. }
  15027. case 3: {
  15028. this.point(this._x3, this._y3);
  15029. this.point(this._x4, this._y4);
  15030. this.point(this._x5, this._y5);
  15031. break;
  15032. }
  15033. }
  15034. },
  15035. point: function(x, y) {
  15036. x = +x, y = +y;
  15037. if (this._point) {
  15038. var x23 = this._x2 - x,
  15039. y23 = this._y2 - y;
  15040. this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
  15041. }
  15042. switch (this._point) {
  15043. case 0: this._point = 1; this._x3 = x, this._y3 = y; break;
  15044. case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;
  15045. case 2: this._point = 3; this._x5 = x, this._y5 = y; break;
  15046. default: point$2(this, x, y); break;
  15047. }
  15048. this._l01_a = this._l12_a, this._l12_a = this._l23_a;
  15049. this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
  15050. this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
  15051. this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  15052. }
  15053. };
  15054. var catmullRomClosed = ((function custom(alpha) {
  15055. function catmullRom(context) {
  15056. return alpha ? new CatmullRomClosed(context, alpha) : new CardinalClosed(context, 0);
  15057. }
  15058. catmullRom.alpha = function(alpha) {
  15059. return custom(+alpha);
  15060. };
  15061. return catmullRom;
  15062. }))(0.5);
  15063. function CatmullRomOpen(context, alpha) {
  15064. this._context = context;
  15065. this._alpha = alpha;
  15066. }
  15067. CatmullRomOpen.prototype = {
  15068. areaStart: function() {
  15069. this._line = 0;
  15070. },
  15071. areaEnd: function() {
  15072. this._line = NaN;
  15073. },
  15074. lineStart: function() {
  15075. this._x0 = this._x1 = this._x2 =
  15076. this._y0 = this._y1 = this._y2 = NaN;
  15077. this._l01_a = this._l12_a = this._l23_a =
  15078. this._l01_2a = this._l12_2a = this._l23_2a =
  15079. this._point = 0;
  15080. },
  15081. lineEnd: function() {
  15082. if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
  15083. this._line = 1 - this._line;
  15084. },
  15085. point: function(x, y) {
  15086. x = +x, y = +y;
  15087. if (this._point) {
  15088. var x23 = this._x2 - x,
  15089. y23 = this._y2 - y;
  15090. this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
  15091. }
  15092. switch (this._point) {
  15093. case 0: this._point = 1; break;
  15094. case 1: this._point = 2; break;
  15095. case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;
  15096. case 3: this._point = 4; // proceed
  15097. default: point$2(this, x, y); break;
  15098. }
  15099. this._l01_a = this._l12_a, this._l12_a = this._l23_a;
  15100. this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
  15101. this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
  15102. this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  15103. }
  15104. };
  15105. var catmullRomOpen = ((function custom(alpha) {
  15106. function catmullRom(context) {
  15107. return alpha ? new CatmullRomOpen(context, alpha) : new CardinalOpen(context, 0);
  15108. }
  15109. catmullRom.alpha = function(alpha) {
  15110. return custom(+alpha);
  15111. };
  15112. return catmullRom;
  15113. }))(0.5);
  15114. function LinearClosed(context) {
  15115. this._context = context;
  15116. }
  15117. LinearClosed.prototype = {
  15118. areaStart: noop,
  15119. areaEnd: noop,
  15120. lineStart: function() {
  15121. this._point = 0;
  15122. },
  15123. lineEnd: function() {
  15124. if (this._point) this._context.closePath();
  15125. },
  15126. point: function(x, y) {
  15127. x = +x, y = +y;
  15128. if (this._point) this._context.lineTo(x, y);
  15129. else this._point = 1, this._context.moveTo(x, y);
  15130. }
  15131. };
  15132. var linearClosed = function(context) {
  15133. return new LinearClosed(context);
  15134. };
  15135. function sign(x) {
  15136. return x < 0 ? -1 : 1;
  15137. }
  15138. // Calculate the slopes of the tangents (Hermite-type interpolation) based on
  15139. // the following paper: Steffen, M. 1990. A Simple Method for Monotonic
  15140. // Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.
  15141. // NOV(II), P. 443, 1990.
  15142. function slope3(that, x2, y2) {
  15143. var h0 = that._x1 - that._x0,
  15144. h1 = x2 - that._x1,
  15145. s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0),
  15146. s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0),
  15147. p = (s0 * h1 + s1 * h0) / (h0 + h1);
  15148. return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
  15149. }
  15150. // Calculate a one-sided slope.
  15151. function slope2(that, t) {
  15152. var h = that._x1 - that._x0;
  15153. return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
  15154. }
  15155. // According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations
  15156. // "you can express cubic Hermite interpolation in terms of cubic Bézier curves
  15157. // with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1".
  15158. function point$3(that, t0, t1) {
  15159. var x0 = that._x0,
  15160. y0 = that._y0,
  15161. x1 = that._x1,
  15162. y1 = that._y1,
  15163. dx = (x1 - x0) / 3;
  15164. that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);
  15165. }
  15166. function MonotoneX(context) {
  15167. this._context = context;
  15168. }
  15169. MonotoneX.prototype = {
  15170. areaStart: function() {
  15171. this._line = 0;
  15172. },
  15173. areaEnd: function() {
  15174. this._line = NaN;
  15175. },
  15176. lineStart: function() {
  15177. this._x0 = this._x1 =
  15178. this._y0 = this._y1 =
  15179. this._t0 = NaN;
  15180. this._point = 0;
  15181. },
  15182. lineEnd: function() {
  15183. switch (this._point) {
  15184. case 2: this._context.lineTo(this._x1, this._y1); break;
  15185. case 3: point$3(this, this._t0, slope2(this, this._t0)); break;
  15186. }
  15187. if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
  15188. this._line = 1 - this._line;
  15189. },
  15190. point: function(x, y) {
  15191. var t1 = NaN;
  15192. x = +x, y = +y;
  15193. if (x === this._x1 && y === this._y1) return; // Ignore coincident points.
  15194. switch (this._point) {
  15195. case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
  15196. case 1: this._point = 2; break;
  15197. case 2: this._point = 3; point$3(this, slope2(this, t1 = slope3(this, x, y)), t1); break;
  15198. default: point$3(this, this._t0, t1 = slope3(this, x, y)); break;
  15199. }
  15200. this._x0 = this._x1, this._x1 = x;
  15201. this._y0 = this._y1, this._y1 = y;
  15202. this._t0 = t1;
  15203. }
  15204. };
  15205. function MonotoneY(context) {
  15206. this._context = new ReflectContext(context);
  15207. }
  15208. (MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) {
  15209. MonotoneX.prototype.point.call(this, y, x);
  15210. };
  15211. function ReflectContext(context) {
  15212. this._context = context;
  15213. }
  15214. ReflectContext.prototype = {
  15215. moveTo: function(x, y) { this._context.moveTo(y, x); },
  15216. closePath: function() { this._context.closePath(); },
  15217. lineTo: function(x, y) { this._context.lineTo(y, x); },
  15218. bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); }
  15219. };
  15220. function monotoneX(context) {
  15221. return new MonotoneX(context);
  15222. }
  15223. function monotoneY(context) {
  15224. return new MonotoneY(context);
  15225. }
  15226. function Natural(context) {
  15227. this._context = context;
  15228. }
  15229. Natural.prototype = {
  15230. areaStart: function() {
  15231. this._line = 0;
  15232. },
  15233. areaEnd: function() {
  15234. this._line = NaN;
  15235. },
  15236. lineStart: function() {
  15237. this._x = [];
  15238. this._y = [];
  15239. },
  15240. lineEnd: function() {
  15241. var x = this._x,
  15242. y = this._y,
  15243. n = x.length;
  15244. if (n) {
  15245. this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]);
  15246. if (n === 2) {
  15247. this._context.lineTo(x[1], y[1]);
  15248. } else {
  15249. var px = controlPoints(x),
  15250. py = controlPoints(y);
  15251. for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {
  15252. this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);
  15253. }
  15254. }
  15255. }
  15256. if (this._line || (this._line !== 0 && n === 1)) this._context.closePath();
  15257. this._line = 1 - this._line;
  15258. this._x = this._y = null;
  15259. },
  15260. point: function(x, y) {
  15261. this._x.push(+x);
  15262. this._y.push(+y);
  15263. }
  15264. };
  15265. // See https://www.particleincell.com/2012/bezier-splines/ for derivation.
  15266. function controlPoints(x) {
  15267. var i,
  15268. n = x.length - 1,
  15269. m,
  15270. a = new Array(n),
  15271. b = new Array(n),
  15272. r = new Array(n);
  15273. a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1];
  15274. for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];
  15275. a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n];
  15276. for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];
  15277. a[n - 1] = r[n - 1] / b[n - 1];
  15278. for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];
  15279. b[n - 1] = (x[n] + a[n - 1]) / 2;
  15280. for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];
  15281. return [a, b];
  15282. }
  15283. var natural = function(context) {
  15284. return new Natural(context);
  15285. };
  15286. function Step(context, t) {
  15287. this._context = context;
  15288. this._t = t;
  15289. }
  15290. Step.prototype = {
  15291. areaStart: function() {
  15292. this._line = 0;
  15293. },
  15294. areaEnd: function() {
  15295. this._line = NaN;
  15296. },
  15297. lineStart: function() {
  15298. this._x = this._y = NaN;
  15299. this._point = 0;
  15300. },
  15301. lineEnd: function() {
  15302. if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);
  15303. if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
  15304. if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;
  15305. },
  15306. point: function(x, y) {
  15307. x = +x, y = +y;
  15308. switch (this._point) {
  15309. case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
  15310. case 1: this._point = 2; // proceed
  15311. default: {
  15312. if (this._t <= 0) {
  15313. this._context.lineTo(this._x, y);
  15314. this._context.lineTo(x, y);
  15315. } else {
  15316. var x1 = this._x * (1 - this._t) + x * this._t;
  15317. this._context.lineTo(x1, this._y);
  15318. this._context.lineTo(x1, y);
  15319. }
  15320. break;
  15321. }
  15322. }
  15323. this._x = x, this._y = y;
  15324. }
  15325. };
  15326. var step = function(context) {
  15327. return new Step(context, 0.5);
  15328. };
  15329. function stepBefore(context) {
  15330. return new Step(context, 0);
  15331. }
  15332. function stepAfter(context) {
  15333. return new Step(context, 1);
  15334. }
  15335. var none = function(series, order) {
  15336. if (!((n = series.length) > 1)) return;
  15337. for (var i = 1, j, s0, s1 = series[order[0]], n, m = s1.length; i < n; ++i) {
  15338. s0 = s1, s1 = series[order[i]];
  15339. for (j = 0; j < m; ++j) {
  15340. s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];
  15341. }
  15342. }
  15343. };
  15344. var none$1 = function(series) {
  15345. var n = series.length, o = new Array(n);
  15346. while (--n >= 0) o[n] = n;
  15347. return o;
  15348. };
  15349. function stackValue(d, key) {
  15350. return d[key];
  15351. }
  15352. var stack = function() {
  15353. var keys = constant([]),
  15354. order = none$1,
  15355. offset = none,
  15356. value = stackValue;
  15357. function stack(data) {
  15358. var kz = keys.apply(this, arguments),
  15359. i,
  15360. m = data.length,
  15361. n = kz.length,
  15362. sz = new Array(n),
  15363. oz;
  15364. for (i = 0; i < n; ++i) {
  15365. for (var ki = kz[i], si = sz[i] = new Array(m), j = 0, sij; j < m; ++j) {
  15366. si[j] = sij = [0, +value(data[j], ki, j, data)];
  15367. sij.data = data[j];
  15368. }
  15369. si.key = ki;
  15370. }
  15371. for (i = 0, oz = order(sz); i < n; ++i) {
  15372. sz[oz[i]].index = i;
  15373. }
  15374. offset(sz, oz);
  15375. return sz;
  15376. }
  15377. stack.keys = function(_) {
  15378. return arguments.length ? (keys = typeof _ === "function" ? _ : constant(slice.call(_)), stack) : keys;
  15379. };
  15380. stack.value = function(_) {
  15381. return arguments.length ? (value = typeof _ === "function" ? _ : constant(+_), stack) : value;
  15382. };
  15383. stack.order = function(_) {
  15384. return arguments.length ? (order = _ == null ? none$1 : typeof _ === "function" ? _ : constant(slice.call(_)), stack) : order;
  15385. };
  15386. stack.offset = function(_) {
  15387. return arguments.length ? (offset = _ == null ? none : _, stack) : offset;
  15388. };
  15389. return stack;
  15390. };
  15391. var expand = function(series, order) {
  15392. if (!((n = series.length) > 0)) return;
  15393. for (var i, n, j = 0, m = series[0].length, y; j < m; ++j) {
  15394. for (y = i = 0; i < n; ++i) y += series[i][j][1] || 0;
  15395. if (y) for (i = 0; i < n; ++i) series[i][j][1] /= y;
  15396. }
  15397. none(series, order);
  15398. };
  15399. var diverging = function(series, order) {
  15400. if (!((n = series.length) > 1)) return;
  15401. for (var i, j = 0, d, dy, yp, yn, n, m = series[order[0]].length; j < m; ++j) {
  15402. for (yp = yn = 0, i = 0; i < n; ++i) {
  15403. if ((dy = (d = series[order[i]][j])[1] - d[0]) >= 0) {
  15404. d[0] = yp, d[1] = yp += dy;
  15405. } else if (dy < 0) {
  15406. d[1] = yn, d[0] = yn += dy;
  15407. } else {
  15408. d[0] = yp;
  15409. }
  15410. }
  15411. }
  15412. };
  15413. var silhouette = function(series, order) {
  15414. if (!((n = series.length) > 0)) return;
  15415. for (var j = 0, s0 = series[order[0]], n, m = s0.length; j < m; ++j) {
  15416. for (var i = 0, y = 0; i < n; ++i) y += series[i][j][1] || 0;
  15417. s0[j][1] += s0[j][0] = -y / 2;
  15418. }
  15419. none(series, order);
  15420. };
  15421. var wiggle = function(series, order) {
  15422. if (!((n = series.length) > 0) || !((m = (s0 = series[order[0]]).length) > 0)) return;
  15423. for (var y = 0, j = 1, s0, m, n; j < m; ++j) {
  15424. for (var i = 0, s1 = 0, s2 = 0; i < n; ++i) {
  15425. var si = series[order[i]],
  15426. sij0 = si[j][1] || 0,
  15427. sij1 = si[j - 1][1] || 0,
  15428. s3 = (sij0 - sij1) / 2;
  15429. for (var k = 0; k < i; ++k) {
  15430. var sk = series[order[k]],
  15431. skj0 = sk[j][1] || 0,
  15432. skj1 = sk[j - 1][1] || 0;
  15433. s3 += skj0 - skj1;
  15434. }
  15435. s1 += sij0, s2 += s3 * sij0;
  15436. }
  15437. s0[j - 1][1] += s0[j - 1][0] = y;
  15438. if (s1) y -= s2 / s1;
  15439. }
  15440. s0[j - 1][1] += s0[j - 1][0] = y;
  15441. none(series, order);
  15442. };
  15443. var ascending = function(series) {
  15444. var sums = series.map(sum);
  15445. return none$1(series).sort(function(a, b) { return sums[a] - sums[b]; });
  15446. };
  15447. function sum(series) {
  15448. var s = 0, i = -1, n = series.length, v;
  15449. while (++i < n) if (v = +series[i][1]) s += v;
  15450. return s;
  15451. }
  15452. var descending$1 = function(series) {
  15453. return ascending(series).reverse();
  15454. };
  15455. var insideOut = function(series) {
  15456. var n = series.length,
  15457. i,
  15458. j,
  15459. sums = series.map(sum),
  15460. order = none$1(series).sort(function(a, b) { return sums[b] - sums[a]; }),
  15461. top = 0,
  15462. bottom = 0,
  15463. tops = [],
  15464. bottoms = [];
  15465. for (i = 0; i < n; ++i) {
  15466. j = order[i];
  15467. if (top < bottom) {
  15468. top += sums[j];
  15469. tops.push(j);
  15470. } else {
  15471. bottom += sums[j];
  15472. bottoms.push(j);
  15473. }
  15474. }
  15475. return bottoms.reverse().concat(tops);
  15476. };
  15477. var reverse = function(series) {
  15478. return none$1(series).reverse();
  15479. };
  15480. exports.arc = arc;
  15481. exports.area = area;
  15482. exports.line = line;
  15483. exports.pie = pie;
  15484. exports.areaRadial = areaRadial;
  15485. exports.radialArea = areaRadial;
  15486. exports.lineRadial = lineRadial$1;
  15487. exports.radialLine = lineRadial$1;
  15488. exports.pointRadial = pointRadial;
  15489. exports.linkHorizontal = linkHorizontal;
  15490. exports.linkVertical = linkVertical;
  15491. exports.linkRadial = linkRadial;
  15492. exports.symbol = symbol;
  15493. exports.symbols = symbols;
  15494. exports.symbolCircle = circle;
  15495. exports.symbolCross = cross;
  15496. exports.symbolDiamond = diamond;
  15497. exports.symbolSquare = square;
  15498. exports.symbolStar = star;
  15499. exports.symbolTriangle = triangle;
  15500. exports.symbolWye = wye;
  15501. exports.curveBasisClosed = basisClosed;
  15502. exports.curveBasisOpen = basisOpen;
  15503. exports.curveBasis = basis;
  15504. exports.curveBundle = bundle;
  15505. exports.curveCardinalClosed = cardinalClosed;
  15506. exports.curveCardinalOpen = cardinalOpen;
  15507. exports.curveCardinal = cardinal;
  15508. exports.curveCatmullRomClosed = catmullRomClosed;
  15509. exports.curveCatmullRomOpen = catmullRomOpen;
  15510. exports.curveCatmullRom = catmullRom;
  15511. exports.curveLinearClosed = linearClosed;
  15512. exports.curveLinear = curveLinear;
  15513. exports.curveMonotoneX = monotoneX;
  15514. exports.curveMonotoneY = monotoneY;
  15515. exports.curveNatural = natural;
  15516. exports.curveStep = step;
  15517. exports.curveStepAfter = stepAfter;
  15518. exports.curveStepBefore = stepBefore;
  15519. exports.stack = stack;
  15520. exports.stackOffsetExpand = expand;
  15521. exports.stackOffsetDiverging = diverging;
  15522. exports.stackOffsetNone = none;
  15523. exports.stackOffsetSilhouette = silhouette;
  15524. exports.stackOffsetWiggle = wiggle;
  15525. exports.stackOrderAscending = ascending;
  15526. exports.stackOrderDescending = descending$1;
  15527. exports.stackOrderInsideOut = insideOut;
  15528. exports.stackOrderNone = none$1;
  15529. exports.stackOrderReverse = reverse;
  15530. Object.defineProperty(exports, '__esModule', { value: true });
  15531. })));
  15532. },{"d3-path":54}],63:[function(require,module,exports){
  15533. // https://d3js.org/d3-time-format/ Version 2.1.1. Copyright 2017 Mike Bostock.
  15534. (function (global, factory) {
  15535. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-time')) :
  15536. typeof define === 'function' && define.amd ? define(['exports', 'd3-time'], factory) :
  15537. (factory((global.d3 = global.d3 || {}),global.d3));
  15538. }(this, (function (exports,d3Time) { 'use strict';
  15539. function localDate(d) {
  15540. if (0 <= d.y && d.y < 100) {
  15541. var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
  15542. date.setFullYear(d.y);
  15543. return date;
  15544. }
  15545. return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
  15546. }
  15547. function utcDate(d) {
  15548. if (0 <= d.y && d.y < 100) {
  15549. var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
  15550. date.setUTCFullYear(d.y);
  15551. return date;
  15552. }
  15553. return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
  15554. }
  15555. function newYear(y) {
  15556. return {y: y, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0};
  15557. }
  15558. function formatLocale(locale) {
  15559. var locale_dateTime = locale.dateTime,
  15560. locale_date = locale.date,
  15561. locale_time = locale.time,
  15562. locale_periods = locale.periods,
  15563. locale_weekdays = locale.days,
  15564. locale_shortWeekdays = locale.shortDays,
  15565. locale_months = locale.months,
  15566. locale_shortMonths = locale.shortMonths;
  15567. var periodRe = formatRe(locale_periods),
  15568. periodLookup = formatLookup(locale_periods),
  15569. weekdayRe = formatRe(locale_weekdays),
  15570. weekdayLookup = formatLookup(locale_weekdays),
  15571. shortWeekdayRe = formatRe(locale_shortWeekdays),
  15572. shortWeekdayLookup = formatLookup(locale_shortWeekdays),
  15573. monthRe = formatRe(locale_months),
  15574. monthLookup = formatLookup(locale_months),
  15575. shortMonthRe = formatRe(locale_shortMonths),
  15576. shortMonthLookup = formatLookup(locale_shortMonths);
  15577. var formats = {
  15578. "a": formatShortWeekday,
  15579. "A": formatWeekday,
  15580. "b": formatShortMonth,
  15581. "B": formatMonth,
  15582. "c": null,
  15583. "d": formatDayOfMonth,
  15584. "e": formatDayOfMonth,
  15585. "f": formatMicroseconds,
  15586. "H": formatHour24,
  15587. "I": formatHour12,
  15588. "j": formatDayOfYear,
  15589. "L": formatMilliseconds,
  15590. "m": formatMonthNumber,
  15591. "M": formatMinutes,
  15592. "p": formatPeriod,
  15593. "Q": formatUnixTimestamp,
  15594. "s": formatUnixTimestampSeconds,
  15595. "S": formatSeconds,
  15596. "u": formatWeekdayNumberMonday,
  15597. "U": formatWeekNumberSunday,
  15598. "V": formatWeekNumberISO,
  15599. "w": formatWeekdayNumberSunday,
  15600. "W": formatWeekNumberMonday,
  15601. "x": null,
  15602. "X": null,
  15603. "y": formatYear,
  15604. "Y": formatFullYear,
  15605. "Z": formatZone,
  15606. "%": formatLiteralPercent
  15607. };
  15608. var utcFormats = {
  15609. "a": formatUTCShortWeekday,
  15610. "A": formatUTCWeekday,
  15611. "b": formatUTCShortMonth,
  15612. "B": formatUTCMonth,
  15613. "c": null,
  15614. "d": formatUTCDayOfMonth,
  15615. "e": formatUTCDayOfMonth,
  15616. "f": formatUTCMicroseconds,
  15617. "H": formatUTCHour24,
  15618. "I": formatUTCHour12,
  15619. "j": formatUTCDayOfYear,
  15620. "L": formatUTCMilliseconds,
  15621. "m": formatUTCMonthNumber,
  15622. "M": formatUTCMinutes,
  15623. "p": formatUTCPeriod,
  15624. "Q": formatUnixTimestamp,
  15625. "s": formatUnixTimestampSeconds,
  15626. "S": formatUTCSeconds,
  15627. "u": formatUTCWeekdayNumberMonday,
  15628. "U": formatUTCWeekNumberSunday,
  15629. "V": formatUTCWeekNumberISO,
  15630. "w": formatUTCWeekdayNumberSunday,
  15631. "W": formatUTCWeekNumberMonday,
  15632. "x": null,
  15633. "X": null,
  15634. "y": formatUTCYear,
  15635. "Y": formatUTCFullYear,
  15636. "Z": formatUTCZone,
  15637. "%": formatLiteralPercent
  15638. };
  15639. var parses = {
  15640. "a": parseShortWeekday,
  15641. "A": parseWeekday,
  15642. "b": parseShortMonth,
  15643. "B": parseMonth,
  15644. "c": parseLocaleDateTime,
  15645. "d": parseDayOfMonth,
  15646. "e": parseDayOfMonth,
  15647. "f": parseMicroseconds,
  15648. "H": parseHour24,
  15649. "I": parseHour24,
  15650. "j": parseDayOfYear,
  15651. "L": parseMilliseconds,
  15652. "m": parseMonthNumber,
  15653. "M": parseMinutes,
  15654. "p": parsePeriod,
  15655. "Q": parseUnixTimestamp,
  15656. "s": parseUnixTimestampSeconds,
  15657. "S": parseSeconds,
  15658. "u": parseWeekdayNumberMonday,
  15659. "U": parseWeekNumberSunday,
  15660. "V": parseWeekNumberISO,
  15661. "w": parseWeekdayNumberSunday,
  15662. "W": parseWeekNumberMonday,
  15663. "x": parseLocaleDate,
  15664. "X": parseLocaleTime,
  15665. "y": parseYear,
  15666. "Y": parseFullYear,
  15667. "Z": parseZone,
  15668. "%": parseLiteralPercent
  15669. };
  15670. // These recursive directive definitions must be deferred.
  15671. formats.x = newFormat(locale_date, formats);
  15672. formats.X = newFormat(locale_time, formats);
  15673. formats.c = newFormat(locale_dateTime, formats);
  15674. utcFormats.x = newFormat(locale_date, utcFormats);
  15675. utcFormats.X = newFormat(locale_time, utcFormats);
  15676. utcFormats.c = newFormat(locale_dateTime, utcFormats);
  15677. function newFormat(specifier, formats) {
  15678. return function(date) {
  15679. var string = [],
  15680. i = -1,
  15681. j = 0,
  15682. n = specifier.length,
  15683. c,
  15684. pad,
  15685. format;
  15686. if (!(date instanceof Date)) date = new Date(+date);
  15687. while (++i < n) {
  15688. if (specifier.charCodeAt(i) === 37) {
  15689. string.push(specifier.slice(j, i));
  15690. if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);
  15691. else pad = c === "e" ? " " : "0";
  15692. if (format = formats[c]) c = format(date, pad);
  15693. string.push(c);
  15694. j = i + 1;
  15695. }
  15696. }
  15697. string.push(specifier.slice(j, i));
  15698. return string.join("");
  15699. };
  15700. }
  15701. function newParse(specifier, newDate) {
  15702. return function(string) {
  15703. var d = newYear(1900),
  15704. i = parseSpecifier(d, specifier, string += "", 0),
  15705. week, day;
  15706. if (i != string.length) return null;
  15707. // If a UNIX timestamp is specified, return it.
  15708. if ("Q" in d) return new Date(d.Q);
  15709. // The am-pm flag is 0 for AM, and 1 for PM.
  15710. if ("p" in d) d.H = d.H % 12 + d.p * 12;
  15711. // Convert day-of-week and week-of-year to day-of-year.
  15712. if ("V" in d) {
  15713. if (d.V < 1 || d.V > 53) return null;
  15714. if (!("w" in d)) d.w = 1;
  15715. if ("Z" in d) {
  15716. week = utcDate(newYear(d.y)), day = week.getUTCDay();
  15717. week = day > 4 || day === 0 ? d3Time.utcMonday.ceil(week) : d3Time.utcMonday(week);
  15718. week = d3Time.utcDay.offset(week, (d.V - 1) * 7);
  15719. d.y = week.getUTCFullYear();
  15720. d.m = week.getUTCMonth();
  15721. d.d = week.getUTCDate() + (d.w + 6) % 7;
  15722. } else {
  15723. week = newDate(newYear(d.y)), day = week.getDay();
  15724. week = day > 4 || day === 0 ? d3Time.timeMonday.ceil(week) : d3Time.timeMonday(week);
  15725. week = d3Time.timeDay.offset(week, (d.V - 1) * 7);
  15726. d.y = week.getFullYear();
  15727. d.m = week.getMonth();
  15728. d.d = week.getDate() + (d.w + 6) % 7;
  15729. }
  15730. } else if ("W" in d || "U" in d) {
  15731. if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
  15732. day = "Z" in d ? utcDate(newYear(d.y)).getUTCDay() : newDate(newYear(d.y)).getDay();
  15733. d.m = 0;
  15734. d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;
  15735. }
  15736. // If a time zone is specified, all fields are interpreted as UTC and then
  15737. // offset according to the specified time zone.
  15738. if ("Z" in d) {
  15739. d.H += d.Z / 100 | 0;
  15740. d.M += d.Z % 100;
  15741. return utcDate(d);
  15742. }
  15743. // Otherwise, all fields are in local time.
  15744. return newDate(d);
  15745. };
  15746. }
  15747. function parseSpecifier(d, specifier, string, j) {
  15748. var i = 0,
  15749. n = specifier.length,
  15750. m = string.length,
  15751. c,
  15752. parse;
  15753. while (i < n) {
  15754. if (j >= m) return -1;
  15755. c = specifier.charCodeAt(i++);
  15756. if (c === 37) {
  15757. c = specifier.charAt(i++);
  15758. parse = parses[c in pads ? specifier.charAt(i++) : c];
  15759. if (!parse || ((j = parse(d, string, j)) < 0)) return -1;
  15760. } else if (c != string.charCodeAt(j++)) {
  15761. return -1;
  15762. }
  15763. }
  15764. return j;
  15765. }
  15766. function parsePeriod(d, string, i) {
  15767. var n = periodRe.exec(string.slice(i));
  15768. return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  15769. }
  15770. function parseShortWeekday(d, string, i) {
  15771. var n = shortWeekdayRe.exec(string.slice(i));
  15772. return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  15773. }
  15774. function parseWeekday(d, string, i) {
  15775. var n = weekdayRe.exec(string.slice(i));
  15776. return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  15777. }
  15778. function parseShortMonth(d, string, i) {
  15779. var n = shortMonthRe.exec(string.slice(i));
  15780. return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  15781. }
  15782. function parseMonth(d, string, i) {
  15783. var n = monthRe.exec(string.slice(i));
  15784. return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  15785. }
  15786. function parseLocaleDateTime(d, string, i) {
  15787. return parseSpecifier(d, locale_dateTime, string, i);
  15788. }
  15789. function parseLocaleDate(d, string, i) {
  15790. return parseSpecifier(d, locale_date, string, i);
  15791. }
  15792. function parseLocaleTime(d, string, i) {
  15793. return parseSpecifier(d, locale_time, string, i);
  15794. }
  15795. function formatShortWeekday(d) {
  15796. return locale_shortWeekdays[d.getDay()];
  15797. }
  15798. function formatWeekday(d) {
  15799. return locale_weekdays[d.getDay()];
  15800. }
  15801. function formatShortMonth(d) {
  15802. return locale_shortMonths[d.getMonth()];
  15803. }
  15804. function formatMonth(d) {
  15805. return locale_months[d.getMonth()];
  15806. }
  15807. function formatPeriod(d) {
  15808. return locale_periods[+(d.getHours() >= 12)];
  15809. }
  15810. function formatUTCShortWeekday(d) {
  15811. return locale_shortWeekdays[d.getUTCDay()];
  15812. }
  15813. function formatUTCWeekday(d) {
  15814. return locale_weekdays[d.getUTCDay()];
  15815. }
  15816. function formatUTCShortMonth(d) {
  15817. return locale_shortMonths[d.getUTCMonth()];
  15818. }
  15819. function formatUTCMonth(d) {
  15820. return locale_months[d.getUTCMonth()];
  15821. }
  15822. function formatUTCPeriod(d) {
  15823. return locale_periods[+(d.getUTCHours() >= 12)];
  15824. }
  15825. return {
  15826. format: function(specifier) {
  15827. var f = newFormat(specifier += "", formats);
  15828. f.toString = function() { return specifier; };
  15829. return f;
  15830. },
  15831. parse: function(specifier) {
  15832. var p = newParse(specifier += "", localDate);
  15833. p.toString = function() { return specifier; };
  15834. return p;
  15835. },
  15836. utcFormat: function(specifier) {
  15837. var f = newFormat(specifier += "", utcFormats);
  15838. f.toString = function() { return specifier; };
  15839. return f;
  15840. },
  15841. utcParse: function(specifier) {
  15842. var p = newParse(specifier, utcDate);
  15843. p.toString = function() { return specifier; };
  15844. return p;
  15845. }
  15846. };
  15847. }
  15848. var pads = {"-": "", "_": " ", "0": "0"};
  15849. var numberRe = /^\s*\d+/;
  15850. var percentRe = /^%/;
  15851. var requoteRe = /[\\^$*+?|[\]().{}]/g;
  15852. function pad(value, fill, width) {
  15853. var sign = value < 0 ? "-" : "",
  15854. string = (sign ? -value : value) + "",
  15855. length = string.length;
  15856. return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
  15857. }
  15858. function requote(s) {
  15859. return s.replace(requoteRe, "\\$&");
  15860. }
  15861. function formatRe(names) {
  15862. return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
  15863. }
  15864. function formatLookup(names) {
  15865. var map = {}, i = -1, n = names.length;
  15866. while (++i < n) map[names[i].toLowerCase()] = i;
  15867. return map;
  15868. }
  15869. function parseWeekdayNumberSunday(d, string, i) {
  15870. var n = numberRe.exec(string.slice(i, i + 1));
  15871. return n ? (d.w = +n[0], i + n[0].length) : -1;
  15872. }
  15873. function parseWeekdayNumberMonday(d, string, i) {
  15874. var n = numberRe.exec(string.slice(i, i + 1));
  15875. return n ? (d.u = +n[0], i + n[0].length) : -1;
  15876. }
  15877. function parseWeekNumberSunday(d, string, i) {
  15878. var n = numberRe.exec(string.slice(i, i + 2));
  15879. return n ? (d.U = +n[0], i + n[0].length) : -1;
  15880. }
  15881. function parseWeekNumberISO(d, string, i) {
  15882. var n = numberRe.exec(string.slice(i, i + 2));
  15883. return n ? (d.V = +n[0], i + n[0].length) : -1;
  15884. }
  15885. function parseWeekNumberMonday(d, string, i) {
  15886. var n = numberRe.exec(string.slice(i, i + 2));
  15887. return n ? (d.W = +n[0], i + n[0].length) : -1;
  15888. }
  15889. function parseFullYear(d, string, i) {
  15890. var n = numberRe.exec(string.slice(i, i + 4));
  15891. return n ? (d.y = +n[0], i + n[0].length) : -1;
  15892. }
  15893. function parseYear(d, string, i) {
  15894. var n = numberRe.exec(string.slice(i, i + 2));
  15895. return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
  15896. }
  15897. function parseZone(d, string, i) {
  15898. var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
  15899. return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
  15900. }
  15901. function parseMonthNumber(d, string, i) {
  15902. var n = numberRe.exec(string.slice(i, i + 2));
  15903. return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
  15904. }
  15905. function parseDayOfMonth(d, string, i) {
  15906. var n = numberRe.exec(string.slice(i, i + 2));
  15907. return n ? (d.d = +n[0], i + n[0].length) : -1;
  15908. }
  15909. function parseDayOfYear(d, string, i) {
  15910. var n = numberRe.exec(string.slice(i, i + 3));
  15911. return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
  15912. }
  15913. function parseHour24(d, string, i) {
  15914. var n = numberRe.exec(string.slice(i, i + 2));
  15915. return n ? (d.H = +n[0], i + n[0].length) : -1;
  15916. }
  15917. function parseMinutes(d, string, i) {
  15918. var n = numberRe.exec(string.slice(i, i + 2));
  15919. return n ? (d.M = +n[0], i + n[0].length) : -1;
  15920. }
  15921. function parseSeconds(d, string, i) {
  15922. var n = numberRe.exec(string.slice(i, i + 2));
  15923. return n ? (d.S = +n[0], i + n[0].length) : -1;
  15924. }
  15925. function parseMilliseconds(d, string, i) {
  15926. var n = numberRe.exec(string.slice(i, i + 3));
  15927. return n ? (d.L = +n[0], i + n[0].length) : -1;
  15928. }
  15929. function parseMicroseconds(d, string, i) {
  15930. var n = numberRe.exec(string.slice(i, i + 6));
  15931. return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;
  15932. }
  15933. function parseLiteralPercent(d, string, i) {
  15934. var n = percentRe.exec(string.slice(i, i + 1));
  15935. return n ? i + n[0].length : -1;
  15936. }
  15937. function parseUnixTimestamp(d, string, i) {
  15938. var n = numberRe.exec(string.slice(i));
  15939. return n ? (d.Q = +n[0], i + n[0].length) : -1;
  15940. }
  15941. function parseUnixTimestampSeconds(d, string, i) {
  15942. var n = numberRe.exec(string.slice(i));
  15943. return n ? (d.Q = (+n[0]) * 1000, i + n[0].length) : -1;
  15944. }
  15945. function formatDayOfMonth(d, p) {
  15946. return pad(d.getDate(), p, 2);
  15947. }
  15948. function formatHour24(d, p) {
  15949. return pad(d.getHours(), p, 2);
  15950. }
  15951. function formatHour12(d, p) {
  15952. return pad(d.getHours() % 12 || 12, p, 2);
  15953. }
  15954. function formatDayOfYear(d, p) {
  15955. return pad(1 + d3Time.timeDay.count(d3Time.timeYear(d), d), p, 3);
  15956. }
  15957. function formatMilliseconds(d, p) {
  15958. return pad(d.getMilliseconds(), p, 3);
  15959. }
  15960. function formatMicroseconds(d, p) {
  15961. return formatMilliseconds(d, p) + "000";
  15962. }
  15963. function formatMonthNumber(d, p) {
  15964. return pad(d.getMonth() + 1, p, 2);
  15965. }
  15966. function formatMinutes(d, p) {
  15967. return pad(d.getMinutes(), p, 2);
  15968. }
  15969. function formatSeconds(d, p) {
  15970. return pad(d.getSeconds(), p, 2);
  15971. }
  15972. function formatWeekdayNumberMonday(d) {
  15973. var day = d.getDay();
  15974. return day === 0 ? 7 : day;
  15975. }
  15976. function formatWeekNumberSunday(d, p) {
  15977. return pad(d3Time.timeSunday.count(d3Time.timeYear(d), d), p, 2);
  15978. }
  15979. function formatWeekNumberISO(d, p) {
  15980. var day = d.getDay();
  15981. d = (day >= 4 || day === 0) ? d3Time.timeThursday(d) : d3Time.timeThursday.ceil(d);
  15982. return pad(d3Time.timeThursday.count(d3Time.timeYear(d), d) + (d3Time.timeYear(d).getDay() === 4), p, 2);
  15983. }
  15984. function formatWeekdayNumberSunday(d) {
  15985. return d.getDay();
  15986. }
  15987. function formatWeekNumberMonday(d, p) {
  15988. return pad(d3Time.timeMonday.count(d3Time.timeYear(d), d), p, 2);
  15989. }
  15990. function formatYear(d, p) {
  15991. return pad(d.getFullYear() % 100, p, 2);
  15992. }
  15993. function formatFullYear(d, p) {
  15994. return pad(d.getFullYear() % 10000, p, 4);
  15995. }
  15996. function formatZone(d) {
  15997. var z = d.getTimezoneOffset();
  15998. return (z > 0 ? "-" : (z *= -1, "+"))
  15999. + pad(z / 60 | 0, "0", 2)
  16000. + pad(z % 60, "0", 2);
  16001. }
  16002. function formatUTCDayOfMonth(d, p) {
  16003. return pad(d.getUTCDate(), p, 2);
  16004. }
  16005. function formatUTCHour24(d, p) {
  16006. return pad(d.getUTCHours(), p, 2);
  16007. }
  16008. function formatUTCHour12(d, p) {
  16009. return pad(d.getUTCHours() % 12 || 12, p, 2);
  16010. }
  16011. function formatUTCDayOfYear(d, p) {
  16012. return pad(1 + d3Time.utcDay.count(d3Time.utcYear(d), d), p, 3);
  16013. }
  16014. function formatUTCMilliseconds(d, p) {
  16015. return pad(d.getUTCMilliseconds(), p, 3);
  16016. }
  16017. function formatUTCMicroseconds(d, p) {
  16018. return formatUTCMilliseconds(d, p) + "000";
  16019. }
  16020. function formatUTCMonthNumber(d, p) {
  16021. return pad(d.getUTCMonth() + 1, p, 2);
  16022. }
  16023. function formatUTCMinutes(d, p) {
  16024. return pad(d.getUTCMinutes(), p, 2);
  16025. }
  16026. function formatUTCSeconds(d, p) {
  16027. return pad(d.getUTCSeconds(), p, 2);
  16028. }
  16029. function formatUTCWeekdayNumberMonday(d) {
  16030. var dow = d.getUTCDay();
  16031. return dow === 0 ? 7 : dow;
  16032. }
  16033. function formatUTCWeekNumberSunday(d, p) {
  16034. return pad(d3Time.utcSunday.count(d3Time.utcYear(d), d), p, 2);
  16035. }
  16036. function formatUTCWeekNumberISO(d, p) {
  16037. var day = d.getUTCDay();
  16038. d = (day >= 4 || day === 0) ? d3Time.utcThursday(d) : d3Time.utcThursday.ceil(d);
  16039. return pad(d3Time.utcThursday.count(d3Time.utcYear(d), d) + (d3Time.utcYear(d).getUTCDay() === 4), p, 2);
  16040. }
  16041. function formatUTCWeekdayNumberSunday(d) {
  16042. return d.getUTCDay();
  16043. }
  16044. function formatUTCWeekNumberMonday(d, p) {
  16045. return pad(d3Time.utcMonday.count(d3Time.utcYear(d), d), p, 2);
  16046. }
  16047. function formatUTCYear(d, p) {
  16048. return pad(d.getUTCFullYear() % 100, p, 2);
  16049. }
  16050. function formatUTCFullYear(d, p) {
  16051. return pad(d.getUTCFullYear() % 10000, p, 4);
  16052. }
  16053. function formatUTCZone() {
  16054. return "+0000";
  16055. }
  16056. function formatLiteralPercent() {
  16057. return "%";
  16058. }
  16059. function formatUnixTimestamp(d) {
  16060. return +d;
  16061. }
  16062. function formatUnixTimestampSeconds(d) {
  16063. return Math.floor(+d / 1000);
  16064. }
  16065. var locale;
  16066. defaultLocale({
  16067. dateTime: "%x, %X",
  16068. date: "%-m/%-d/%Y",
  16069. time: "%-I:%M:%S %p",
  16070. periods: ["AM", "PM"],
  16071. days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  16072. shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  16073. months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  16074. shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  16075. });
  16076. function defaultLocale(definition) {
  16077. locale = formatLocale(definition);
  16078. exports.timeFormat = locale.format;
  16079. exports.timeParse = locale.parse;
  16080. exports.utcFormat = locale.utcFormat;
  16081. exports.utcParse = locale.utcParse;
  16082. return locale;
  16083. }
  16084. var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ";
  16085. function formatIsoNative(date) {
  16086. return date.toISOString();
  16087. }
  16088. var formatIso = Date.prototype.toISOString
  16089. ? formatIsoNative
  16090. : exports.utcFormat(isoSpecifier);
  16091. function parseIsoNative(string) {
  16092. var date = new Date(string);
  16093. return isNaN(date) ? null : date;
  16094. }
  16095. var parseIso = +new Date("2000-01-01T00:00:00.000Z")
  16096. ? parseIsoNative
  16097. : exports.utcParse(isoSpecifier);
  16098. exports.timeFormatDefaultLocale = defaultLocale;
  16099. exports.timeFormatLocale = formatLocale;
  16100. exports.isoFormat = formatIso;
  16101. exports.isoParse = parseIso;
  16102. Object.defineProperty(exports, '__esModule', { value: true });
  16103. })));
  16104. },{"d3-time":64}],64:[function(require,module,exports){
  16105. // https://d3js.org/d3-time/ Version 1.0.8. Copyright 2017 Mike Bostock.
  16106. (function (global, factory) {
  16107. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  16108. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  16109. (factory((global.d3 = global.d3 || {})));
  16110. }(this, (function (exports) { 'use strict';
  16111. var t0 = new Date;
  16112. var t1 = new Date;
  16113. function newInterval(floori, offseti, count, field) {
  16114. function interval(date) {
  16115. return floori(date = new Date(+date)), date;
  16116. }
  16117. interval.floor = interval;
  16118. interval.ceil = function(date) {
  16119. return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
  16120. };
  16121. interval.round = function(date) {
  16122. var d0 = interval(date),
  16123. d1 = interval.ceil(date);
  16124. return date - d0 < d1 - date ? d0 : d1;
  16125. };
  16126. interval.offset = function(date, step) {
  16127. return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;
  16128. };
  16129. interval.range = function(start, stop, step) {
  16130. var range = [], previous;
  16131. start = interval.ceil(start);
  16132. step = step == null ? 1 : Math.floor(step);
  16133. if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date
  16134. do range.push(previous = new Date(+start)), offseti(start, step), floori(start);
  16135. while (previous < start && start < stop);
  16136. return range;
  16137. };
  16138. interval.filter = function(test) {
  16139. return newInterval(function(date) {
  16140. if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);
  16141. }, function(date, step) {
  16142. if (date >= date) {
  16143. if (step < 0) while (++step <= 0) {
  16144. while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty
  16145. } else while (--step >= 0) {
  16146. while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty
  16147. }
  16148. }
  16149. });
  16150. };
  16151. if (count) {
  16152. interval.count = function(start, end) {
  16153. t0.setTime(+start), t1.setTime(+end);
  16154. floori(t0), floori(t1);
  16155. return Math.floor(count(t0, t1));
  16156. };
  16157. interval.every = function(step) {
  16158. step = Math.floor(step);
  16159. return !isFinite(step) || !(step > 0) ? null
  16160. : !(step > 1) ? interval
  16161. : interval.filter(field
  16162. ? function(d) { return field(d) % step === 0; }
  16163. : function(d) { return interval.count(0, d) % step === 0; });
  16164. };
  16165. }
  16166. return interval;
  16167. }
  16168. var millisecond = newInterval(function() {
  16169. // noop
  16170. }, function(date, step) {
  16171. date.setTime(+date + step);
  16172. }, function(start, end) {
  16173. return end - start;
  16174. });
  16175. // An optimized implementation for this simple case.
  16176. millisecond.every = function(k) {
  16177. k = Math.floor(k);
  16178. if (!isFinite(k) || !(k > 0)) return null;
  16179. if (!(k > 1)) return millisecond;
  16180. return newInterval(function(date) {
  16181. date.setTime(Math.floor(date / k) * k);
  16182. }, function(date, step) {
  16183. date.setTime(+date + step * k);
  16184. }, function(start, end) {
  16185. return (end - start) / k;
  16186. });
  16187. };
  16188. var milliseconds = millisecond.range;
  16189. var durationSecond = 1e3;
  16190. var durationMinute = 6e4;
  16191. var durationHour = 36e5;
  16192. var durationDay = 864e5;
  16193. var durationWeek = 6048e5;
  16194. var second = newInterval(function(date) {
  16195. date.setTime(Math.floor(date / durationSecond) * durationSecond);
  16196. }, function(date, step) {
  16197. date.setTime(+date + step * durationSecond);
  16198. }, function(start, end) {
  16199. return (end - start) / durationSecond;
  16200. }, function(date) {
  16201. return date.getUTCSeconds();
  16202. });
  16203. var seconds = second.range;
  16204. var minute = newInterval(function(date) {
  16205. date.setTime(Math.floor(date / durationMinute) * durationMinute);
  16206. }, function(date, step) {
  16207. date.setTime(+date + step * durationMinute);
  16208. }, function(start, end) {
  16209. return (end - start) / durationMinute;
  16210. }, function(date) {
  16211. return date.getMinutes();
  16212. });
  16213. var minutes = minute.range;
  16214. var hour = newInterval(function(date) {
  16215. var offset = date.getTimezoneOffset() * durationMinute % durationHour;
  16216. if (offset < 0) offset += durationHour;
  16217. date.setTime(Math.floor((+date - offset) / durationHour) * durationHour + offset);
  16218. }, function(date, step) {
  16219. date.setTime(+date + step * durationHour);
  16220. }, function(start, end) {
  16221. return (end - start) / durationHour;
  16222. }, function(date) {
  16223. return date.getHours();
  16224. });
  16225. var hours = hour.range;
  16226. var day = newInterval(function(date) {
  16227. date.setHours(0, 0, 0, 0);
  16228. }, function(date, step) {
  16229. date.setDate(date.getDate() + step);
  16230. }, function(start, end) {
  16231. return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay;
  16232. }, function(date) {
  16233. return date.getDate() - 1;
  16234. });
  16235. var days = day.range;
  16236. function weekday(i) {
  16237. return newInterval(function(date) {
  16238. date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);
  16239. date.setHours(0, 0, 0, 0);
  16240. }, function(date, step) {
  16241. date.setDate(date.getDate() + step * 7);
  16242. }, function(start, end) {
  16243. return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;
  16244. });
  16245. }
  16246. var sunday = weekday(0);
  16247. var monday = weekday(1);
  16248. var tuesday = weekday(2);
  16249. var wednesday = weekday(3);
  16250. var thursday = weekday(4);
  16251. var friday = weekday(5);
  16252. var saturday = weekday(6);
  16253. var sundays = sunday.range;
  16254. var mondays = monday.range;
  16255. var tuesdays = tuesday.range;
  16256. var wednesdays = wednesday.range;
  16257. var thursdays = thursday.range;
  16258. var fridays = friday.range;
  16259. var saturdays = saturday.range;
  16260. var month = newInterval(function(date) {
  16261. date.setDate(1);
  16262. date.setHours(0, 0, 0, 0);
  16263. }, function(date, step) {
  16264. date.setMonth(date.getMonth() + step);
  16265. }, function(start, end) {
  16266. return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
  16267. }, function(date) {
  16268. return date.getMonth();
  16269. });
  16270. var months = month.range;
  16271. var year = newInterval(function(date) {
  16272. date.setMonth(0, 1);
  16273. date.setHours(0, 0, 0, 0);
  16274. }, function(date, step) {
  16275. date.setFullYear(date.getFullYear() + step);
  16276. }, function(start, end) {
  16277. return end.getFullYear() - start.getFullYear();
  16278. }, function(date) {
  16279. return date.getFullYear();
  16280. });
  16281. // An optimized implementation for this simple case.
  16282. year.every = function(k) {
  16283. return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
  16284. date.setFullYear(Math.floor(date.getFullYear() / k) * k);
  16285. date.setMonth(0, 1);
  16286. date.setHours(0, 0, 0, 0);
  16287. }, function(date, step) {
  16288. date.setFullYear(date.getFullYear() + step * k);
  16289. });
  16290. };
  16291. var years = year.range;
  16292. var utcMinute = newInterval(function(date) {
  16293. date.setUTCSeconds(0, 0);
  16294. }, function(date, step) {
  16295. date.setTime(+date + step * durationMinute);
  16296. }, function(start, end) {
  16297. return (end - start) / durationMinute;
  16298. }, function(date) {
  16299. return date.getUTCMinutes();
  16300. });
  16301. var utcMinutes = utcMinute.range;
  16302. var utcHour = newInterval(function(date) {
  16303. date.setUTCMinutes(0, 0, 0);
  16304. }, function(date, step) {
  16305. date.setTime(+date + step * durationHour);
  16306. }, function(start, end) {
  16307. return (end - start) / durationHour;
  16308. }, function(date) {
  16309. return date.getUTCHours();
  16310. });
  16311. var utcHours = utcHour.range;
  16312. var utcDay = newInterval(function(date) {
  16313. date.setUTCHours(0, 0, 0, 0);
  16314. }, function(date, step) {
  16315. date.setUTCDate(date.getUTCDate() + step);
  16316. }, function(start, end) {
  16317. return (end - start) / durationDay;
  16318. }, function(date) {
  16319. return date.getUTCDate() - 1;
  16320. });
  16321. var utcDays = utcDay.range;
  16322. function utcWeekday(i) {
  16323. return newInterval(function(date) {
  16324. date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);
  16325. date.setUTCHours(0, 0, 0, 0);
  16326. }, function(date, step) {
  16327. date.setUTCDate(date.getUTCDate() + step * 7);
  16328. }, function(start, end) {
  16329. return (end - start) / durationWeek;
  16330. });
  16331. }
  16332. var utcSunday = utcWeekday(0);
  16333. var utcMonday = utcWeekday(1);
  16334. var utcTuesday = utcWeekday(2);
  16335. var utcWednesday = utcWeekday(3);
  16336. var utcThursday = utcWeekday(4);
  16337. var utcFriday = utcWeekday(5);
  16338. var utcSaturday = utcWeekday(6);
  16339. var utcSundays = utcSunday.range;
  16340. var utcMondays = utcMonday.range;
  16341. var utcTuesdays = utcTuesday.range;
  16342. var utcWednesdays = utcWednesday.range;
  16343. var utcThursdays = utcThursday.range;
  16344. var utcFridays = utcFriday.range;
  16345. var utcSaturdays = utcSaturday.range;
  16346. var utcMonth = newInterval(function(date) {
  16347. date.setUTCDate(1);
  16348. date.setUTCHours(0, 0, 0, 0);
  16349. }, function(date, step) {
  16350. date.setUTCMonth(date.getUTCMonth() + step);
  16351. }, function(start, end) {
  16352. return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
  16353. }, function(date) {
  16354. return date.getUTCMonth();
  16355. });
  16356. var utcMonths = utcMonth.range;
  16357. var utcYear = newInterval(function(date) {
  16358. date.setUTCMonth(0, 1);
  16359. date.setUTCHours(0, 0, 0, 0);
  16360. }, function(date, step) {
  16361. date.setUTCFullYear(date.getUTCFullYear() + step);
  16362. }, function(start, end) {
  16363. return end.getUTCFullYear() - start.getUTCFullYear();
  16364. }, function(date) {
  16365. return date.getUTCFullYear();
  16366. });
  16367. // An optimized implementation for this simple case.
  16368. utcYear.every = function(k) {
  16369. return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
  16370. date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);
  16371. date.setUTCMonth(0, 1);
  16372. date.setUTCHours(0, 0, 0, 0);
  16373. }, function(date, step) {
  16374. date.setUTCFullYear(date.getUTCFullYear() + step * k);
  16375. });
  16376. };
  16377. var utcYears = utcYear.range;
  16378. exports.timeInterval = newInterval;
  16379. exports.timeMillisecond = millisecond;
  16380. exports.timeMilliseconds = milliseconds;
  16381. exports.utcMillisecond = millisecond;
  16382. exports.utcMilliseconds = milliseconds;
  16383. exports.timeSecond = second;
  16384. exports.timeSeconds = seconds;
  16385. exports.utcSecond = second;
  16386. exports.utcSeconds = seconds;
  16387. exports.timeMinute = minute;
  16388. exports.timeMinutes = minutes;
  16389. exports.timeHour = hour;
  16390. exports.timeHours = hours;
  16391. exports.timeDay = day;
  16392. exports.timeDays = days;
  16393. exports.timeWeek = sunday;
  16394. exports.timeWeeks = sundays;
  16395. exports.timeSunday = sunday;
  16396. exports.timeSundays = sundays;
  16397. exports.timeMonday = monday;
  16398. exports.timeMondays = mondays;
  16399. exports.timeTuesday = tuesday;
  16400. exports.timeTuesdays = tuesdays;
  16401. exports.timeWednesday = wednesday;
  16402. exports.timeWednesdays = wednesdays;
  16403. exports.timeThursday = thursday;
  16404. exports.timeThursdays = thursdays;
  16405. exports.timeFriday = friday;
  16406. exports.timeFridays = fridays;
  16407. exports.timeSaturday = saturday;
  16408. exports.timeSaturdays = saturdays;
  16409. exports.timeMonth = month;
  16410. exports.timeMonths = months;
  16411. exports.timeYear = year;
  16412. exports.timeYears = years;
  16413. exports.utcMinute = utcMinute;
  16414. exports.utcMinutes = utcMinutes;
  16415. exports.utcHour = utcHour;
  16416. exports.utcHours = utcHours;
  16417. exports.utcDay = utcDay;
  16418. exports.utcDays = utcDays;
  16419. exports.utcWeek = utcSunday;
  16420. exports.utcWeeks = utcSundays;
  16421. exports.utcSunday = utcSunday;
  16422. exports.utcSundays = utcSundays;
  16423. exports.utcMonday = utcMonday;
  16424. exports.utcMondays = utcMondays;
  16425. exports.utcTuesday = utcTuesday;
  16426. exports.utcTuesdays = utcTuesdays;
  16427. exports.utcWednesday = utcWednesday;
  16428. exports.utcWednesdays = utcWednesdays;
  16429. exports.utcThursday = utcThursday;
  16430. exports.utcThursdays = utcThursdays;
  16431. exports.utcFriday = utcFriday;
  16432. exports.utcFridays = utcFridays;
  16433. exports.utcSaturday = utcSaturday;
  16434. exports.utcSaturdays = utcSaturdays;
  16435. exports.utcMonth = utcMonth;
  16436. exports.utcMonths = utcMonths;
  16437. exports.utcYear = utcYear;
  16438. exports.utcYears = utcYears;
  16439. Object.defineProperty(exports, '__esModule', { value: true });
  16440. })));
  16441. },{}],65:[function(require,module,exports){
  16442. // https://d3js.org/d3-timer/ Version 1.0.7. Copyright 2017 Mike Bostock.
  16443. (function (global, factory) {
  16444. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  16445. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  16446. (factory((global.d3 = global.d3 || {})));
  16447. }(this, (function (exports) { 'use strict';
  16448. var frame = 0;
  16449. var timeout = 0;
  16450. var interval = 0;
  16451. var pokeDelay = 1000;
  16452. var taskHead;
  16453. var taskTail;
  16454. var clockLast = 0;
  16455. var clockNow = 0;
  16456. var clockSkew = 0;
  16457. var clock = typeof performance === "object" && performance.now ? performance : Date;
  16458. var setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };
  16459. function now() {
  16460. return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
  16461. }
  16462. function clearNow() {
  16463. clockNow = 0;
  16464. }
  16465. function Timer() {
  16466. this._call =
  16467. this._time =
  16468. this._next = null;
  16469. }
  16470. Timer.prototype = timer.prototype = {
  16471. constructor: Timer,
  16472. restart: function(callback, delay, time) {
  16473. if (typeof callback !== "function") throw new TypeError("callback is not a function");
  16474. time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);
  16475. if (!this._next && taskTail !== this) {
  16476. if (taskTail) taskTail._next = this;
  16477. else taskHead = this;
  16478. taskTail = this;
  16479. }
  16480. this._call = callback;
  16481. this._time = time;
  16482. sleep();
  16483. },
  16484. stop: function() {
  16485. if (this._call) {
  16486. this._call = null;
  16487. this._time = Infinity;
  16488. sleep();
  16489. }
  16490. }
  16491. };
  16492. function timer(callback, delay, time) {
  16493. var t = new Timer;
  16494. t.restart(callback, delay, time);
  16495. return t;
  16496. }
  16497. function timerFlush() {
  16498. now(); // Get the current time, if not already set.
  16499. ++frame; // Pretend we’ve set an alarm, if we haven’t already.
  16500. var t = taskHead, e;
  16501. while (t) {
  16502. if ((e = clockNow - t._time) >= 0) t._call.call(null, e);
  16503. t = t._next;
  16504. }
  16505. --frame;
  16506. }
  16507. function wake() {
  16508. clockNow = (clockLast = clock.now()) + clockSkew;
  16509. frame = timeout = 0;
  16510. try {
  16511. timerFlush();
  16512. } finally {
  16513. frame = 0;
  16514. nap();
  16515. clockNow = 0;
  16516. }
  16517. }
  16518. function poke() {
  16519. var now = clock.now(), delay = now - clockLast;
  16520. if (delay > pokeDelay) clockSkew -= delay, clockLast = now;
  16521. }
  16522. function nap() {
  16523. var t0, t1 = taskHead, t2, time = Infinity;
  16524. while (t1) {
  16525. if (t1._call) {
  16526. if (time > t1._time) time = t1._time;
  16527. t0 = t1, t1 = t1._next;
  16528. } else {
  16529. t2 = t1._next, t1._next = null;
  16530. t1 = t0 ? t0._next = t2 : taskHead = t2;
  16531. }
  16532. }
  16533. taskTail = t0;
  16534. sleep(time);
  16535. }
  16536. function sleep(time) {
  16537. if (frame) return; // Soonest alarm already set, or will be.
  16538. if (timeout) timeout = clearTimeout(timeout);
  16539. var delay = time - clockNow; // Strictly less than if we recomputed clockNow.
  16540. if (delay > 24) {
  16541. if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew);
  16542. if (interval) interval = clearInterval(interval);
  16543. } else {
  16544. if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);
  16545. frame = 1, setFrame(wake);
  16546. }
  16547. }
  16548. var timeout$1 = function(callback, delay, time) {
  16549. var t = new Timer;
  16550. delay = delay == null ? 0 : +delay;
  16551. t.restart(function(elapsed) {
  16552. t.stop();
  16553. callback(elapsed + delay);
  16554. }, delay, time);
  16555. return t;
  16556. };
  16557. var interval$1 = function(callback, delay, time) {
  16558. var t = new Timer, total = delay;
  16559. if (delay == null) return t.restart(callback, delay, time), t;
  16560. delay = +delay, time = time == null ? now() : +time;
  16561. t.restart(function tick(elapsed) {
  16562. elapsed += total;
  16563. t.restart(tick, total += delay, time);
  16564. callback(elapsed);
  16565. }, delay, time);
  16566. return t;
  16567. };
  16568. exports.now = now;
  16569. exports.timer = timer;
  16570. exports.timerFlush = timerFlush;
  16571. exports.timeout = timeout$1;
  16572. exports.interval = interval$1;
  16573. Object.defineProperty(exports, '__esModule', { value: true });
  16574. })));
  16575. },{}],66:[function(require,module,exports){
  16576. // https://d3js.org/d3-transition/ Version 1.1.1. Copyright 2017 Mike Bostock.
  16577. (function (global, factory) {
  16578. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-selection'), require('d3-dispatch'), require('d3-timer'), require('d3-interpolate'), require('d3-color'), require('d3-ease')) :
  16579. typeof define === 'function' && define.amd ? define(['exports', 'd3-selection', 'd3-dispatch', 'd3-timer', 'd3-interpolate', 'd3-color', 'd3-ease'], factory) :
  16580. (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3,global.d3,global.d3));
  16581. }(this, (function (exports,d3Selection,d3Dispatch,d3Timer,d3Interpolate,d3Color,d3Ease) { 'use strict';
  16582. var emptyOn = d3Dispatch.dispatch("start", "end", "interrupt");
  16583. var emptyTween = [];
  16584. var CREATED = 0;
  16585. var SCHEDULED = 1;
  16586. var STARTING = 2;
  16587. var STARTED = 3;
  16588. var RUNNING = 4;
  16589. var ENDING = 5;
  16590. var ENDED = 6;
  16591. var schedule = function(node, name, id, index, group, timing) {
  16592. var schedules = node.__transition;
  16593. if (!schedules) node.__transition = {};
  16594. else if (id in schedules) return;
  16595. create(node, id, {
  16596. name: name,
  16597. index: index, // For context during callback.
  16598. group: group, // For context during callback.
  16599. on: emptyOn,
  16600. tween: emptyTween,
  16601. time: timing.time,
  16602. delay: timing.delay,
  16603. duration: timing.duration,
  16604. ease: timing.ease,
  16605. timer: null,
  16606. state: CREATED
  16607. });
  16608. };
  16609. function init(node, id) {
  16610. var schedule = get(node, id);
  16611. if (schedule.state > CREATED) throw new Error("too late; already scheduled");
  16612. return schedule;
  16613. }
  16614. function set(node, id) {
  16615. var schedule = get(node, id);
  16616. if (schedule.state > STARTING) throw new Error("too late; already started");
  16617. return schedule;
  16618. }
  16619. function get(node, id) {
  16620. var schedule = node.__transition;
  16621. if (!schedule || !(schedule = schedule[id])) throw new Error("transition not found");
  16622. return schedule;
  16623. }
  16624. function create(node, id, self) {
  16625. var schedules = node.__transition,
  16626. tween;
  16627. // Initialize the self timer when the transition is created.
  16628. // Note the actual delay is not known until the first callback!
  16629. schedules[id] = self;
  16630. self.timer = d3Timer.timer(schedule, 0, self.time);
  16631. function schedule(elapsed) {
  16632. self.state = SCHEDULED;
  16633. self.timer.restart(start, self.delay, self.time);
  16634. // If the elapsed delay is less than our first sleep, start immediately.
  16635. if (self.delay <= elapsed) start(elapsed - self.delay);
  16636. }
  16637. function start(elapsed) {
  16638. var i, j, n, o;
  16639. // If the state is not SCHEDULED, then we previously errored on start.
  16640. if (self.state !== SCHEDULED) return stop();
  16641. for (i in schedules) {
  16642. o = schedules[i];
  16643. if (o.name !== self.name) continue;
  16644. // While this element already has a starting transition during this frame,
  16645. // defer starting an interrupting transition until that transition has a
  16646. // chance to tick (and possibly end); see d3/d3-transition#54!
  16647. if (o.state === STARTED) return d3Timer.timeout(start);
  16648. // Interrupt the active transition, if any.
  16649. // Dispatch the interrupt event.
  16650. if (o.state === RUNNING) {
  16651. o.state = ENDED;
  16652. o.timer.stop();
  16653. o.on.call("interrupt", node, node.__data__, o.index, o.group);
  16654. delete schedules[i];
  16655. }
  16656. // Cancel any pre-empted transitions. No interrupt event is dispatched
  16657. // because the cancelled transitions never started. Note that this also
  16658. // removes this transition from the pending list!
  16659. else if (+i < id) {
  16660. o.state = ENDED;
  16661. o.timer.stop();
  16662. delete schedules[i];
  16663. }
  16664. }
  16665. // Defer the first tick to end of the current frame; see d3/d3#1576.
  16666. // Note the transition may be canceled after start and before the first tick!
  16667. // Note this must be scheduled before the start event; see d3/d3-transition#16!
  16668. // Assuming this is successful, subsequent callbacks go straight to tick.
  16669. d3Timer.timeout(function() {
  16670. if (self.state === STARTED) {
  16671. self.state = RUNNING;
  16672. self.timer.restart(tick, self.delay, self.time);
  16673. tick(elapsed);
  16674. }
  16675. });
  16676. // Dispatch the start event.
  16677. // Note this must be done before the tween are initialized.
  16678. self.state = STARTING;
  16679. self.on.call("start", node, node.__data__, self.index, self.group);
  16680. if (self.state !== STARTING) return; // interrupted
  16681. self.state = STARTED;
  16682. // Initialize the tween, deleting null tween.
  16683. tween = new Array(n = self.tween.length);
  16684. for (i = 0, j = -1; i < n; ++i) {
  16685. if (o = self.tween[i].value.call(node, node.__data__, self.index, self.group)) {
  16686. tween[++j] = o;
  16687. }
  16688. }
  16689. tween.length = j + 1;
  16690. }
  16691. function tick(elapsed) {
  16692. var t = elapsed < self.duration ? self.ease.call(null, elapsed / self.duration) : (self.timer.restart(stop), self.state = ENDING, 1),
  16693. i = -1,
  16694. n = tween.length;
  16695. while (++i < n) {
  16696. tween[i].call(null, t);
  16697. }
  16698. // Dispatch the end event.
  16699. if (self.state === ENDING) {
  16700. self.on.call("end", node, node.__data__, self.index, self.group);
  16701. stop();
  16702. }
  16703. }
  16704. function stop() {
  16705. self.state = ENDED;
  16706. self.timer.stop();
  16707. delete schedules[id];
  16708. for (var i in schedules) return; // eslint-disable-line no-unused-vars
  16709. delete node.__transition;
  16710. }
  16711. }
  16712. var interrupt = function(node, name) {
  16713. var schedules = node.__transition,
  16714. schedule,
  16715. active,
  16716. empty = true,
  16717. i;
  16718. if (!schedules) return;
  16719. name = name == null ? null : name + "";
  16720. for (i in schedules) {
  16721. if ((schedule = schedules[i]).name !== name) { empty = false; continue; }
  16722. active = schedule.state > STARTING && schedule.state < ENDING;
  16723. schedule.state = ENDED;
  16724. schedule.timer.stop();
  16725. if (active) schedule.on.call("interrupt", node, node.__data__, schedule.index, schedule.group);
  16726. delete schedules[i];
  16727. }
  16728. if (empty) delete node.__transition;
  16729. };
  16730. var selection_interrupt = function(name) {
  16731. return this.each(function() {
  16732. interrupt(this, name);
  16733. });
  16734. };
  16735. function tweenRemove(id, name) {
  16736. var tween0, tween1;
  16737. return function() {
  16738. var schedule = set(this, id),
  16739. tween = schedule.tween;
  16740. // If this node shared tween with the previous node,
  16741. // just assign the updated shared tween and we’re done!
  16742. // Otherwise, copy-on-write.
  16743. if (tween !== tween0) {
  16744. tween1 = tween0 = tween;
  16745. for (var i = 0, n = tween1.length; i < n; ++i) {
  16746. if (tween1[i].name === name) {
  16747. tween1 = tween1.slice();
  16748. tween1.splice(i, 1);
  16749. break;
  16750. }
  16751. }
  16752. }
  16753. schedule.tween = tween1;
  16754. };
  16755. }
  16756. function tweenFunction(id, name, value) {
  16757. var tween0, tween1;
  16758. if (typeof value !== "function") throw new Error;
  16759. return function() {
  16760. var schedule = set(this, id),
  16761. tween = schedule.tween;
  16762. // If this node shared tween with the previous node,
  16763. // just assign the updated shared tween and we’re done!
  16764. // Otherwise, copy-on-write.
  16765. if (tween !== tween0) {
  16766. tween1 = (tween0 = tween).slice();
  16767. for (var t = {name: name, value: value}, i = 0, n = tween1.length; i < n; ++i) {
  16768. if (tween1[i].name === name) {
  16769. tween1[i] = t;
  16770. break;
  16771. }
  16772. }
  16773. if (i === n) tween1.push(t);
  16774. }
  16775. schedule.tween = tween1;
  16776. };
  16777. }
  16778. var transition_tween = function(name, value) {
  16779. var id = this._id;
  16780. name += "";
  16781. if (arguments.length < 2) {
  16782. var tween = get(this.node(), id).tween;
  16783. for (var i = 0, n = tween.length, t; i < n; ++i) {
  16784. if ((t = tween[i]).name === name) {
  16785. return t.value;
  16786. }
  16787. }
  16788. return null;
  16789. }
  16790. return this.each((value == null ? tweenRemove : tweenFunction)(id, name, value));
  16791. };
  16792. function tweenValue(transition, name, value) {
  16793. var id = transition._id;
  16794. transition.each(function() {
  16795. var schedule = set(this, id);
  16796. (schedule.value || (schedule.value = {}))[name] = value.apply(this, arguments);
  16797. });
  16798. return function(node) {
  16799. return get(node, id).value[name];
  16800. };
  16801. }
  16802. var interpolate = function(a, b) {
  16803. var c;
  16804. return (typeof b === "number" ? d3Interpolate.interpolateNumber
  16805. : b instanceof d3Color.color ? d3Interpolate.interpolateRgb
  16806. : (c = d3Color.color(b)) ? (b = c, d3Interpolate.interpolateRgb)
  16807. : d3Interpolate.interpolateString)(a, b);
  16808. };
  16809. function attrRemove(name) {
  16810. return function() {
  16811. this.removeAttribute(name);
  16812. };
  16813. }
  16814. function attrRemoveNS(fullname) {
  16815. return function() {
  16816. this.removeAttributeNS(fullname.space, fullname.local);
  16817. };
  16818. }
  16819. function attrConstant(name, interpolate$$1, value1) {
  16820. var value00,
  16821. interpolate0;
  16822. return function() {
  16823. var value0 = this.getAttribute(name);
  16824. return value0 === value1 ? null
  16825. : value0 === value00 ? interpolate0
  16826. : interpolate0 = interpolate$$1(value00 = value0, value1);
  16827. };
  16828. }
  16829. function attrConstantNS(fullname, interpolate$$1, value1) {
  16830. var value00,
  16831. interpolate0;
  16832. return function() {
  16833. var value0 = this.getAttributeNS(fullname.space, fullname.local);
  16834. return value0 === value1 ? null
  16835. : value0 === value00 ? interpolate0
  16836. : interpolate0 = interpolate$$1(value00 = value0, value1);
  16837. };
  16838. }
  16839. function attrFunction(name, interpolate$$1, value) {
  16840. var value00,
  16841. value10,
  16842. interpolate0;
  16843. return function() {
  16844. var value0, value1 = value(this);
  16845. if (value1 == null) return void this.removeAttribute(name);
  16846. value0 = this.getAttribute(name);
  16847. return value0 === value1 ? null
  16848. : value0 === value00 && value1 === value10 ? interpolate0
  16849. : interpolate0 = interpolate$$1(value00 = value0, value10 = value1);
  16850. };
  16851. }
  16852. function attrFunctionNS(fullname, interpolate$$1, value) {
  16853. var value00,
  16854. value10,
  16855. interpolate0;
  16856. return function() {
  16857. var value0, value1 = value(this);
  16858. if (value1 == null) return void this.removeAttributeNS(fullname.space, fullname.local);
  16859. value0 = this.getAttributeNS(fullname.space, fullname.local);
  16860. return value0 === value1 ? null
  16861. : value0 === value00 && value1 === value10 ? interpolate0
  16862. : interpolate0 = interpolate$$1(value00 = value0, value10 = value1);
  16863. };
  16864. }
  16865. var transition_attr = function(name, value) {
  16866. var fullname = d3Selection.namespace(name), i = fullname === "transform" ? d3Interpolate.interpolateTransformSvg : interpolate;
  16867. return this.attrTween(name, typeof value === "function"
  16868. ? (fullname.local ? attrFunctionNS : attrFunction)(fullname, i, tweenValue(this, "attr." + name, value))
  16869. : value == null ? (fullname.local ? attrRemoveNS : attrRemove)(fullname)
  16870. : (fullname.local ? attrConstantNS : attrConstant)(fullname, i, value + ""));
  16871. };
  16872. function attrTweenNS(fullname, value) {
  16873. function tween() {
  16874. var node = this, i = value.apply(node, arguments);
  16875. return i && function(t) {
  16876. node.setAttributeNS(fullname.space, fullname.local, i(t));
  16877. };
  16878. }
  16879. tween._value = value;
  16880. return tween;
  16881. }
  16882. function attrTween(name, value) {
  16883. function tween() {
  16884. var node = this, i = value.apply(node, arguments);
  16885. return i && function(t) {
  16886. node.setAttribute(name, i(t));
  16887. };
  16888. }
  16889. tween._value = value;
  16890. return tween;
  16891. }
  16892. var transition_attrTween = function(name, value) {
  16893. var key = "attr." + name;
  16894. if (arguments.length < 2) return (key = this.tween(key)) && key._value;
  16895. if (value == null) return this.tween(key, null);
  16896. if (typeof value !== "function") throw new Error;
  16897. var fullname = d3Selection.namespace(name);
  16898. return this.tween(key, (fullname.local ? attrTweenNS : attrTween)(fullname, value));
  16899. };
  16900. function delayFunction(id, value) {
  16901. return function() {
  16902. init(this, id).delay = +value.apply(this, arguments);
  16903. };
  16904. }
  16905. function delayConstant(id, value) {
  16906. return value = +value, function() {
  16907. init(this, id).delay = value;
  16908. };
  16909. }
  16910. var transition_delay = function(value) {
  16911. var id = this._id;
  16912. return arguments.length
  16913. ? this.each((typeof value === "function"
  16914. ? delayFunction
  16915. : delayConstant)(id, value))
  16916. : get(this.node(), id).delay;
  16917. };
  16918. function durationFunction(id, value) {
  16919. return function() {
  16920. set(this, id).duration = +value.apply(this, arguments);
  16921. };
  16922. }
  16923. function durationConstant(id, value) {
  16924. return value = +value, function() {
  16925. set(this, id).duration = value;
  16926. };
  16927. }
  16928. var transition_duration = function(value) {
  16929. var id = this._id;
  16930. return arguments.length
  16931. ? this.each((typeof value === "function"
  16932. ? durationFunction
  16933. : durationConstant)(id, value))
  16934. : get(this.node(), id).duration;
  16935. };
  16936. function easeConstant(id, value) {
  16937. if (typeof value !== "function") throw new Error;
  16938. return function() {
  16939. set(this, id).ease = value;
  16940. };
  16941. }
  16942. var transition_ease = function(value) {
  16943. var id = this._id;
  16944. return arguments.length
  16945. ? this.each(easeConstant(id, value))
  16946. : get(this.node(), id).ease;
  16947. };
  16948. var transition_filter = function(match) {
  16949. if (typeof match !== "function") match = d3Selection.matcher(match);
  16950. for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
  16951. for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
  16952. if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
  16953. subgroup.push(node);
  16954. }
  16955. }
  16956. }
  16957. return new Transition(subgroups, this._parents, this._name, this._id);
  16958. };
  16959. var transition_merge = function(transition) {
  16960. if (transition._id !== this._id) throw new Error;
  16961. for (var groups0 = this._groups, groups1 = transition._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
  16962. for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
  16963. if (node = group0[i] || group1[i]) {
  16964. merge[i] = node;
  16965. }
  16966. }
  16967. }
  16968. for (; j < m0; ++j) {
  16969. merges[j] = groups0[j];
  16970. }
  16971. return new Transition(merges, this._parents, this._name, this._id);
  16972. };
  16973. function start(name) {
  16974. return (name + "").trim().split(/^|\s+/).every(function(t) {
  16975. var i = t.indexOf(".");
  16976. if (i >= 0) t = t.slice(0, i);
  16977. return !t || t === "start";
  16978. });
  16979. }
  16980. function onFunction(id, name, listener) {
  16981. var on0, on1, sit = start(name) ? init : set;
  16982. return function() {
  16983. var schedule = sit(this, id),
  16984. on = schedule.on;
  16985. // If this node shared a dispatch with the previous node,
  16986. // just assign the updated shared dispatch and we’re done!
  16987. // Otherwise, copy-on-write.
  16988. if (on !== on0) (on1 = (on0 = on).copy()).on(name, listener);
  16989. schedule.on = on1;
  16990. };
  16991. }
  16992. var transition_on = function(name, listener) {
  16993. var id = this._id;
  16994. return arguments.length < 2
  16995. ? get(this.node(), id).on.on(name)
  16996. : this.each(onFunction(id, name, listener));
  16997. };
  16998. function removeFunction(id) {
  16999. return function() {
  17000. var parent = this.parentNode;
  17001. for (var i in this.__transition) if (+i !== id) return;
  17002. if (parent) parent.removeChild(this);
  17003. };
  17004. }
  17005. var transition_remove = function() {
  17006. return this.on("end.remove", removeFunction(this._id));
  17007. };
  17008. var transition_select = function(select) {
  17009. var name = this._name,
  17010. id = this._id;
  17011. if (typeof select !== "function") select = d3Selection.selector(select);
  17012. for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
  17013. for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
  17014. if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
  17015. if ("__data__" in node) subnode.__data__ = node.__data__;
  17016. subgroup[i] = subnode;
  17017. schedule(subgroup[i], name, id, i, subgroup, get(node, id));
  17018. }
  17019. }
  17020. }
  17021. return new Transition(subgroups, this._parents, name, id);
  17022. };
  17023. var transition_selectAll = function(select) {
  17024. var name = this._name,
  17025. id = this._id;
  17026. if (typeof select !== "function") select = d3Selection.selectorAll(select);
  17027. for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
  17028. for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
  17029. if (node = group[i]) {
  17030. for (var children = select.call(node, node.__data__, i, group), child, inherit = get(node, id), k = 0, l = children.length; k < l; ++k) {
  17031. if (child = children[k]) {
  17032. schedule(child, name, id, k, children, inherit);
  17033. }
  17034. }
  17035. subgroups.push(children);
  17036. parents.push(node);
  17037. }
  17038. }
  17039. }
  17040. return new Transition(subgroups, parents, name, id);
  17041. };
  17042. var Selection = d3Selection.selection.prototype.constructor;
  17043. var transition_selection = function() {
  17044. return new Selection(this._groups, this._parents);
  17045. };
  17046. function styleRemove(name, interpolate$$1) {
  17047. var value00,
  17048. value10,
  17049. interpolate0;
  17050. return function() {
  17051. var value0 = d3Selection.style(this, name),
  17052. value1 = (this.style.removeProperty(name), d3Selection.style(this, name));
  17053. return value0 === value1 ? null
  17054. : value0 === value00 && value1 === value10 ? interpolate0
  17055. : interpolate0 = interpolate$$1(value00 = value0, value10 = value1);
  17056. };
  17057. }
  17058. function styleRemoveEnd(name) {
  17059. return function() {
  17060. this.style.removeProperty(name);
  17061. };
  17062. }
  17063. function styleConstant(name, interpolate$$1, value1) {
  17064. var value00,
  17065. interpolate0;
  17066. return function() {
  17067. var value0 = d3Selection.style(this, name);
  17068. return value0 === value1 ? null
  17069. : value0 === value00 ? interpolate0
  17070. : interpolate0 = interpolate$$1(value00 = value0, value1);
  17071. };
  17072. }
  17073. function styleFunction(name, interpolate$$1, value) {
  17074. var value00,
  17075. value10,
  17076. interpolate0;
  17077. return function() {
  17078. var value0 = d3Selection.style(this, name),
  17079. value1 = value(this);
  17080. if (value1 == null) value1 = (this.style.removeProperty(name), d3Selection.style(this, name));
  17081. return value0 === value1 ? null
  17082. : value0 === value00 && value1 === value10 ? interpolate0
  17083. : interpolate0 = interpolate$$1(value00 = value0, value10 = value1);
  17084. };
  17085. }
  17086. var transition_style = function(name, value, priority) {
  17087. var i = (name += "") === "transform" ? d3Interpolate.interpolateTransformCss : interpolate;
  17088. return value == null ? this
  17089. .styleTween(name, styleRemove(name, i))
  17090. .on("end.style." + name, styleRemoveEnd(name))
  17091. : this.styleTween(name, typeof value === "function"
  17092. ? styleFunction(name, i, tweenValue(this, "style." + name, value))
  17093. : styleConstant(name, i, value + ""), priority);
  17094. };
  17095. function styleTween(name, value, priority) {
  17096. function tween() {
  17097. var node = this, i = value.apply(node, arguments);
  17098. return i && function(t) {
  17099. node.style.setProperty(name, i(t), priority);
  17100. };
  17101. }
  17102. tween._value = value;
  17103. return tween;
  17104. }
  17105. var transition_styleTween = function(name, value, priority) {
  17106. var key = "style." + (name += "");
  17107. if (arguments.length < 2) return (key = this.tween(key)) && key._value;
  17108. if (value == null) return this.tween(key, null);
  17109. if (typeof value !== "function") throw new Error;
  17110. return this.tween(key, styleTween(name, value, priority == null ? "" : priority));
  17111. };
  17112. function textConstant(value) {
  17113. return function() {
  17114. this.textContent = value;
  17115. };
  17116. }
  17117. function textFunction(value) {
  17118. return function() {
  17119. var value1 = value(this);
  17120. this.textContent = value1 == null ? "" : value1;
  17121. };
  17122. }
  17123. var transition_text = function(value) {
  17124. return this.tween("text", typeof value === "function"
  17125. ? textFunction(tweenValue(this, "text", value))
  17126. : textConstant(value == null ? "" : value + ""));
  17127. };
  17128. var transition_transition = function() {
  17129. var name = this._name,
  17130. id0 = this._id,
  17131. id1 = newId();
  17132. for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {
  17133. for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
  17134. if (node = group[i]) {
  17135. var inherit = get(node, id0);
  17136. schedule(node, name, id1, i, group, {
  17137. time: inherit.time + inherit.delay + inherit.duration,
  17138. delay: 0,
  17139. duration: inherit.duration,
  17140. ease: inherit.ease
  17141. });
  17142. }
  17143. }
  17144. }
  17145. return new Transition(groups, this._parents, name, id1);
  17146. };
  17147. var id = 0;
  17148. function Transition(groups, parents, name, id) {
  17149. this._groups = groups;
  17150. this._parents = parents;
  17151. this._name = name;
  17152. this._id = id;
  17153. }
  17154. function transition(name) {
  17155. return d3Selection.selection().transition(name);
  17156. }
  17157. function newId() {
  17158. return ++id;
  17159. }
  17160. var selection_prototype = d3Selection.selection.prototype;
  17161. Transition.prototype = transition.prototype = {
  17162. constructor: Transition,
  17163. select: transition_select,
  17164. selectAll: transition_selectAll,
  17165. filter: transition_filter,
  17166. merge: transition_merge,
  17167. selection: transition_selection,
  17168. transition: transition_transition,
  17169. call: selection_prototype.call,
  17170. nodes: selection_prototype.nodes,
  17171. node: selection_prototype.node,
  17172. size: selection_prototype.size,
  17173. empty: selection_prototype.empty,
  17174. each: selection_prototype.each,
  17175. on: transition_on,
  17176. attr: transition_attr,
  17177. attrTween: transition_attrTween,
  17178. style: transition_style,
  17179. styleTween: transition_styleTween,
  17180. text: transition_text,
  17181. remove: transition_remove,
  17182. tween: transition_tween,
  17183. delay: transition_delay,
  17184. duration: transition_duration,
  17185. ease: transition_ease
  17186. };
  17187. var defaultTiming = {
  17188. time: null, // Set on use.
  17189. delay: 0,
  17190. duration: 250,
  17191. ease: d3Ease.easeCubicInOut
  17192. };
  17193. function inherit(node, id) {
  17194. var timing;
  17195. while (!(timing = node.__transition) || !(timing = timing[id])) {
  17196. if (!(node = node.parentNode)) {
  17197. return defaultTiming.time = d3Timer.now(), defaultTiming;
  17198. }
  17199. }
  17200. return timing;
  17201. }
  17202. var selection_transition = function(name) {
  17203. var id,
  17204. timing;
  17205. if (name instanceof Transition) {
  17206. id = name._id, name = name._name;
  17207. } else {
  17208. id = newId(), (timing = defaultTiming).time = d3Timer.now(), name = name == null ? null : name + "";
  17209. }
  17210. for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {
  17211. for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
  17212. if (node = group[i]) {
  17213. schedule(node, name, id, i, group, timing || inherit(node, id));
  17214. }
  17215. }
  17216. }
  17217. return new Transition(groups, this._parents, name, id);
  17218. };
  17219. d3Selection.selection.prototype.interrupt = selection_interrupt;
  17220. d3Selection.selection.prototype.transition = selection_transition;
  17221. var root = [null];
  17222. var active = function(node, name) {
  17223. var schedules = node.__transition,
  17224. schedule,
  17225. i;
  17226. if (schedules) {
  17227. name = name == null ? null : name + "";
  17228. for (i in schedules) {
  17229. if ((schedule = schedules[i]).state > SCHEDULED && schedule.name === name) {
  17230. return new Transition([[node]], root, name, +i);
  17231. }
  17232. }
  17233. }
  17234. return null;
  17235. };
  17236. exports.transition = transition;
  17237. exports.active = active;
  17238. exports.interrupt = interrupt;
  17239. Object.defineProperty(exports, '__esModule', { value: true });
  17240. })));
  17241. },{"d3-color":44,"d3-dispatch":45,"d3-ease":48,"d3-interpolate":53,"d3-selection":61,"d3-timer":65}],67:[function(require,module,exports){
  17242. // https://d3js.org/d3-voronoi/ Version 1.1.2. Copyright 2017 Mike Bostock.
  17243. (function (global, factory) {
  17244. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  17245. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  17246. (factory((global.d3 = global.d3 || {})));
  17247. }(this, (function (exports) { 'use strict';
  17248. var constant = function(x) {
  17249. return function() {
  17250. return x;
  17251. };
  17252. };
  17253. function x(d) {
  17254. return d[0];
  17255. }
  17256. function y(d) {
  17257. return d[1];
  17258. }
  17259. function RedBlackTree() {
  17260. this._ = null; // root node
  17261. }
  17262. function RedBlackNode(node) {
  17263. node.U = // parent node
  17264. node.C = // color - true for red, false for black
  17265. node.L = // left node
  17266. node.R = // right node
  17267. node.P = // previous node
  17268. node.N = null; // next node
  17269. }
  17270. RedBlackTree.prototype = {
  17271. constructor: RedBlackTree,
  17272. insert: function(after, node) {
  17273. var parent, grandpa, uncle;
  17274. if (after) {
  17275. node.P = after;
  17276. node.N = after.N;
  17277. if (after.N) after.N.P = node;
  17278. after.N = node;
  17279. if (after.R) {
  17280. after = after.R;
  17281. while (after.L) after = after.L;
  17282. after.L = node;
  17283. } else {
  17284. after.R = node;
  17285. }
  17286. parent = after;
  17287. } else if (this._) {
  17288. after = RedBlackFirst(this._);
  17289. node.P = null;
  17290. node.N = after;
  17291. after.P = after.L = node;
  17292. parent = after;
  17293. } else {
  17294. node.P = node.N = null;
  17295. this._ = node;
  17296. parent = null;
  17297. }
  17298. node.L = node.R = null;
  17299. node.U = parent;
  17300. node.C = true;
  17301. after = node;
  17302. while (parent && parent.C) {
  17303. grandpa = parent.U;
  17304. if (parent === grandpa.L) {
  17305. uncle = grandpa.R;
  17306. if (uncle && uncle.C) {
  17307. parent.C = uncle.C = false;
  17308. grandpa.C = true;
  17309. after = grandpa;
  17310. } else {
  17311. if (after === parent.R) {
  17312. RedBlackRotateLeft(this, parent);
  17313. after = parent;
  17314. parent = after.U;
  17315. }
  17316. parent.C = false;
  17317. grandpa.C = true;
  17318. RedBlackRotateRight(this, grandpa);
  17319. }
  17320. } else {
  17321. uncle = grandpa.L;
  17322. if (uncle && uncle.C) {
  17323. parent.C = uncle.C = false;
  17324. grandpa.C = true;
  17325. after = grandpa;
  17326. } else {
  17327. if (after === parent.L) {
  17328. RedBlackRotateRight(this, parent);
  17329. after = parent;
  17330. parent = after.U;
  17331. }
  17332. parent.C = false;
  17333. grandpa.C = true;
  17334. RedBlackRotateLeft(this, grandpa);
  17335. }
  17336. }
  17337. parent = after.U;
  17338. }
  17339. this._.C = false;
  17340. },
  17341. remove: function(node) {
  17342. if (node.N) node.N.P = node.P;
  17343. if (node.P) node.P.N = node.N;
  17344. node.N = node.P = null;
  17345. var parent = node.U,
  17346. sibling,
  17347. left = node.L,
  17348. right = node.R,
  17349. next,
  17350. red;
  17351. if (!left) next = right;
  17352. else if (!right) next = left;
  17353. else next = RedBlackFirst(right);
  17354. if (parent) {
  17355. if (parent.L === node) parent.L = next;
  17356. else parent.R = next;
  17357. } else {
  17358. this._ = next;
  17359. }
  17360. if (left && right) {
  17361. red = next.C;
  17362. next.C = node.C;
  17363. next.L = left;
  17364. left.U = next;
  17365. if (next !== right) {
  17366. parent = next.U;
  17367. next.U = node.U;
  17368. node = next.R;
  17369. parent.L = node;
  17370. next.R = right;
  17371. right.U = next;
  17372. } else {
  17373. next.U = parent;
  17374. parent = next;
  17375. node = next.R;
  17376. }
  17377. } else {
  17378. red = node.C;
  17379. node = next;
  17380. }
  17381. if (node) node.U = parent;
  17382. if (red) return;
  17383. if (node && node.C) { node.C = false; return; }
  17384. do {
  17385. if (node === this._) break;
  17386. if (node === parent.L) {
  17387. sibling = parent.R;
  17388. if (sibling.C) {
  17389. sibling.C = false;
  17390. parent.C = true;
  17391. RedBlackRotateLeft(this, parent);
  17392. sibling = parent.R;
  17393. }
  17394. if ((sibling.L && sibling.L.C)
  17395. || (sibling.R && sibling.R.C)) {
  17396. if (!sibling.R || !sibling.R.C) {
  17397. sibling.L.C = false;
  17398. sibling.C = true;
  17399. RedBlackRotateRight(this, sibling);
  17400. sibling = parent.R;
  17401. }
  17402. sibling.C = parent.C;
  17403. parent.C = sibling.R.C = false;
  17404. RedBlackRotateLeft(this, parent);
  17405. node = this._;
  17406. break;
  17407. }
  17408. } else {
  17409. sibling = parent.L;
  17410. if (sibling.C) {
  17411. sibling.C = false;
  17412. parent.C = true;
  17413. RedBlackRotateRight(this, parent);
  17414. sibling = parent.L;
  17415. }
  17416. if ((sibling.L && sibling.L.C)
  17417. || (sibling.R && sibling.R.C)) {
  17418. if (!sibling.L || !sibling.L.C) {
  17419. sibling.R.C = false;
  17420. sibling.C = true;
  17421. RedBlackRotateLeft(this, sibling);
  17422. sibling = parent.L;
  17423. }
  17424. sibling.C = parent.C;
  17425. parent.C = sibling.L.C = false;
  17426. RedBlackRotateRight(this, parent);
  17427. node = this._;
  17428. break;
  17429. }
  17430. }
  17431. sibling.C = true;
  17432. node = parent;
  17433. parent = parent.U;
  17434. } while (!node.C);
  17435. if (node) node.C = false;
  17436. }
  17437. };
  17438. function RedBlackRotateLeft(tree, node) {
  17439. var p = node,
  17440. q = node.R,
  17441. parent = p.U;
  17442. if (parent) {
  17443. if (parent.L === p) parent.L = q;
  17444. else parent.R = q;
  17445. } else {
  17446. tree._ = q;
  17447. }
  17448. q.U = parent;
  17449. p.U = q;
  17450. p.R = q.L;
  17451. if (p.R) p.R.U = p;
  17452. q.L = p;
  17453. }
  17454. function RedBlackRotateRight(tree, node) {
  17455. var p = node,
  17456. q = node.L,
  17457. parent = p.U;
  17458. if (parent) {
  17459. if (parent.L === p) parent.L = q;
  17460. else parent.R = q;
  17461. } else {
  17462. tree._ = q;
  17463. }
  17464. q.U = parent;
  17465. p.U = q;
  17466. p.L = q.R;
  17467. if (p.L) p.L.U = p;
  17468. q.R = p;
  17469. }
  17470. function RedBlackFirst(node) {
  17471. while (node.L) node = node.L;
  17472. return node;
  17473. }
  17474. function createEdge(left, right, v0, v1) {
  17475. var edge = [null, null],
  17476. index = edges.push(edge) - 1;
  17477. edge.left = left;
  17478. edge.right = right;
  17479. if (v0) setEdgeEnd(edge, left, right, v0);
  17480. if (v1) setEdgeEnd(edge, right, left, v1);
  17481. cells[left.index].halfedges.push(index);
  17482. cells[right.index].halfedges.push(index);
  17483. return edge;
  17484. }
  17485. function createBorderEdge(left, v0, v1) {
  17486. var edge = [v0, v1];
  17487. edge.left = left;
  17488. return edge;
  17489. }
  17490. function setEdgeEnd(edge, left, right, vertex) {
  17491. if (!edge[0] && !edge[1]) {
  17492. edge[0] = vertex;
  17493. edge.left = left;
  17494. edge.right = right;
  17495. } else if (edge.left === right) {
  17496. edge[1] = vertex;
  17497. } else {
  17498. edge[0] = vertex;
  17499. }
  17500. }
  17501. // Liang–Barsky line clipping.
  17502. function clipEdge(edge, x0, y0, x1, y1) {
  17503. var a = edge[0],
  17504. b = edge[1],
  17505. ax = a[0],
  17506. ay = a[1],
  17507. bx = b[0],
  17508. by = b[1],
  17509. t0 = 0,
  17510. t1 = 1,
  17511. dx = bx - ax,
  17512. dy = by - ay,
  17513. r;
  17514. r = x0 - ax;
  17515. if (!dx && r > 0) return;
  17516. r /= dx;
  17517. if (dx < 0) {
  17518. if (r < t0) return;
  17519. if (r < t1) t1 = r;
  17520. } else if (dx > 0) {
  17521. if (r > t1) return;
  17522. if (r > t0) t0 = r;
  17523. }
  17524. r = x1 - ax;
  17525. if (!dx && r < 0) return;
  17526. r /= dx;
  17527. if (dx < 0) {
  17528. if (r > t1) return;
  17529. if (r > t0) t0 = r;
  17530. } else if (dx > 0) {
  17531. if (r < t0) return;
  17532. if (r < t1) t1 = r;
  17533. }
  17534. r = y0 - ay;
  17535. if (!dy && r > 0) return;
  17536. r /= dy;
  17537. if (dy < 0) {
  17538. if (r < t0) return;
  17539. if (r < t1) t1 = r;
  17540. } else if (dy > 0) {
  17541. if (r > t1) return;
  17542. if (r > t0) t0 = r;
  17543. }
  17544. r = y1 - ay;
  17545. if (!dy && r < 0) return;
  17546. r /= dy;
  17547. if (dy < 0) {
  17548. if (r > t1) return;
  17549. if (r > t0) t0 = r;
  17550. } else if (dy > 0) {
  17551. if (r < t0) return;
  17552. if (r < t1) t1 = r;
  17553. }
  17554. if (!(t0 > 0) && !(t1 < 1)) return true; // TODO Better check?
  17555. if (t0 > 0) edge[0] = [ax + t0 * dx, ay + t0 * dy];
  17556. if (t1 < 1) edge[1] = [ax + t1 * dx, ay + t1 * dy];
  17557. return true;
  17558. }
  17559. function connectEdge(edge, x0, y0, x1, y1) {
  17560. var v1 = edge[1];
  17561. if (v1) return true;
  17562. var v0 = edge[0],
  17563. left = edge.left,
  17564. right = edge.right,
  17565. lx = left[0],
  17566. ly = left[1],
  17567. rx = right[0],
  17568. ry = right[1],
  17569. fx = (lx + rx) / 2,
  17570. fy = (ly + ry) / 2,
  17571. fm,
  17572. fb;
  17573. if (ry === ly) {
  17574. if (fx < x0 || fx >= x1) return;
  17575. if (lx > rx) {
  17576. if (!v0) v0 = [fx, y0];
  17577. else if (v0[1] >= y1) return;
  17578. v1 = [fx, y1];
  17579. } else {
  17580. if (!v0) v0 = [fx, y1];
  17581. else if (v0[1] < y0) return;
  17582. v1 = [fx, y0];
  17583. }
  17584. } else {
  17585. fm = (lx - rx) / (ry - ly);
  17586. fb = fy - fm * fx;
  17587. if (fm < -1 || fm > 1) {
  17588. if (lx > rx) {
  17589. if (!v0) v0 = [(y0 - fb) / fm, y0];
  17590. else if (v0[1] >= y1) return;
  17591. v1 = [(y1 - fb) / fm, y1];
  17592. } else {
  17593. if (!v0) v0 = [(y1 - fb) / fm, y1];
  17594. else if (v0[1] < y0) return;
  17595. v1 = [(y0 - fb) / fm, y0];
  17596. }
  17597. } else {
  17598. if (ly < ry) {
  17599. if (!v0) v0 = [x0, fm * x0 + fb];
  17600. else if (v0[0] >= x1) return;
  17601. v1 = [x1, fm * x1 + fb];
  17602. } else {
  17603. if (!v0) v0 = [x1, fm * x1 + fb];
  17604. else if (v0[0] < x0) return;
  17605. v1 = [x0, fm * x0 + fb];
  17606. }
  17607. }
  17608. }
  17609. edge[0] = v0;
  17610. edge[1] = v1;
  17611. return true;
  17612. }
  17613. function clipEdges(x0, y0, x1, y1) {
  17614. var i = edges.length,
  17615. edge;
  17616. while (i--) {
  17617. if (!connectEdge(edge = edges[i], x0, y0, x1, y1)
  17618. || !clipEdge(edge, x0, y0, x1, y1)
  17619. || !(Math.abs(edge[0][0] - edge[1][0]) > epsilon
  17620. || Math.abs(edge[0][1] - edge[1][1]) > epsilon)) {
  17621. delete edges[i];
  17622. }
  17623. }
  17624. }
  17625. function createCell(site) {
  17626. return cells[site.index] = {
  17627. site: site,
  17628. halfedges: []
  17629. };
  17630. }
  17631. function cellHalfedgeAngle(cell, edge) {
  17632. var site = cell.site,
  17633. va = edge.left,
  17634. vb = edge.right;
  17635. if (site === vb) vb = va, va = site;
  17636. if (vb) return Math.atan2(vb[1] - va[1], vb[0] - va[0]);
  17637. if (site === va) va = edge[1], vb = edge[0];
  17638. else va = edge[0], vb = edge[1];
  17639. return Math.atan2(va[0] - vb[0], vb[1] - va[1]);
  17640. }
  17641. function cellHalfedgeStart(cell, edge) {
  17642. return edge[+(edge.left !== cell.site)];
  17643. }
  17644. function cellHalfedgeEnd(cell, edge) {
  17645. return edge[+(edge.left === cell.site)];
  17646. }
  17647. function sortCellHalfedges() {
  17648. for (var i = 0, n = cells.length, cell, halfedges, j, m; i < n; ++i) {
  17649. if ((cell = cells[i]) && (m = (halfedges = cell.halfedges).length)) {
  17650. var index = new Array(m),
  17651. array = new Array(m);
  17652. for (j = 0; j < m; ++j) index[j] = j, array[j] = cellHalfedgeAngle(cell, edges[halfedges[j]]);
  17653. index.sort(function(i, j) { return array[j] - array[i]; });
  17654. for (j = 0; j < m; ++j) array[j] = halfedges[index[j]];
  17655. for (j = 0; j < m; ++j) halfedges[j] = array[j];
  17656. }
  17657. }
  17658. }
  17659. function clipCells(x0, y0, x1, y1) {
  17660. var nCells = cells.length,
  17661. iCell,
  17662. cell,
  17663. site,
  17664. iHalfedge,
  17665. halfedges,
  17666. nHalfedges,
  17667. start,
  17668. startX,
  17669. startY,
  17670. end,
  17671. endX,
  17672. endY,
  17673. cover = true;
  17674. for (iCell = 0; iCell < nCells; ++iCell) {
  17675. if (cell = cells[iCell]) {
  17676. site = cell.site;
  17677. halfedges = cell.halfedges;
  17678. iHalfedge = halfedges.length;
  17679. // Remove any dangling clipped edges.
  17680. while (iHalfedge--) {
  17681. if (!edges[halfedges[iHalfedge]]) {
  17682. halfedges.splice(iHalfedge, 1);
  17683. }
  17684. }
  17685. // Insert any border edges as necessary.
  17686. iHalfedge = 0, nHalfedges = halfedges.length;
  17687. while (iHalfedge < nHalfedges) {
  17688. end = cellHalfedgeEnd(cell, edges[halfedges[iHalfedge]]), endX = end[0], endY = end[1];
  17689. start = cellHalfedgeStart(cell, edges[halfedges[++iHalfedge % nHalfedges]]), startX = start[0], startY = start[1];
  17690. if (Math.abs(endX - startX) > epsilon || Math.abs(endY - startY) > epsilon) {
  17691. halfedges.splice(iHalfedge, 0, edges.push(createBorderEdge(site, end,
  17692. Math.abs(endX - x0) < epsilon && y1 - endY > epsilon ? [x0, Math.abs(startX - x0) < epsilon ? startY : y1]
  17693. : Math.abs(endY - y1) < epsilon && x1 - endX > epsilon ? [Math.abs(startY - y1) < epsilon ? startX : x1, y1]
  17694. : Math.abs(endX - x1) < epsilon && endY - y0 > epsilon ? [x1, Math.abs(startX - x1) < epsilon ? startY : y0]
  17695. : Math.abs(endY - y0) < epsilon && endX - x0 > epsilon ? [Math.abs(startY - y0) < epsilon ? startX : x0, y0]
  17696. : null)) - 1);
  17697. ++nHalfedges;
  17698. }
  17699. }
  17700. if (nHalfedges) cover = false;
  17701. }
  17702. }
  17703. // If there weren’t any edges, have the closest site cover the extent.
  17704. // It doesn’t matter which corner of the extent we measure!
  17705. if (cover) {
  17706. var dx, dy, d2, dc = Infinity;
  17707. for (iCell = 0, cover = null; iCell < nCells; ++iCell) {
  17708. if (cell = cells[iCell]) {
  17709. site = cell.site;
  17710. dx = site[0] - x0;
  17711. dy = site[1] - y0;
  17712. d2 = dx * dx + dy * dy;
  17713. if (d2 < dc) dc = d2, cover = cell;
  17714. }
  17715. }
  17716. if (cover) {
  17717. var v00 = [x0, y0], v01 = [x0, y1], v11 = [x1, y1], v10 = [x1, y0];
  17718. cover.halfedges.push(
  17719. edges.push(createBorderEdge(site = cover.site, v00, v01)) - 1,
  17720. edges.push(createBorderEdge(site, v01, v11)) - 1,
  17721. edges.push(createBorderEdge(site, v11, v10)) - 1,
  17722. edges.push(createBorderEdge(site, v10, v00)) - 1
  17723. );
  17724. }
  17725. }
  17726. // Lastly delete any cells with no edges; these were entirely clipped.
  17727. for (iCell = 0; iCell < nCells; ++iCell) {
  17728. if (cell = cells[iCell]) {
  17729. if (!cell.halfedges.length) {
  17730. delete cells[iCell];
  17731. }
  17732. }
  17733. }
  17734. }
  17735. var circlePool = [];
  17736. var firstCircle;
  17737. function Circle() {
  17738. RedBlackNode(this);
  17739. this.x =
  17740. this.y =
  17741. this.arc =
  17742. this.site =
  17743. this.cy = null;
  17744. }
  17745. function attachCircle(arc) {
  17746. var lArc = arc.P,
  17747. rArc = arc.N;
  17748. if (!lArc || !rArc) return;
  17749. var lSite = lArc.site,
  17750. cSite = arc.site,
  17751. rSite = rArc.site;
  17752. if (lSite === rSite) return;
  17753. var bx = cSite[0],
  17754. by = cSite[1],
  17755. ax = lSite[0] - bx,
  17756. ay = lSite[1] - by,
  17757. cx = rSite[0] - bx,
  17758. cy = rSite[1] - by;
  17759. var d = 2 * (ax * cy - ay * cx);
  17760. if (d >= -epsilon2) return;
  17761. var ha = ax * ax + ay * ay,
  17762. hc = cx * cx + cy * cy,
  17763. x = (cy * ha - ay * hc) / d,
  17764. y = (ax * hc - cx * ha) / d;
  17765. var circle = circlePool.pop() || new Circle;
  17766. circle.arc = arc;
  17767. circle.site = cSite;
  17768. circle.x = x + bx;
  17769. circle.y = (circle.cy = y + by) + Math.sqrt(x * x + y * y); // y bottom
  17770. arc.circle = circle;
  17771. var before = null,
  17772. node = circles._;
  17773. while (node) {
  17774. if (circle.y < node.y || (circle.y === node.y && circle.x <= node.x)) {
  17775. if (node.L) node = node.L;
  17776. else { before = node.P; break; }
  17777. } else {
  17778. if (node.R) node = node.R;
  17779. else { before = node; break; }
  17780. }
  17781. }
  17782. circles.insert(before, circle);
  17783. if (!before) firstCircle = circle;
  17784. }
  17785. function detachCircle(arc) {
  17786. var circle = arc.circle;
  17787. if (circle) {
  17788. if (!circle.P) firstCircle = circle.N;
  17789. circles.remove(circle);
  17790. circlePool.push(circle);
  17791. RedBlackNode(circle);
  17792. arc.circle = null;
  17793. }
  17794. }
  17795. var beachPool = [];
  17796. function Beach() {
  17797. RedBlackNode(this);
  17798. this.edge =
  17799. this.site =
  17800. this.circle = null;
  17801. }
  17802. function createBeach(site) {
  17803. var beach = beachPool.pop() || new Beach;
  17804. beach.site = site;
  17805. return beach;
  17806. }
  17807. function detachBeach(beach) {
  17808. detachCircle(beach);
  17809. beaches.remove(beach);
  17810. beachPool.push(beach);
  17811. RedBlackNode(beach);
  17812. }
  17813. function removeBeach(beach) {
  17814. var circle = beach.circle,
  17815. x = circle.x,
  17816. y = circle.cy,
  17817. vertex = [x, y],
  17818. previous = beach.P,
  17819. next = beach.N,
  17820. disappearing = [beach];
  17821. detachBeach(beach);
  17822. var lArc = previous;
  17823. while (lArc.circle
  17824. && Math.abs(x - lArc.circle.x) < epsilon
  17825. && Math.abs(y - lArc.circle.cy) < epsilon) {
  17826. previous = lArc.P;
  17827. disappearing.unshift(lArc);
  17828. detachBeach(lArc);
  17829. lArc = previous;
  17830. }
  17831. disappearing.unshift(lArc);
  17832. detachCircle(lArc);
  17833. var rArc = next;
  17834. while (rArc.circle
  17835. && Math.abs(x - rArc.circle.x) < epsilon
  17836. && Math.abs(y - rArc.circle.cy) < epsilon) {
  17837. next = rArc.N;
  17838. disappearing.push(rArc);
  17839. detachBeach(rArc);
  17840. rArc = next;
  17841. }
  17842. disappearing.push(rArc);
  17843. detachCircle(rArc);
  17844. var nArcs = disappearing.length,
  17845. iArc;
  17846. for (iArc = 1; iArc < nArcs; ++iArc) {
  17847. rArc = disappearing[iArc];
  17848. lArc = disappearing[iArc - 1];
  17849. setEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
  17850. }
  17851. lArc = disappearing[0];
  17852. rArc = disappearing[nArcs - 1];
  17853. rArc.edge = createEdge(lArc.site, rArc.site, null, vertex);
  17854. attachCircle(lArc);
  17855. attachCircle(rArc);
  17856. }
  17857. function addBeach(site) {
  17858. var x = site[0],
  17859. directrix = site[1],
  17860. lArc,
  17861. rArc,
  17862. dxl,
  17863. dxr,
  17864. node = beaches._;
  17865. while (node) {
  17866. dxl = leftBreakPoint(node, directrix) - x;
  17867. if (dxl > epsilon) node = node.L; else {
  17868. dxr = x - rightBreakPoint(node, directrix);
  17869. if (dxr > epsilon) {
  17870. if (!node.R) {
  17871. lArc = node;
  17872. break;
  17873. }
  17874. node = node.R;
  17875. } else {
  17876. if (dxl > -epsilon) {
  17877. lArc = node.P;
  17878. rArc = node;
  17879. } else if (dxr > -epsilon) {
  17880. lArc = node;
  17881. rArc = node.N;
  17882. } else {
  17883. lArc = rArc = node;
  17884. }
  17885. break;
  17886. }
  17887. }
  17888. }
  17889. createCell(site);
  17890. var newArc = createBeach(site);
  17891. beaches.insert(lArc, newArc);
  17892. if (!lArc && !rArc) return;
  17893. if (lArc === rArc) {
  17894. detachCircle(lArc);
  17895. rArc = createBeach(lArc.site);
  17896. beaches.insert(newArc, rArc);
  17897. newArc.edge = rArc.edge = createEdge(lArc.site, newArc.site);
  17898. attachCircle(lArc);
  17899. attachCircle(rArc);
  17900. return;
  17901. }
  17902. if (!rArc) { // && lArc
  17903. newArc.edge = createEdge(lArc.site, newArc.site);
  17904. return;
  17905. }
  17906. // else lArc !== rArc
  17907. detachCircle(lArc);
  17908. detachCircle(rArc);
  17909. var lSite = lArc.site,
  17910. ax = lSite[0],
  17911. ay = lSite[1],
  17912. bx = site[0] - ax,
  17913. by = site[1] - ay,
  17914. rSite = rArc.site,
  17915. cx = rSite[0] - ax,
  17916. cy = rSite[1] - ay,
  17917. d = 2 * (bx * cy - by * cx),
  17918. hb = bx * bx + by * by,
  17919. hc = cx * cx + cy * cy,
  17920. vertex = [(cy * hb - by * hc) / d + ax, (bx * hc - cx * hb) / d + ay];
  17921. setEdgeEnd(rArc.edge, lSite, rSite, vertex);
  17922. newArc.edge = createEdge(lSite, site, null, vertex);
  17923. rArc.edge = createEdge(site, rSite, null, vertex);
  17924. attachCircle(lArc);
  17925. attachCircle(rArc);
  17926. }
  17927. function leftBreakPoint(arc, directrix) {
  17928. var site = arc.site,
  17929. rfocx = site[0],
  17930. rfocy = site[1],
  17931. pby2 = rfocy - directrix;
  17932. if (!pby2) return rfocx;
  17933. var lArc = arc.P;
  17934. if (!lArc) return -Infinity;
  17935. site = lArc.site;
  17936. var lfocx = site[0],
  17937. lfocy = site[1],
  17938. plby2 = lfocy - directrix;
  17939. if (!plby2) return lfocx;
  17940. var hl = lfocx - rfocx,
  17941. aby2 = 1 / pby2 - 1 / plby2,
  17942. b = hl / plby2;
  17943. if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
  17944. return (rfocx + lfocx) / 2;
  17945. }
  17946. function rightBreakPoint(arc, directrix) {
  17947. var rArc = arc.N;
  17948. if (rArc) return leftBreakPoint(rArc, directrix);
  17949. var site = arc.site;
  17950. return site[1] === directrix ? site[0] : Infinity;
  17951. }
  17952. var epsilon = 1e-6;
  17953. var epsilon2 = 1e-12;
  17954. var beaches;
  17955. var cells;
  17956. var circles;
  17957. var edges;
  17958. function triangleArea(a, b, c) {
  17959. return (a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1]);
  17960. }
  17961. function lexicographic(a, b) {
  17962. return b[1] - a[1]
  17963. || b[0] - a[0];
  17964. }
  17965. function Diagram(sites, extent) {
  17966. var site = sites.sort(lexicographic).pop(),
  17967. x,
  17968. y,
  17969. circle;
  17970. edges = [];
  17971. cells = new Array(sites.length);
  17972. beaches = new RedBlackTree;
  17973. circles = new RedBlackTree;
  17974. while (true) {
  17975. circle = firstCircle;
  17976. if (site && (!circle || site[1] < circle.y || (site[1] === circle.y && site[0] < circle.x))) {
  17977. if (site[0] !== x || site[1] !== y) {
  17978. addBeach(site);
  17979. x = site[0], y = site[1];
  17980. }
  17981. site = sites.pop();
  17982. } else if (circle) {
  17983. removeBeach(circle.arc);
  17984. } else {
  17985. break;
  17986. }
  17987. }
  17988. sortCellHalfedges();
  17989. if (extent) {
  17990. var x0 = +extent[0][0],
  17991. y0 = +extent[0][1],
  17992. x1 = +extent[1][0],
  17993. y1 = +extent[1][1];
  17994. clipEdges(x0, y0, x1, y1);
  17995. clipCells(x0, y0, x1, y1);
  17996. }
  17997. this.edges = edges;
  17998. this.cells = cells;
  17999. beaches =
  18000. circles =
  18001. edges =
  18002. cells = null;
  18003. }
  18004. Diagram.prototype = {
  18005. constructor: Diagram,
  18006. polygons: function() {
  18007. var edges = this.edges;
  18008. return this.cells.map(function(cell) {
  18009. var polygon = cell.halfedges.map(function(i) { return cellHalfedgeStart(cell, edges[i]); });
  18010. polygon.data = cell.site.data;
  18011. return polygon;
  18012. });
  18013. },
  18014. triangles: function() {
  18015. var triangles = [],
  18016. edges = this.edges;
  18017. this.cells.forEach(function(cell, i) {
  18018. if (!(m = (halfedges = cell.halfedges).length)) return;
  18019. var site = cell.site,
  18020. halfedges,
  18021. j = -1,
  18022. m,
  18023. s0,
  18024. e1 = edges[halfedges[m - 1]],
  18025. s1 = e1.left === site ? e1.right : e1.left;
  18026. while (++j < m) {
  18027. s0 = s1;
  18028. e1 = edges[halfedges[j]];
  18029. s1 = e1.left === site ? e1.right : e1.left;
  18030. if (s0 && s1 && i < s0.index && i < s1.index && triangleArea(site, s0, s1) < 0) {
  18031. triangles.push([site.data, s0.data, s1.data]);
  18032. }
  18033. }
  18034. });
  18035. return triangles;
  18036. },
  18037. links: function() {
  18038. return this.edges.filter(function(edge) {
  18039. return edge.right;
  18040. }).map(function(edge) {
  18041. return {
  18042. source: edge.left.data,
  18043. target: edge.right.data
  18044. };
  18045. });
  18046. },
  18047. find: function(x, y, radius) {
  18048. var that = this, i0, i1 = that._found || 0, n = that.cells.length, cell;
  18049. // Use the previously-found cell, or start with an arbitrary one.
  18050. while (!(cell = that.cells[i1])) if (++i1 >= n) return null;
  18051. var dx = x - cell.site[0], dy = y - cell.site[1], d2 = dx * dx + dy * dy;
  18052. // Traverse the half-edges to find a closer cell, if any.
  18053. do {
  18054. cell = that.cells[i0 = i1], i1 = null;
  18055. cell.halfedges.forEach(function(e) {
  18056. var edge = that.edges[e], v = edge.left;
  18057. if ((v === cell.site || !v) && !(v = edge.right)) return;
  18058. var vx = x - v[0], vy = y - v[1], v2 = vx * vx + vy * vy;
  18059. if (v2 < d2) d2 = v2, i1 = v.index;
  18060. });
  18061. } while (i1 !== null);
  18062. that._found = i0;
  18063. return radius == null || d2 <= radius * radius ? cell.site : null;
  18064. }
  18065. };
  18066. var voronoi = function() {
  18067. var x$$1 = x,
  18068. y$$1 = y,
  18069. extent = null;
  18070. function voronoi(data) {
  18071. return new Diagram(data.map(function(d, i) {
  18072. var s = [Math.round(x$$1(d, i, data) / epsilon) * epsilon, Math.round(y$$1(d, i, data) / epsilon) * epsilon];
  18073. s.index = i;
  18074. s.data = d;
  18075. return s;
  18076. }), extent);
  18077. }
  18078. voronoi.polygons = function(data) {
  18079. return voronoi(data).polygons();
  18080. };
  18081. voronoi.links = function(data) {
  18082. return voronoi(data).links();
  18083. };
  18084. voronoi.triangles = function(data) {
  18085. return voronoi(data).triangles();
  18086. };
  18087. voronoi.x = function(_) {
  18088. return arguments.length ? (x$$1 = typeof _ === "function" ? _ : constant(+_), voronoi) : x$$1;
  18089. };
  18090. voronoi.y = function(_) {
  18091. return arguments.length ? (y$$1 = typeof _ === "function" ? _ : constant(+_), voronoi) : y$$1;
  18092. };
  18093. voronoi.extent = function(_) {
  18094. return arguments.length ? (extent = _ == null ? null : [[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]], voronoi) : extent && [[extent[0][0], extent[0][1]], [extent[1][0], extent[1][1]]];
  18095. };
  18096. voronoi.size = function(_) {
  18097. return arguments.length ? (extent = _ == null ? null : [[0, 0], [+_[0], +_[1]]], voronoi) : extent && [extent[1][0] - extent[0][0], extent[1][1] - extent[0][1]];
  18098. };
  18099. return voronoi;
  18100. };
  18101. exports.voronoi = voronoi;
  18102. Object.defineProperty(exports, '__esModule', { value: true });
  18103. })));
  18104. },{}],68:[function(require,module,exports){
  18105. // https://d3js.org/d3-zoom/ Version 1.7.1. Copyright 2017 Mike Bostock.
  18106. (function (global, factory) {
  18107. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-dispatch'), require('d3-drag'), require('d3-interpolate'), require('d3-selection'), require('d3-transition')) :
  18108. typeof define === 'function' && define.amd ? define(['exports', 'd3-dispatch', 'd3-drag', 'd3-interpolate', 'd3-selection', 'd3-transition'], factory) :
  18109. (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3,global.d3));
  18110. }(this, (function (exports,d3Dispatch,d3Drag,d3Interpolate,d3Selection,d3Transition) { 'use strict';
  18111. var constant = function(x) {
  18112. return function() {
  18113. return x;
  18114. };
  18115. };
  18116. function ZoomEvent(target, type, transform) {
  18117. this.target = target;
  18118. this.type = type;
  18119. this.transform = transform;
  18120. }
  18121. function Transform(k, x, y) {
  18122. this.k = k;
  18123. this.x = x;
  18124. this.y = y;
  18125. }
  18126. Transform.prototype = {
  18127. constructor: Transform,
  18128. scale: function(k) {
  18129. return k === 1 ? this : new Transform(this.k * k, this.x, this.y);
  18130. },
  18131. translate: function(x, y) {
  18132. return x === 0 & y === 0 ? this : new Transform(this.k, this.x + this.k * x, this.y + this.k * y);
  18133. },
  18134. apply: function(point) {
  18135. return [point[0] * this.k + this.x, point[1] * this.k + this.y];
  18136. },
  18137. applyX: function(x) {
  18138. return x * this.k + this.x;
  18139. },
  18140. applyY: function(y) {
  18141. return y * this.k + this.y;
  18142. },
  18143. invert: function(location) {
  18144. return [(location[0] - this.x) / this.k, (location[1] - this.y) / this.k];
  18145. },
  18146. invertX: function(x) {
  18147. return (x - this.x) / this.k;
  18148. },
  18149. invertY: function(y) {
  18150. return (y - this.y) / this.k;
  18151. },
  18152. rescaleX: function(x) {
  18153. return x.copy().domain(x.range().map(this.invertX, this).map(x.invert, x));
  18154. },
  18155. rescaleY: function(y) {
  18156. return y.copy().domain(y.range().map(this.invertY, this).map(y.invert, y));
  18157. },
  18158. toString: function() {
  18159. return "translate(" + this.x + "," + this.y + ") scale(" + this.k + ")";
  18160. }
  18161. };
  18162. var identity = new Transform(1, 0, 0);
  18163. transform.prototype = Transform.prototype;
  18164. function transform(node) {
  18165. return node.__zoom || identity;
  18166. }
  18167. function nopropagation() {
  18168. d3Selection.event.stopImmediatePropagation();
  18169. }
  18170. var noevent = function() {
  18171. d3Selection.event.preventDefault();
  18172. d3Selection.event.stopImmediatePropagation();
  18173. };
  18174. // Ignore right-click, since that should open the context menu.
  18175. function defaultFilter() {
  18176. return !d3Selection.event.button;
  18177. }
  18178. function defaultExtent() {
  18179. var e = this, w, h;
  18180. if (e instanceof SVGElement) {
  18181. e = e.ownerSVGElement || e;
  18182. w = e.width.baseVal.value;
  18183. h = e.height.baseVal.value;
  18184. } else {
  18185. w = e.clientWidth;
  18186. h = e.clientHeight;
  18187. }
  18188. return [[0, 0], [w, h]];
  18189. }
  18190. function defaultTransform() {
  18191. return this.__zoom || identity;
  18192. }
  18193. function defaultWheelDelta() {
  18194. return -d3Selection.event.deltaY * (d3Selection.event.deltaMode ? 120 : 1) / 500;
  18195. }
  18196. function defaultTouchable() {
  18197. return "ontouchstart" in this;
  18198. }
  18199. function defaultConstrain(transform$$1, extent, translateExtent) {
  18200. var dx0 = transform$$1.invertX(extent[0][0]) - translateExtent[0][0],
  18201. dx1 = transform$$1.invertX(extent[1][0]) - translateExtent[1][0],
  18202. dy0 = transform$$1.invertY(extent[0][1]) - translateExtent[0][1],
  18203. dy1 = transform$$1.invertY(extent[1][1]) - translateExtent[1][1];
  18204. return transform$$1.translate(
  18205. dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1),
  18206. dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1)
  18207. );
  18208. }
  18209. var zoom = function() {
  18210. var filter = defaultFilter,
  18211. extent = defaultExtent,
  18212. constrain = defaultConstrain,
  18213. wheelDelta = defaultWheelDelta,
  18214. touchable = defaultTouchable,
  18215. scaleExtent = [0, Infinity],
  18216. translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]],
  18217. duration = 250,
  18218. interpolate = d3Interpolate.interpolateZoom,
  18219. gestures = [],
  18220. listeners = d3Dispatch.dispatch("start", "zoom", "end"),
  18221. touchstarting,
  18222. touchending,
  18223. touchDelay = 500,
  18224. wheelDelay = 150,
  18225. clickDistance2 = 0;
  18226. function zoom(selection) {
  18227. selection
  18228. .property("__zoom", defaultTransform)
  18229. .on("wheel.zoom", wheeled)
  18230. .on("mousedown.zoom", mousedowned)
  18231. .on("dblclick.zoom", dblclicked)
  18232. .filter(touchable)
  18233. .on("touchstart.zoom", touchstarted)
  18234. .on("touchmove.zoom", touchmoved)
  18235. .on("touchend.zoom touchcancel.zoom", touchended)
  18236. .style("touch-action", "none")
  18237. .style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  18238. }
  18239. zoom.transform = function(collection, transform$$1) {
  18240. var selection = collection.selection ? collection.selection() : collection;
  18241. selection.property("__zoom", defaultTransform);
  18242. if (collection !== selection) {
  18243. schedule(collection, transform$$1);
  18244. } else {
  18245. selection.interrupt().each(function() {
  18246. gesture(this, arguments)
  18247. .start()
  18248. .zoom(null, typeof transform$$1 === "function" ? transform$$1.apply(this, arguments) : transform$$1)
  18249. .end();
  18250. });
  18251. }
  18252. };
  18253. zoom.scaleBy = function(selection, k) {
  18254. zoom.scaleTo(selection, function() {
  18255. var k0 = this.__zoom.k,
  18256. k1 = typeof k === "function" ? k.apply(this, arguments) : k;
  18257. return k0 * k1;
  18258. });
  18259. };
  18260. zoom.scaleTo = function(selection, k) {
  18261. zoom.transform(selection, function() {
  18262. var e = extent.apply(this, arguments),
  18263. t0 = this.__zoom,
  18264. p0 = centroid(e),
  18265. p1 = t0.invert(p0),
  18266. k1 = typeof k === "function" ? k.apply(this, arguments) : k;
  18267. return constrain(translate(scale(t0, k1), p0, p1), e, translateExtent);
  18268. });
  18269. };
  18270. zoom.translateBy = function(selection, x, y) {
  18271. zoom.transform(selection, function() {
  18272. return constrain(this.__zoom.translate(
  18273. typeof x === "function" ? x.apply(this, arguments) : x,
  18274. typeof y === "function" ? y.apply(this, arguments) : y
  18275. ), extent.apply(this, arguments), translateExtent);
  18276. });
  18277. };
  18278. zoom.translateTo = function(selection, x, y) {
  18279. zoom.transform(selection, function() {
  18280. var e = extent.apply(this, arguments),
  18281. t = this.__zoom,
  18282. p = centroid(e);
  18283. return constrain(identity.translate(p[0], p[1]).scale(t.k).translate(
  18284. typeof x === "function" ? -x.apply(this, arguments) : -x,
  18285. typeof y === "function" ? -y.apply(this, arguments) : -y
  18286. ), e, translateExtent);
  18287. });
  18288. };
  18289. function scale(transform$$1, k) {
  18290. k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], k));
  18291. return k === transform$$1.k ? transform$$1 : new Transform(k, transform$$1.x, transform$$1.y);
  18292. }
  18293. function translate(transform$$1, p0, p1) {
  18294. var x = p0[0] - p1[0] * transform$$1.k, y = p0[1] - p1[1] * transform$$1.k;
  18295. return x === transform$$1.x && y === transform$$1.y ? transform$$1 : new Transform(transform$$1.k, x, y);
  18296. }
  18297. function centroid(extent) {
  18298. return [(+extent[0][0] + +extent[1][0]) / 2, (+extent[0][1] + +extent[1][1]) / 2];
  18299. }
  18300. function schedule(transition, transform$$1, center) {
  18301. transition
  18302. .on("start.zoom", function() { gesture(this, arguments).start(); })
  18303. .on("interrupt.zoom end.zoom", function() { gesture(this, arguments).end(); })
  18304. .tween("zoom", function() {
  18305. var that = this,
  18306. args = arguments,
  18307. g = gesture(that, args),
  18308. e = extent.apply(that, args),
  18309. p = center || centroid(e),
  18310. w = Math.max(e[1][0] - e[0][0], e[1][1] - e[0][1]),
  18311. a = that.__zoom,
  18312. b = typeof transform$$1 === "function" ? transform$$1.apply(that, args) : transform$$1,
  18313. i = interpolate(a.invert(p).concat(w / a.k), b.invert(p).concat(w / b.k));
  18314. return function(t) {
  18315. if (t === 1) t = b; // Avoid rounding error on end.
  18316. else { var l = i(t), k = w / l[2]; t = new Transform(k, p[0] - l[0] * k, p[1] - l[1] * k); }
  18317. g.zoom(null, t);
  18318. };
  18319. });
  18320. }
  18321. function gesture(that, args) {
  18322. for (var i = 0, n = gestures.length, g; i < n; ++i) {
  18323. if ((g = gestures[i]).that === that) {
  18324. return g;
  18325. }
  18326. }
  18327. return new Gesture(that, args);
  18328. }
  18329. function Gesture(that, args) {
  18330. this.that = that;
  18331. this.args = args;
  18332. this.index = -1;
  18333. this.active = 0;
  18334. this.extent = extent.apply(that, args);
  18335. }
  18336. Gesture.prototype = {
  18337. start: function() {
  18338. if (++this.active === 1) {
  18339. this.index = gestures.push(this) - 1;
  18340. this.emit("start");
  18341. }
  18342. return this;
  18343. },
  18344. zoom: function(key, transform$$1) {
  18345. if (this.mouse && key !== "mouse") this.mouse[1] = transform$$1.invert(this.mouse[0]);
  18346. if (this.touch0 && key !== "touch") this.touch0[1] = transform$$1.invert(this.touch0[0]);
  18347. if (this.touch1 && key !== "touch") this.touch1[1] = transform$$1.invert(this.touch1[0]);
  18348. this.that.__zoom = transform$$1;
  18349. this.emit("zoom");
  18350. return this;
  18351. },
  18352. end: function() {
  18353. if (--this.active === 0) {
  18354. gestures.splice(this.index, 1);
  18355. this.index = -1;
  18356. this.emit("end");
  18357. }
  18358. return this;
  18359. },
  18360. emit: function(type) {
  18361. d3Selection.customEvent(new ZoomEvent(zoom, type, this.that.__zoom), listeners.apply, listeners, [type, this.that, this.args]);
  18362. }
  18363. };
  18364. function wheeled() {
  18365. if (!filter.apply(this, arguments)) return;
  18366. var g = gesture(this, arguments),
  18367. t = this.__zoom,
  18368. k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], t.k * Math.pow(2, wheelDelta.apply(this, arguments)))),
  18369. p = d3Selection.mouse(this);
  18370. // If the mouse is in the same location as before, reuse it.
  18371. // If there were recent wheel events, reset the wheel idle timeout.
  18372. if (g.wheel) {
  18373. if (g.mouse[0][0] !== p[0] || g.mouse[0][1] !== p[1]) {
  18374. g.mouse[1] = t.invert(g.mouse[0] = p);
  18375. }
  18376. clearTimeout(g.wheel);
  18377. }
  18378. // If this wheel event won’t trigger a transform change, ignore it.
  18379. else if (t.k === k) return;
  18380. // Otherwise, capture the mouse point and location at the start.
  18381. else {
  18382. g.mouse = [p, t.invert(p)];
  18383. d3Transition.interrupt(this);
  18384. g.start();
  18385. }
  18386. noevent();
  18387. g.wheel = setTimeout(wheelidled, wheelDelay);
  18388. g.zoom("mouse", constrain(translate(scale(t, k), g.mouse[0], g.mouse[1]), g.extent, translateExtent));
  18389. function wheelidled() {
  18390. g.wheel = null;
  18391. g.end();
  18392. }
  18393. }
  18394. function mousedowned() {
  18395. if (touchending || !filter.apply(this, arguments)) return;
  18396. var g = gesture(this, arguments),
  18397. v = d3Selection.select(d3Selection.event.view).on("mousemove.zoom", mousemoved, true).on("mouseup.zoom", mouseupped, true),
  18398. p = d3Selection.mouse(this),
  18399. x0 = d3Selection.event.clientX,
  18400. y0 = d3Selection.event.clientY;
  18401. d3Drag.dragDisable(d3Selection.event.view);
  18402. nopropagation();
  18403. g.mouse = [p, this.__zoom.invert(p)];
  18404. d3Transition.interrupt(this);
  18405. g.start();
  18406. function mousemoved() {
  18407. noevent();
  18408. if (!g.moved) {
  18409. var dx = d3Selection.event.clientX - x0, dy = d3Selection.event.clientY - y0;
  18410. g.moved = dx * dx + dy * dy > clickDistance2;
  18411. }
  18412. g.zoom("mouse", constrain(translate(g.that.__zoom, g.mouse[0] = d3Selection.mouse(g.that), g.mouse[1]), g.extent, translateExtent));
  18413. }
  18414. function mouseupped() {
  18415. v.on("mousemove.zoom mouseup.zoom", null);
  18416. d3Drag.dragEnable(d3Selection.event.view, g.moved);
  18417. noevent();
  18418. g.end();
  18419. }
  18420. }
  18421. function dblclicked() {
  18422. if (!filter.apply(this, arguments)) return;
  18423. var t0 = this.__zoom,
  18424. p0 = d3Selection.mouse(this),
  18425. p1 = t0.invert(p0),
  18426. k1 = t0.k * (d3Selection.event.shiftKey ? 0.5 : 2),
  18427. t1 = constrain(translate(scale(t0, k1), p0, p1), extent.apply(this, arguments), translateExtent);
  18428. noevent();
  18429. if (duration > 0) d3Selection.select(this).transition().duration(duration).call(schedule, t1, p0);
  18430. else d3Selection.select(this).call(zoom.transform, t1);
  18431. }
  18432. function touchstarted() {
  18433. if (!filter.apply(this, arguments)) return;
  18434. var g = gesture(this, arguments),
  18435. touches = d3Selection.event.changedTouches,
  18436. started,
  18437. n = touches.length, i, t, p;
  18438. nopropagation();
  18439. for (i = 0; i < n; ++i) {
  18440. t = touches[i], p = d3Selection.touch(this, touches, t.identifier);
  18441. p = [p, this.__zoom.invert(p), t.identifier];
  18442. if (!g.touch0) g.touch0 = p, started = true;
  18443. else if (!g.touch1) g.touch1 = p;
  18444. }
  18445. // If this is a dbltap, reroute to the (optional) dblclick.zoom handler.
  18446. if (touchstarting) {
  18447. touchstarting = clearTimeout(touchstarting);
  18448. if (!g.touch1) {
  18449. g.end();
  18450. p = d3Selection.select(this).on("dblclick.zoom");
  18451. if (p) p.apply(this, arguments);
  18452. return;
  18453. }
  18454. }
  18455. if (started) {
  18456. touchstarting = setTimeout(function() { touchstarting = null; }, touchDelay);
  18457. d3Transition.interrupt(this);
  18458. g.start();
  18459. }
  18460. }
  18461. function touchmoved() {
  18462. var g = gesture(this, arguments),
  18463. touches = d3Selection.event.changedTouches,
  18464. n = touches.length, i, t, p, l;
  18465. noevent();
  18466. if (touchstarting) touchstarting = clearTimeout(touchstarting);
  18467. for (i = 0; i < n; ++i) {
  18468. t = touches[i], p = d3Selection.touch(this, touches, t.identifier);
  18469. if (g.touch0 && g.touch0[2] === t.identifier) g.touch0[0] = p;
  18470. else if (g.touch1 && g.touch1[2] === t.identifier) g.touch1[0] = p;
  18471. }
  18472. t = g.that.__zoom;
  18473. if (g.touch1) {
  18474. var p0 = g.touch0[0], l0 = g.touch0[1],
  18475. p1 = g.touch1[0], l1 = g.touch1[1],
  18476. dp = (dp = p1[0] - p0[0]) * dp + (dp = p1[1] - p0[1]) * dp,
  18477. dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl;
  18478. t = scale(t, Math.sqrt(dp / dl));
  18479. p = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];
  18480. l = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2];
  18481. }
  18482. else if (g.touch0) p = g.touch0[0], l = g.touch0[1];
  18483. else return;
  18484. g.zoom("touch", constrain(translate(t, p, l), g.extent, translateExtent));
  18485. }
  18486. function touchended() {
  18487. var g = gesture(this, arguments),
  18488. touches = d3Selection.event.changedTouches,
  18489. n = touches.length, i, t;
  18490. nopropagation();
  18491. if (touchending) clearTimeout(touchending);
  18492. touchending = setTimeout(function() { touchending = null; }, touchDelay);
  18493. for (i = 0; i < n; ++i) {
  18494. t = touches[i];
  18495. if (g.touch0 && g.touch0[2] === t.identifier) delete g.touch0;
  18496. else if (g.touch1 && g.touch1[2] === t.identifier) delete g.touch1;
  18497. }
  18498. if (g.touch1 && !g.touch0) g.touch0 = g.touch1, delete g.touch1;
  18499. if (g.touch0) g.touch0[1] = this.__zoom.invert(g.touch0[0]);
  18500. else g.end();
  18501. }
  18502. zoom.wheelDelta = function(_) {
  18503. return arguments.length ? (wheelDelta = typeof _ === "function" ? _ : constant(+_), zoom) : wheelDelta;
  18504. };
  18505. zoom.filter = function(_) {
  18506. return arguments.length ? (filter = typeof _ === "function" ? _ : constant(!!_), zoom) : filter;
  18507. };
  18508. zoom.touchable = function(_) {
  18509. return arguments.length ? (touchable = typeof _ === "function" ? _ : constant(!!_), zoom) : touchable;
  18510. };
  18511. zoom.extent = function(_) {
  18512. return arguments.length ? (extent = typeof _ === "function" ? _ : constant([[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]]), zoom) : extent;
  18513. };
  18514. zoom.scaleExtent = function(_) {
  18515. return arguments.length ? (scaleExtent[0] = +_[0], scaleExtent[1] = +_[1], zoom) : [scaleExtent[0], scaleExtent[1]];
  18516. };
  18517. zoom.translateExtent = function(_) {
  18518. return arguments.length ? (translateExtent[0][0] = +_[0][0], translateExtent[1][0] = +_[1][0], translateExtent[0][1] = +_[0][1], translateExtent[1][1] = +_[1][1], zoom) : [[translateExtent[0][0], translateExtent[0][1]], [translateExtent[1][0], translateExtent[1][1]]];
  18519. };
  18520. zoom.constrain = function(_) {
  18521. return arguments.length ? (constrain = _, zoom) : constrain;
  18522. };
  18523. zoom.duration = function(_) {
  18524. return arguments.length ? (duration = +_, zoom) : duration;
  18525. };
  18526. zoom.interpolate = function(_) {
  18527. return arguments.length ? (interpolate = _, zoom) : interpolate;
  18528. };
  18529. zoom.on = function() {
  18530. var value = listeners.on.apply(listeners, arguments);
  18531. return value === listeners ? zoom : value;
  18532. };
  18533. zoom.clickDistance = function(_) {
  18534. return arguments.length ? (clickDistance2 = (_ = +_) * _, zoom) : Math.sqrt(clickDistance2);
  18535. };
  18536. return zoom;
  18537. };
  18538. exports.zoom = zoom;
  18539. exports.zoomTransform = transform;
  18540. exports.zoomIdentity = identity;
  18541. Object.defineProperty(exports, '__esModule', { value: true });
  18542. })));
  18543. },{"d3-dispatch":45,"d3-drag":46,"d3-interpolate":53,"d3-selection":61,"d3-transition":66}],69:[function(require,module,exports){
  18544. 'use strict';
  18545. Object.defineProperty(exports, '__esModule', { value: true });
  18546. var d3Array = require('d3-array');
  18547. var d3Axis = require('d3-axis');
  18548. var d3Brush = require('d3-brush');
  18549. var d3Chord = require('d3-chord');
  18550. var d3Collection = require('d3-collection');
  18551. var d3Color = require('d3-color');
  18552. var d3Dispatch = require('d3-dispatch');
  18553. var d3Drag = require('d3-drag');
  18554. var d3Dsv = require('d3-dsv');
  18555. var d3Ease = require('d3-ease');
  18556. var d3Force = require('d3-force');
  18557. var d3Format = require('d3-format');
  18558. var d3Geo = require('d3-geo');
  18559. var d3Hierarchy = require('d3-hierarchy');
  18560. var d3Interpolate = require('d3-interpolate');
  18561. var d3Path = require('d3-path');
  18562. var d3Polygon = require('d3-polygon');
  18563. var d3Quadtree = require('d3-quadtree');
  18564. var d3Queue = require('d3-queue');
  18565. var d3Random = require('d3-random');
  18566. var d3Request = require('d3-request');
  18567. var d3Scale = require('d3-scale');
  18568. var d3Selection = require('d3-selection');
  18569. var d3Shape = require('d3-shape');
  18570. var d3Time = require('d3-time');
  18571. var d3TimeFormat = require('d3-time-format');
  18572. var d3Timer = require('d3-timer');
  18573. var d3Transition = require('d3-transition');
  18574. var d3Voronoi = require('d3-voronoi');
  18575. var d3Zoom = require('d3-zoom');
  18576. var version = "4.12.2";
  18577. exports.version = version;
  18578. Object.keys(d3Array).forEach(function (key) { exports[key] = d3Array[key]; });
  18579. Object.keys(d3Axis).forEach(function (key) { exports[key] = d3Axis[key]; });
  18580. Object.keys(d3Brush).forEach(function (key) { exports[key] = d3Brush[key]; });
  18581. Object.keys(d3Chord).forEach(function (key) { exports[key] = d3Chord[key]; });
  18582. Object.keys(d3Collection).forEach(function (key) { exports[key] = d3Collection[key]; });
  18583. Object.keys(d3Color).forEach(function (key) { exports[key] = d3Color[key]; });
  18584. Object.keys(d3Dispatch).forEach(function (key) { exports[key] = d3Dispatch[key]; });
  18585. Object.keys(d3Drag).forEach(function (key) { exports[key] = d3Drag[key]; });
  18586. Object.keys(d3Dsv).forEach(function (key) { exports[key] = d3Dsv[key]; });
  18587. Object.keys(d3Ease).forEach(function (key) { exports[key] = d3Ease[key]; });
  18588. Object.keys(d3Force).forEach(function (key) { exports[key] = d3Force[key]; });
  18589. Object.keys(d3Format).forEach(function (key) { exports[key] = d3Format[key]; });
  18590. Object.keys(d3Geo).forEach(function (key) { exports[key] = d3Geo[key]; });
  18591. Object.keys(d3Hierarchy).forEach(function (key) { exports[key] = d3Hierarchy[key]; });
  18592. Object.keys(d3Interpolate).forEach(function (key) { exports[key] = d3Interpolate[key]; });
  18593. Object.keys(d3Path).forEach(function (key) { exports[key] = d3Path[key]; });
  18594. Object.keys(d3Polygon).forEach(function (key) { exports[key] = d3Polygon[key]; });
  18595. Object.keys(d3Quadtree).forEach(function (key) { exports[key] = d3Quadtree[key]; });
  18596. Object.keys(d3Queue).forEach(function (key) { exports[key] = d3Queue[key]; });
  18597. Object.keys(d3Random).forEach(function (key) { exports[key] = d3Random[key]; });
  18598. Object.keys(d3Request).forEach(function (key) { exports[key] = d3Request[key]; });
  18599. Object.keys(d3Scale).forEach(function (key) { exports[key] = d3Scale[key]; });
  18600. Object.keys(d3Selection).forEach(function (key) { exports[key] = d3Selection[key]; });
  18601. Object.keys(d3Shape).forEach(function (key) { exports[key] = d3Shape[key]; });
  18602. Object.keys(d3Time).forEach(function (key) { exports[key] = d3Time[key]; });
  18603. Object.keys(d3TimeFormat).forEach(function (key) { exports[key] = d3TimeFormat[key]; });
  18604. Object.keys(d3Timer).forEach(function (key) { exports[key] = d3Timer[key]; });
  18605. Object.keys(d3Transition).forEach(function (key) { exports[key] = d3Transition[key]; });
  18606. Object.keys(d3Voronoi).forEach(function (key) { exports[key] = d3Voronoi[key]; });
  18607. Object.keys(d3Zoom).forEach(function (key) { exports[key] = d3Zoom[key]; });
  18608. Object.defineProperty(exports, "event", {get: function() { return d3Selection.event; }});
  18609. },{"d3-array":39,"d3-axis":40,"d3-brush":41,"d3-chord":42,"d3-collection":43,"d3-color":44,"d3-dispatch":45,"d3-drag":46,"d3-dsv":47,"d3-ease":48,"d3-force":49,"d3-format":50,"d3-geo":51,"d3-hierarchy":52,"d3-interpolate":53,"d3-path":54,"d3-polygon":55,"d3-quadtree":56,"d3-queue":57,"d3-random":58,"d3-request":59,"d3-scale":60,"d3-selection":61,"d3-shape":62,"d3-time":64,"d3-time-format":63,"d3-timer":65,"d3-transition":66,"d3-voronoi":67,"d3-zoom":68}],70:[function(require,module,exports){
  18610. /*
  18611. Copyright (c) 2012-2014 Chris Pettitt
  18612. Permission is hereby granted, free of charge, to any person obtaining a copy
  18613. of this software and associated documentation files (the "Software"), to deal
  18614. in the Software without restriction, including without limitation the rights
  18615. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18616. copies of the Software, and to permit persons to whom the Software is
  18617. furnished to do so, subject to the following conditions:
  18618. The above copyright notice and this permission notice shall be included in
  18619. all copies or substantial portions of the Software.
  18620. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18621. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18622. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18623. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18624. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18625. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18626. THE SOFTWARE.
  18627. */
  18628. module.exports = {
  18629. graphlib: require("./lib/graphlib"),
  18630. layout: require("./lib/layout"),
  18631. debug: require("./lib/debug"),
  18632. util: {
  18633. time: require("./lib/util").time,
  18634. notime: require("./lib/util").notime
  18635. },
  18636. version: require("./lib/version")
  18637. };
  18638. },{"./lib/debug":75,"./lib/graphlib":76,"./lib/layout":78,"./lib/util":98,"./lib/version":99}],71:[function(require,module,exports){
  18639. "use strict";
  18640. var _ = require("./lodash"),
  18641. greedyFAS = require("./greedy-fas");
  18642. module.exports = {
  18643. run: run,
  18644. undo: undo
  18645. };
  18646. function run(g) {
  18647. var fas = (g.graph().acyclicer === "greedy"
  18648. ? greedyFAS(g, weightFn(g))
  18649. : dfsFAS(g));
  18650. _.forEach(fas, function(e) {
  18651. var label = g.edge(e);
  18652. g.removeEdge(e);
  18653. label.forwardName = e.name;
  18654. label.reversed = true;
  18655. g.setEdge(e.w, e.v, label, _.uniqueId("rev"));
  18656. });
  18657. function weightFn(g) {
  18658. return function(e) {
  18659. return g.edge(e).weight;
  18660. };
  18661. }
  18662. }
  18663. function dfsFAS(g) {
  18664. var fas = [],
  18665. stack = {},
  18666. visited = {};
  18667. function dfs(v) {
  18668. if (_.has(visited, v)) {
  18669. return;
  18670. }
  18671. visited[v] = true;
  18672. stack[v] = true;
  18673. _.forEach(g.outEdges(v), function(e) {
  18674. if (_.has(stack, e.w)) {
  18675. fas.push(e);
  18676. } else {
  18677. dfs(e.w);
  18678. }
  18679. });
  18680. delete stack[v];
  18681. }
  18682. _.forEach(g.nodes(), dfs);
  18683. return fas;
  18684. }
  18685. function undo(g) {
  18686. _.forEach(g.edges(), function(e) {
  18687. var label = g.edge(e);
  18688. if (label.reversed) {
  18689. g.removeEdge(e);
  18690. var forwardName = label.forwardName;
  18691. delete label.reversed;
  18692. delete label.forwardName;
  18693. g.setEdge(e.w, e.v, label, forwardName);
  18694. }
  18695. });
  18696. }
  18697. },{"./greedy-fas":77,"./lodash":79}],72:[function(require,module,exports){
  18698. var _ = require("./lodash"),
  18699. util = require("./util");
  18700. module.exports = addBorderSegments;
  18701. function addBorderSegments(g) {
  18702. function dfs(v) {
  18703. var children = g.children(v),
  18704. node = g.node(v);
  18705. if (children.length) {
  18706. _.forEach(children, dfs);
  18707. }
  18708. if (_.has(node, "minRank")) {
  18709. node.borderLeft = [];
  18710. node.borderRight = [];
  18711. for (var rank = node.minRank, maxRank = node.maxRank + 1;
  18712. rank < maxRank;
  18713. ++rank) {
  18714. addBorderNode(g, "borderLeft", "_bl", v, node, rank);
  18715. addBorderNode(g, "borderRight", "_br", v, node, rank);
  18716. }
  18717. }
  18718. }
  18719. _.forEach(g.children(), dfs);
  18720. }
  18721. function addBorderNode(g, prop, prefix, sg, sgNode, rank) {
  18722. var label = { width: 0, height: 0, rank: rank, borderType: prop },
  18723. prev = sgNode[prop][rank - 1],
  18724. curr = util.addDummyNode(g, "border", label, prefix);
  18725. sgNode[prop][rank] = curr;
  18726. g.setParent(curr, sg);
  18727. if (prev) {
  18728. g.setEdge(prev, curr, { weight: 1 });
  18729. }
  18730. }
  18731. },{"./lodash":79,"./util":98}],73:[function(require,module,exports){
  18732. "use strict";
  18733. var _ = require("./lodash");
  18734. module.exports = {
  18735. adjust: adjust,
  18736. undo: undo
  18737. };
  18738. function adjust(g) {
  18739. var rankDir = g.graph().rankdir.toLowerCase();
  18740. if (rankDir === "lr" || rankDir === "rl") {
  18741. swapWidthHeight(g);
  18742. }
  18743. }
  18744. function undo(g) {
  18745. var rankDir = g.graph().rankdir.toLowerCase();
  18746. if (rankDir === "bt" || rankDir === "rl") {
  18747. reverseY(g);
  18748. }
  18749. if (rankDir === "lr" || rankDir === "rl") {
  18750. swapXY(g);
  18751. swapWidthHeight(g);
  18752. }
  18753. }
  18754. function swapWidthHeight(g) {
  18755. _.forEach(g.nodes(), function(v) { swapWidthHeightOne(g.node(v)); });
  18756. _.forEach(g.edges(), function(e) { swapWidthHeightOne(g.edge(e)); });
  18757. }
  18758. function swapWidthHeightOne(attrs) {
  18759. var w = attrs.width;
  18760. attrs.width = attrs.height;
  18761. attrs.height = w;
  18762. }
  18763. function reverseY(g) {
  18764. _.forEach(g.nodes(), function(v) { reverseYOne(g.node(v)); });
  18765. _.forEach(g.edges(), function(e) {
  18766. var edge = g.edge(e);
  18767. _.forEach(edge.points, reverseYOne);
  18768. if (_.has(edge, "y")) {
  18769. reverseYOne(edge);
  18770. }
  18771. });
  18772. }
  18773. function reverseYOne(attrs) {
  18774. attrs.y = -attrs.y;
  18775. }
  18776. function swapXY(g) {
  18777. _.forEach(g.nodes(), function(v) { swapXYOne(g.node(v)); });
  18778. _.forEach(g.edges(), function(e) {
  18779. var edge = g.edge(e);
  18780. _.forEach(edge.points, swapXYOne);
  18781. if (_.has(edge, "x")) {
  18782. swapXYOne(edge);
  18783. }
  18784. });
  18785. }
  18786. function swapXYOne(attrs) {
  18787. var x = attrs.x;
  18788. attrs.x = attrs.y;
  18789. attrs.y = x;
  18790. }
  18791. },{"./lodash":79}],74:[function(require,module,exports){
  18792. /*
  18793. * Simple doubly linked list implementation derived from Cormen, et al.,
  18794. * "Introduction to Algorithms".
  18795. */
  18796. module.exports = List;
  18797. function List() {
  18798. var sentinel = {};
  18799. sentinel._next = sentinel._prev = sentinel;
  18800. this._sentinel = sentinel;
  18801. }
  18802. List.prototype.dequeue = function() {
  18803. var sentinel = this._sentinel,
  18804. entry = sentinel._prev;
  18805. if (entry !== sentinel) {
  18806. unlink(entry);
  18807. return entry;
  18808. }
  18809. };
  18810. List.prototype.enqueue = function(entry) {
  18811. var sentinel = this._sentinel;
  18812. if (entry._prev && entry._next) {
  18813. unlink(entry);
  18814. }
  18815. entry._next = sentinel._next;
  18816. sentinel._next._prev = entry;
  18817. sentinel._next = entry;
  18818. entry._prev = sentinel;
  18819. };
  18820. List.prototype.toString = function() {
  18821. var strs = [],
  18822. sentinel = this._sentinel,
  18823. curr = sentinel._prev;
  18824. while (curr !== sentinel) {
  18825. strs.push(JSON.stringify(curr, filterOutLinks));
  18826. curr = curr._prev;
  18827. }
  18828. return "[" + strs.join(", ") + "]";
  18829. };
  18830. function unlink(entry) {
  18831. entry._prev._next = entry._next;
  18832. entry._next._prev = entry._prev;
  18833. delete entry._next;
  18834. delete entry._prev;
  18835. }
  18836. function filterOutLinks(k, v) {
  18837. if (k !== "_next" && k !== "_prev") {
  18838. return v;
  18839. }
  18840. }
  18841. },{}],75:[function(require,module,exports){
  18842. var _ = require("./lodash"),
  18843. util = require("./util"),
  18844. Graph = require("./graphlib").Graph;
  18845. module.exports = {
  18846. debugOrdering: debugOrdering
  18847. };
  18848. /* istanbul ignore next */
  18849. function debugOrdering(g) {
  18850. var layerMatrix = util.buildLayerMatrix(g);
  18851. var h = new Graph({ compound: true, multigraph: true }).setGraph({});
  18852. _.forEach(g.nodes(), function(v) {
  18853. h.setNode(v, { label: v });
  18854. h.setParent(v, "layer" + g.node(v).rank);
  18855. });
  18856. _.forEach(g.edges(), function(e) {
  18857. h.setEdge(e.v, e.w, {}, e.name);
  18858. });
  18859. _.forEach(layerMatrix, function(layer, i) {
  18860. var layerV = "layer" + i;
  18861. h.setNode(layerV, { rank: "same" });
  18862. _.reduce(layer, function(u, v) {
  18863. h.setEdge(u, v, { style: "invis" });
  18864. return v;
  18865. });
  18866. });
  18867. return h;
  18868. }
  18869. },{"./graphlib":76,"./lodash":79,"./util":98}],76:[function(require,module,exports){
  18870. /* global window */
  18871. var graphlib;
  18872. if (typeof require === "function") {
  18873. try {
  18874. graphlib = require("graphlib");
  18875. } catch (e) {}
  18876. }
  18877. if (!graphlib) {
  18878. graphlib = window.graphlib;
  18879. }
  18880. module.exports = graphlib;
  18881. },{"graphlib":100}],77:[function(require,module,exports){
  18882. var _ = require("./lodash"),
  18883. Graph = require("./graphlib").Graph,
  18884. List = require("./data/list");
  18885. /*
  18886. * A greedy heuristic for finding a feedback arc set for a graph. A feedback
  18887. * arc set is a set of edges that can be removed to make a graph acyclic.
  18888. * The algorithm comes from: P. Eades, X. Lin, and W. F. Smyth, "A fast and
  18889. * effective heuristic for the feedback arc set problem." This implementation
  18890. * adjusts that from the paper to allow for weighted edges.
  18891. */
  18892. module.exports = greedyFAS;
  18893. var DEFAULT_WEIGHT_FN = _.constant(1);
  18894. function greedyFAS(g, weightFn) {
  18895. if (g.nodeCount() <= 1) {
  18896. return [];
  18897. }
  18898. var state = buildState(g, weightFn || DEFAULT_WEIGHT_FN);
  18899. var results = doGreedyFAS(state.graph, state.buckets, state.zeroIdx);
  18900. // Expand multi-edges
  18901. return _.flatten(_.map(results, function(e) {
  18902. return g.outEdges(e.v, e.w);
  18903. }), true);
  18904. }
  18905. function doGreedyFAS(g, buckets, zeroIdx) {
  18906. var results = [],
  18907. sources = buckets[buckets.length - 1],
  18908. sinks = buckets[0];
  18909. var entry;
  18910. while (g.nodeCount()) {
  18911. while ((entry = sinks.dequeue())) { removeNode(g, buckets, zeroIdx, entry); }
  18912. while ((entry = sources.dequeue())) { removeNode(g, buckets, zeroIdx, entry); }
  18913. if (g.nodeCount()) {
  18914. for (var i = buckets.length - 2; i > 0; --i) {
  18915. entry = buckets[i].dequeue();
  18916. if (entry) {
  18917. results = results.concat(removeNode(g, buckets, zeroIdx, entry, true));
  18918. break;
  18919. }
  18920. }
  18921. }
  18922. }
  18923. return results;
  18924. }
  18925. function removeNode(g, buckets, zeroIdx, entry, collectPredecessors) {
  18926. var results = collectPredecessors ? [] : undefined;
  18927. _.forEach(g.inEdges(entry.v), function(edge) {
  18928. var weight = g.edge(edge),
  18929. uEntry = g.node(edge.v);
  18930. if (collectPredecessors) {
  18931. results.push({ v: edge.v, w: edge.w });
  18932. }
  18933. uEntry.out -= weight;
  18934. assignBucket(buckets, zeroIdx, uEntry);
  18935. });
  18936. _.forEach(g.outEdges(entry.v), function(edge) {
  18937. var weight = g.edge(edge),
  18938. w = edge.w,
  18939. wEntry = g.node(w);
  18940. wEntry["in"] -= weight;
  18941. assignBucket(buckets, zeroIdx, wEntry);
  18942. });
  18943. g.removeNode(entry.v);
  18944. return results;
  18945. }
  18946. function buildState(g, weightFn) {
  18947. var fasGraph = new Graph(),
  18948. maxIn = 0,
  18949. maxOut = 0;
  18950. _.forEach(g.nodes(), function(v) {
  18951. fasGraph.setNode(v, { v: v, "in": 0, out: 0 });
  18952. });
  18953. // Aggregate weights on nodes, but also sum the weights across multi-edges
  18954. // into a single edge for the fasGraph.
  18955. _.forEach(g.edges(), function(e) {
  18956. var prevWeight = fasGraph.edge(e.v, e.w) || 0,
  18957. weight = weightFn(e),
  18958. edgeWeight = prevWeight + weight;
  18959. fasGraph.setEdge(e.v, e.w, edgeWeight);
  18960. maxOut = Math.max(maxOut, fasGraph.node(e.v).out += weight);
  18961. maxIn = Math.max(maxIn, fasGraph.node(e.w)["in"] += weight);
  18962. });
  18963. var buckets = _.range(maxOut + maxIn + 3).map(function() { return new List(); });
  18964. var zeroIdx = maxIn + 1;
  18965. _.forEach(fasGraph.nodes(), function(v) {
  18966. assignBucket(buckets, zeroIdx, fasGraph.node(v));
  18967. });
  18968. return { graph: fasGraph, buckets: buckets, zeroIdx: zeroIdx };
  18969. }
  18970. function assignBucket(buckets, zeroIdx, entry) {
  18971. if (!entry.out) {
  18972. buckets[0].enqueue(entry);
  18973. } else if (!entry["in"]) {
  18974. buckets[buckets.length - 1].enqueue(entry);
  18975. } else {
  18976. buckets[entry.out - entry["in"] + zeroIdx].enqueue(entry);
  18977. }
  18978. }
  18979. },{"./data/list":74,"./graphlib":76,"./lodash":79}],78:[function(require,module,exports){
  18980. "use strict";
  18981. var _ = require("./lodash"),
  18982. acyclic = require("./acyclic"),
  18983. normalize = require("./normalize"),
  18984. rank = require("./rank"),
  18985. normalizeRanks = require("./util").normalizeRanks,
  18986. parentDummyChains = require("./parent-dummy-chains"),
  18987. removeEmptyRanks = require("./util").removeEmptyRanks,
  18988. nestingGraph = require("./nesting-graph"),
  18989. addBorderSegments = require("./add-border-segments"),
  18990. coordinateSystem = require("./coordinate-system"),
  18991. order = require("./order"),
  18992. position = require("./position"),
  18993. util = require("./util"),
  18994. Graph = require("./graphlib").Graph;
  18995. module.exports = layout;
  18996. function layout(g, opts) {
  18997. var time = opts && opts.debugTiming ? util.time : util.notime;
  18998. time("layout", function() {
  18999. var layoutGraph = time(" buildLayoutGraph",
  19000. function() { return buildLayoutGraph(g); });
  19001. time(" runLayout", function() { runLayout(layoutGraph, time); });
  19002. time(" updateInputGraph", function() { updateInputGraph(g, layoutGraph); });
  19003. });
  19004. }
  19005. function runLayout(g, time) {
  19006. time(" makeSpaceForEdgeLabels", function() { makeSpaceForEdgeLabels(g); });
  19007. time(" removeSelfEdges", function() { removeSelfEdges(g); });
  19008. time(" acyclic", function() { acyclic.run(g); });
  19009. time(" nestingGraph.run", function() { nestingGraph.run(g); });
  19010. time(" rank", function() { rank(util.asNonCompoundGraph(g)); });
  19011. time(" injectEdgeLabelProxies", function() { injectEdgeLabelProxies(g); });
  19012. time(" removeEmptyRanks", function() { removeEmptyRanks(g); });
  19013. time(" nestingGraph.cleanup", function() { nestingGraph.cleanup(g); });
  19014. time(" normalizeRanks", function() { normalizeRanks(g); });
  19015. time(" assignRankMinMax", function() { assignRankMinMax(g); });
  19016. time(" removeEdgeLabelProxies", function() { removeEdgeLabelProxies(g); });
  19017. time(" normalize.run", function() { normalize.run(g); });
  19018. time(" parentDummyChains", function() { parentDummyChains(g); });
  19019. time(" addBorderSegments", function() { addBorderSegments(g); });
  19020. time(" order", function() { order(g); });
  19021. time(" insertSelfEdges", function() { insertSelfEdges(g); });
  19022. time(" adjustCoordinateSystem", function() { coordinateSystem.adjust(g); });
  19023. time(" position", function() { position(g); });
  19024. time(" positionSelfEdges", function() { positionSelfEdges(g); });
  19025. time(" removeBorderNodes", function() { removeBorderNodes(g); });
  19026. time(" normalize.undo", function() { normalize.undo(g); });
  19027. time(" fixupEdgeLabelCoords", function() { fixupEdgeLabelCoords(g); });
  19028. time(" undoCoordinateSystem", function() { coordinateSystem.undo(g); });
  19029. time(" translateGraph", function() { translateGraph(g); });
  19030. time(" assignNodeIntersects", function() { assignNodeIntersects(g); });
  19031. time(" reversePoints", function() { reversePointsForReversedEdges(g); });
  19032. time(" acyclic.undo", function() { acyclic.undo(g); });
  19033. }
  19034. /*
  19035. * Copies final layout information from the layout graph back to the input
  19036. * graph. This process only copies whitelisted attributes from the layout graph
  19037. * to the input graph, so it serves as a good place to determine what
  19038. * attributes can influence layout.
  19039. */
  19040. function updateInputGraph(inputGraph, layoutGraph) {
  19041. _.forEach(inputGraph.nodes(), function(v) {
  19042. var inputLabel = inputGraph.node(v),
  19043. layoutLabel = layoutGraph.node(v);
  19044. if (inputLabel) {
  19045. inputLabel.x = layoutLabel.x;
  19046. inputLabel.y = layoutLabel.y;
  19047. if (layoutGraph.children(v).length) {
  19048. inputLabel.width = layoutLabel.width;
  19049. inputLabel.height = layoutLabel.height;
  19050. }
  19051. }
  19052. });
  19053. _.forEach(inputGraph.edges(), function(e) {
  19054. var inputLabel = inputGraph.edge(e),
  19055. layoutLabel = layoutGraph.edge(e);
  19056. inputLabel.points = layoutLabel.points;
  19057. if (_.has(layoutLabel, "x")) {
  19058. inputLabel.x = layoutLabel.x;
  19059. inputLabel.y = layoutLabel.y;
  19060. }
  19061. });
  19062. inputGraph.graph().width = layoutGraph.graph().width;
  19063. inputGraph.graph().height = layoutGraph.graph().height;
  19064. }
  19065. var graphNumAttrs = ["nodesep", "edgesep", "ranksep", "marginx", "marginy"],
  19066. graphDefaults = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: "tb" },
  19067. graphAttrs = ["acyclicer", "ranker", "rankdir", "align"],
  19068. nodeNumAttrs = ["width", "height"],
  19069. nodeDefaults = { width: 0, height: 0 },
  19070. edgeNumAttrs = ["minlen", "weight", "width", "height", "labeloffset"],
  19071. edgeDefaults = {
  19072. minlen: 1, weight: 1, width: 0, height: 0,
  19073. labeloffset: 10, labelpos: "r"
  19074. },
  19075. edgeAttrs = ["labelpos"];
  19076. /*
  19077. * Constructs a new graph from the input graph, which can be used for layout.
  19078. * This process copies only whitelisted attributes from the input graph to the
  19079. * layout graph. Thus this function serves as a good place to determine what
  19080. * attributes can influence layout.
  19081. */
  19082. function buildLayoutGraph(inputGraph) {
  19083. var g = new Graph({ multigraph: true, compound: true }),
  19084. graph = canonicalize(inputGraph.graph());
  19085. g.setGraph(_.merge({},
  19086. graphDefaults,
  19087. selectNumberAttrs(graph, graphNumAttrs),
  19088. _.pick(graph, graphAttrs)));
  19089. _.forEach(inputGraph.nodes(), function(v) {
  19090. var node = canonicalize(inputGraph.node(v));
  19091. g.setNode(v, _.defaults(selectNumberAttrs(node, nodeNumAttrs), nodeDefaults));
  19092. g.setParent(v, inputGraph.parent(v));
  19093. });
  19094. _.forEach(inputGraph.edges(), function(e) {
  19095. var edge = canonicalize(inputGraph.edge(e));
  19096. g.setEdge(e, _.merge({},
  19097. edgeDefaults,
  19098. selectNumberAttrs(edge, edgeNumAttrs),
  19099. _.pick(edge, edgeAttrs)));
  19100. });
  19101. return g;
  19102. }
  19103. /*
  19104. * This idea comes from the Gansner paper: to account for edge labels in our
  19105. * layout we split each rank in half by doubling minlen and halving ranksep.
  19106. * Then we can place labels at these mid-points between nodes.
  19107. *
  19108. * We also add some minimal padding to the width to push the label for the edge
  19109. * away from the edge itself a bit.
  19110. */
  19111. function makeSpaceForEdgeLabels(g) {
  19112. var graph = g.graph();
  19113. graph.ranksep /= 2;
  19114. _.forEach(g.edges(), function(e) {
  19115. var edge = g.edge(e);
  19116. edge.minlen *= 2;
  19117. if (edge.labelpos.toLowerCase() !== "c") {
  19118. if (graph.rankdir === "TB" || graph.rankdir === "BT") {
  19119. edge.width += edge.labeloffset;
  19120. } else {
  19121. edge.height += edge.labeloffset;
  19122. }
  19123. }
  19124. });
  19125. }
  19126. /*
  19127. * Creates temporary dummy nodes that capture the rank in which each edge's
  19128. * label is going to, if it has one of non-zero width and height. We do this
  19129. * so that we can safely remove empty ranks while preserving balance for the
  19130. * label's position.
  19131. */
  19132. function injectEdgeLabelProxies(g) {
  19133. _.forEach(g.edges(), function(e) {
  19134. var edge = g.edge(e);
  19135. if (edge.width && edge.height) {
  19136. var v = g.node(e.v),
  19137. w = g.node(e.w),
  19138. label = { rank: (w.rank - v.rank) / 2 + v.rank, e: e };
  19139. util.addDummyNode(g, "edge-proxy", label, "_ep");
  19140. }
  19141. });
  19142. }
  19143. function assignRankMinMax(g) {
  19144. var maxRank = 0;
  19145. _.forEach(g.nodes(), function(v) {
  19146. var node = g.node(v);
  19147. if (node.borderTop) {
  19148. node.minRank = g.node(node.borderTop).rank;
  19149. node.maxRank = g.node(node.borderBottom).rank;
  19150. maxRank = _.max(maxRank, node.maxRank);
  19151. }
  19152. });
  19153. g.graph().maxRank = maxRank;
  19154. }
  19155. function removeEdgeLabelProxies(g) {
  19156. _.forEach(g.nodes(), function(v) {
  19157. var node = g.node(v);
  19158. if (node.dummy === "edge-proxy") {
  19159. g.edge(node.e).labelRank = node.rank;
  19160. g.removeNode(v);
  19161. }
  19162. });
  19163. }
  19164. function translateGraph(g) {
  19165. var minX = Number.POSITIVE_INFINITY,
  19166. maxX = 0,
  19167. minY = Number.POSITIVE_INFINITY,
  19168. maxY = 0,
  19169. graphLabel = g.graph(),
  19170. marginX = graphLabel.marginx || 0,
  19171. marginY = graphLabel.marginy || 0;
  19172. function getExtremes(attrs) {
  19173. var x = attrs.x,
  19174. y = attrs.y,
  19175. w = attrs.width,
  19176. h = attrs.height;
  19177. minX = Math.min(minX, x - w / 2);
  19178. maxX = Math.max(maxX, x + w / 2);
  19179. minY = Math.min(minY, y - h / 2);
  19180. maxY = Math.max(maxY, y + h / 2);
  19181. }
  19182. _.forEach(g.nodes(), function(v) { getExtremes(g.node(v)); });
  19183. _.forEach(g.edges(), function(e) {
  19184. var edge = g.edge(e);
  19185. if (_.has(edge, "x")) {
  19186. getExtremes(edge);
  19187. }
  19188. });
  19189. minX -= marginX;
  19190. minY -= marginY;
  19191. _.forEach(g.nodes(), function(v) {
  19192. var node = g.node(v);
  19193. node.x -= minX;
  19194. node.y -= minY;
  19195. });
  19196. _.forEach(g.edges(), function(e) {
  19197. var edge = g.edge(e);
  19198. _.forEach(edge.points, function(p) {
  19199. p.x -= minX;
  19200. p.y -= minY;
  19201. });
  19202. if (_.has(edge, "x")) { edge.x -= minX; }
  19203. if (_.has(edge, "y")) { edge.y -= minY; }
  19204. });
  19205. graphLabel.width = maxX - minX + marginX;
  19206. graphLabel.height = maxY - minY + marginY;
  19207. }
  19208. function assignNodeIntersects(g) {
  19209. _.forEach(g.edges(), function(e) {
  19210. var edge = g.edge(e),
  19211. nodeV = g.node(e.v),
  19212. nodeW = g.node(e.w),
  19213. p1, p2;
  19214. if (!edge.points) {
  19215. edge.points = [];
  19216. p1 = nodeW;
  19217. p2 = nodeV;
  19218. } else {
  19219. p1 = edge.points[0];
  19220. p2 = edge.points[edge.points.length - 1];
  19221. }
  19222. edge.points.unshift(util.intersectRect(nodeV, p1));
  19223. edge.points.push(util.intersectRect(nodeW, p2));
  19224. });
  19225. }
  19226. function fixupEdgeLabelCoords(g) {
  19227. _.forEach(g.edges(), function(e) {
  19228. var edge = g.edge(e);
  19229. if (_.has(edge, "x")) {
  19230. if (edge.labelpos === "l" || edge.labelpos === "r") {
  19231. edge.width -= edge.labeloffset;
  19232. }
  19233. switch (edge.labelpos) {
  19234. case "l": edge.x -= edge.width / 2 + edge.labeloffset; break;
  19235. case "r": edge.x += edge.width / 2 + edge.labeloffset; break;
  19236. }
  19237. }
  19238. });
  19239. }
  19240. function reversePointsForReversedEdges(g) {
  19241. _.forEach(g.edges(), function(e) {
  19242. var edge = g.edge(e);
  19243. if (edge.reversed) {
  19244. edge.points.reverse();
  19245. }
  19246. });
  19247. }
  19248. function removeBorderNodes(g) {
  19249. _.forEach(g.nodes(), function(v) {
  19250. if (g.children(v).length) {
  19251. var node = g.node(v),
  19252. t = g.node(node.borderTop),
  19253. b = g.node(node.borderBottom),
  19254. l = g.node(_.last(node.borderLeft)),
  19255. r = g.node(_.last(node.borderRight));
  19256. node.width = Math.abs(r.x - l.x);
  19257. node.height = Math.abs(b.y - t.y);
  19258. node.x = l.x + node.width / 2;
  19259. node.y = t.y + node.height / 2;
  19260. }
  19261. });
  19262. _.forEach(g.nodes(), function(v) {
  19263. if (g.node(v).dummy === "border") {
  19264. g.removeNode(v);
  19265. }
  19266. });
  19267. }
  19268. function removeSelfEdges(g) {
  19269. _.forEach(g.edges(), function(e) {
  19270. if (e.v === e.w) {
  19271. var node = g.node(e.v);
  19272. if (!node.selfEdges) {
  19273. node.selfEdges = [];
  19274. }
  19275. node.selfEdges.push({ e: e, label: g.edge(e) });
  19276. g.removeEdge(e);
  19277. }
  19278. });
  19279. }
  19280. function insertSelfEdges(g) {
  19281. var layers = util.buildLayerMatrix(g);
  19282. _.forEach(layers, function(layer) {
  19283. var orderShift = 0;
  19284. _.forEach(layer, function(v, i) {
  19285. var node = g.node(v);
  19286. node.order = i + orderShift;
  19287. _.forEach(node.selfEdges, function(selfEdge) {
  19288. util.addDummyNode(g, "selfedge", {
  19289. width: selfEdge.label.width,
  19290. height: selfEdge.label.height,
  19291. rank: node.rank,
  19292. order: i + (++orderShift),
  19293. e: selfEdge.e,
  19294. label: selfEdge.label
  19295. }, "_se");
  19296. });
  19297. delete node.selfEdges;
  19298. });
  19299. });
  19300. }
  19301. function positionSelfEdges(g) {
  19302. _.forEach(g.nodes(), function(v) {
  19303. var node = g.node(v);
  19304. if (node.dummy === "selfedge") {
  19305. var selfNode = g.node(node.e.v),
  19306. x = selfNode.x + selfNode.width / 2,
  19307. y = selfNode.y,
  19308. dx = node.x - x,
  19309. dy = selfNode.height / 2;
  19310. g.setEdge(node.e, node.label);
  19311. g.removeNode(v);
  19312. node.label.points = [
  19313. { x: x + 2 * dx / 3, y: y - dy },
  19314. { x: x + 5 * dx / 6, y: y - dy },
  19315. { x: x + dx , y: y },
  19316. { x: x + 5 * dx / 6, y: y + dy },
  19317. { x: x + 2 * dx / 3, y: y + dy }
  19318. ];
  19319. node.label.x = node.x;
  19320. node.label.y = node.y;
  19321. }
  19322. });
  19323. }
  19324. function selectNumberAttrs(obj, attrs) {
  19325. return _.mapValues(_.pick(obj, attrs), Number);
  19326. }
  19327. function canonicalize(attrs) {
  19328. var newAttrs = {};
  19329. _.forEach(attrs, function(v, k) {
  19330. newAttrs[k.toLowerCase()] = v;
  19331. });
  19332. return newAttrs;
  19333. }
  19334. },{"./acyclic":71,"./add-border-segments":72,"./coordinate-system":73,"./graphlib":76,"./lodash":79,"./nesting-graph":80,"./normalize":81,"./order":86,"./parent-dummy-chains":91,"./position":93,"./rank":95,"./util":98}],79:[function(require,module,exports){
  19335. /* global window */
  19336. var lodash;
  19337. if (typeof require === "function") {
  19338. try {
  19339. lodash = require("lodash");
  19340. } catch (e) {}
  19341. }
  19342. if (!lodash) {
  19343. lodash = window._;
  19344. }
  19345. module.exports = lodash;
  19346. },{"lodash":123}],80:[function(require,module,exports){
  19347. var _ = require("./lodash"),
  19348. util = require("./util");
  19349. module.exports = {
  19350. run: run,
  19351. cleanup: cleanup
  19352. };
  19353. /*
  19354. * A nesting graph creates dummy nodes for the tops and bottoms of subgraphs,
  19355. * adds appropriate edges to ensure that all cluster nodes are placed between
  19356. * these boundries, and ensures that the graph is connected.
  19357. *
  19358. * In addition we ensure, through the use of the minlen property, that nodes
  19359. * and subgraph border nodes to not end up on the same rank.
  19360. *
  19361. * Preconditions:
  19362. *
  19363. * 1. Input graph is a DAG
  19364. * 2. Nodes in the input graph has a minlen attribute
  19365. *
  19366. * Postconditions:
  19367. *
  19368. * 1. Input graph is connected.
  19369. * 2. Dummy nodes are added for the tops and bottoms of subgraphs.
  19370. * 3. The minlen attribute for nodes is adjusted to ensure nodes do not
  19371. * get placed on the same rank as subgraph border nodes.
  19372. *
  19373. * The nesting graph idea comes from Sander, "Layout of Compound Directed
  19374. * Graphs."
  19375. */
  19376. function run(g) {
  19377. var root = util.addDummyNode(g, "root", {}, "_root");
  19378. var depths = treeDepths(g);
  19379. var height = _.max(_.values(depths)) - 1; // Note: depths is an Object not an array
  19380. var nodeSep = 2 * height + 1;
  19381. g.graph().nestingRoot = root;
  19382. // Multiply minlen by nodeSep to align nodes on non-border ranks.
  19383. _.forEach(g.edges(), function(e) { g.edge(e).minlen *= nodeSep; });
  19384. // Calculate a weight that is sufficient to keep subgraphs vertically compact
  19385. var weight = sumWeights(g) + 1;
  19386. // Create border nodes and link them up
  19387. _.forEach(g.children(), function(child) {
  19388. dfs(g, root, nodeSep, weight, height, depths, child);
  19389. });
  19390. // Save the multiplier for node layers for later removal of empty border
  19391. // layers.
  19392. g.graph().nodeRankFactor = nodeSep;
  19393. }
  19394. function dfs(g, root, nodeSep, weight, height, depths, v) {
  19395. var children = g.children(v);
  19396. if (!children.length) {
  19397. if (v !== root) {
  19398. g.setEdge(root, v, { weight: 0, minlen: nodeSep });
  19399. }
  19400. return;
  19401. }
  19402. var top = util.addBorderNode(g, "_bt"),
  19403. bottom = util.addBorderNode(g, "_bb"),
  19404. label = g.node(v);
  19405. g.setParent(top, v);
  19406. label.borderTop = top;
  19407. g.setParent(bottom, v);
  19408. label.borderBottom = bottom;
  19409. _.forEach(children, function(child) {
  19410. dfs(g, root, nodeSep, weight, height, depths, child);
  19411. var childNode = g.node(child),
  19412. childTop = childNode.borderTop ? childNode.borderTop : child,
  19413. childBottom = childNode.borderBottom ? childNode.borderBottom : child,
  19414. thisWeight = childNode.borderTop ? weight : 2 * weight,
  19415. minlen = childTop !== childBottom ? 1 : height - depths[v] + 1;
  19416. g.setEdge(top, childTop, {
  19417. weight: thisWeight,
  19418. minlen: minlen,
  19419. nestingEdge: true
  19420. });
  19421. g.setEdge(childBottom, bottom, {
  19422. weight: thisWeight,
  19423. minlen: minlen,
  19424. nestingEdge: true
  19425. });
  19426. });
  19427. if (!g.parent(v)) {
  19428. g.setEdge(root, top, { weight: 0, minlen: height + depths[v] });
  19429. }
  19430. }
  19431. function treeDepths(g) {
  19432. var depths = {};
  19433. function dfs(v, depth) {
  19434. var children = g.children(v);
  19435. if (children && children.length) {
  19436. _.forEach(children, function(child) {
  19437. dfs(child, depth + 1);
  19438. });
  19439. }
  19440. depths[v] = depth;
  19441. }
  19442. _.forEach(g.children(), function(v) { dfs(v, 1); });
  19443. return depths;
  19444. }
  19445. function sumWeights(g) {
  19446. return _.reduce(g.edges(), function(acc, e) {
  19447. return acc + g.edge(e).weight;
  19448. }, 0);
  19449. }
  19450. function cleanup(g) {
  19451. var graphLabel = g.graph();
  19452. g.removeNode(graphLabel.nestingRoot);
  19453. delete graphLabel.nestingRoot;
  19454. _.forEach(g.edges(), function(e) {
  19455. var edge = g.edge(e);
  19456. if (edge.nestingEdge) {
  19457. g.removeEdge(e);
  19458. }
  19459. });
  19460. }
  19461. },{"./lodash":79,"./util":98}],81:[function(require,module,exports){
  19462. "use strict";
  19463. var _ = require("./lodash"),
  19464. util = require("./util");
  19465. module.exports = {
  19466. run: run,
  19467. undo: undo
  19468. };
  19469. /*
  19470. * Breaks any long edges in the graph into short segments that span 1 layer
  19471. * each. This operation is undoable with the denormalize function.
  19472. *
  19473. * Pre-conditions:
  19474. *
  19475. * 1. The input graph is a DAG.
  19476. * 2. Each node in the graph has a "rank" property.
  19477. *
  19478. * Post-condition:
  19479. *
  19480. * 1. All edges in the graph have a length of 1.
  19481. * 2. Dummy nodes are added where edges have been split into segments.
  19482. * 3. The graph is augmented with a "dummyChains" attribute which contains
  19483. * the first dummy in each chain of dummy nodes produced.
  19484. */
  19485. function run(g) {
  19486. g.graph().dummyChains = [];
  19487. _.forEach(g.edges(), function(edge) { normalizeEdge(g, edge); });
  19488. }
  19489. function normalizeEdge(g, e) {
  19490. var v = e.v,
  19491. vRank = g.node(v).rank,
  19492. w = e.w,
  19493. wRank = g.node(w).rank,
  19494. name = e.name,
  19495. edgeLabel = g.edge(e),
  19496. labelRank = edgeLabel.labelRank;
  19497. if (wRank === vRank + 1) return;
  19498. g.removeEdge(e);
  19499. var dummy, attrs, i;
  19500. for (i = 0, ++vRank; vRank < wRank; ++i, ++vRank) {
  19501. edgeLabel.points = [];
  19502. attrs = {
  19503. width: 0, height: 0,
  19504. edgeLabel: edgeLabel, edgeObj: e,
  19505. rank: vRank
  19506. };
  19507. dummy = util.addDummyNode(g, "edge", attrs, "_d");
  19508. if (vRank === labelRank) {
  19509. attrs.width = edgeLabel.width;
  19510. attrs.height = edgeLabel.height;
  19511. attrs.dummy = "edge-label";
  19512. attrs.labelpos = edgeLabel.labelpos;
  19513. }
  19514. g.setEdge(v, dummy, { weight: edgeLabel.weight }, name);
  19515. if (i === 0) {
  19516. g.graph().dummyChains.push(dummy);
  19517. }
  19518. v = dummy;
  19519. }
  19520. g.setEdge(v, w, { weight: edgeLabel.weight }, name);
  19521. }
  19522. function undo(g) {
  19523. _.forEach(g.graph().dummyChains, function(v) {
  19524. var node = g.node(v),
  19525. origLabel = node.edgeLabel,
  19526. w;
  19527. g.setEdge(node.edgeObj, origLabel);
  19528. while (node.dummy) {
  19529. w = g.successors(v)[0];
  19530. g.removeNode(v);
  19531. origLabel.points.push({ x: node.x, y: node.y });
  19532. if (node.dummy === "edge-label") {
  19533. origLabel.x = node.x;
  19534. origLabel.y = node.y;
  19535. origLabel.width = node.width;
  19536. origLabel.height = node.height;
  19537. }
  19538. v = w;
  19539. node = g.node(v);
  19540. }
  19541. });
  19542. }
  19543. },{"./lodash":79,"./util":98}],82:[function(require,module,exports){
  19544. var _ = require("../lodash");
  19545. module.exports = addSubgraphConstraints;
  19546. function addSubgraphConstraints(g, cg, vs) {
  19547. var prev = {},
  19548. rootPrev;
  19549. _.forEach(vs, function(v) {
  19550. var child = g.parent(v),
  19551. parent,
  19552. prevChild;
  19553. while (child) {
  19554. parent = g.parent(child);
  19555. if (parent) {
  19556. prevChild = prev[parent];
  19557. prev[parent] = child;
  19558. } else {
  19559. prevChild = rootPrev;
  19560. rootPrev = child;
  19561. }
  19562. if (prevChild && prevChild !== child) {
  19563. cg.setEdge(prevChild, child);
  19564. return;
  19565. }
  19566. child = parent;
  19567. }
  19568. });
  19569. /*
  19570. function dfs(v) {
  19571. var children = v ? g.children(v) : g.children();
  19572. if (children.length) {
  19573. var min = Number.POSITIVE_INFINITY,
  19574. subgraphs = [];
  19575. _.each(children, function(child) {
  19576. var childMin = dfs(child);
  19577. if (g.children(child).length) {
  19578. subgraphs.push({ v: child, order: childMin });
  19579. }
  19580. min = Math.min(min, childMin);
  19581. });
  19582. _.reduce(_.sortBy(subgraphs, "order"), function(prev, curr) {
  19583. cg.setEdge(prev.v, curr.v);
  19584. return curr;
  19585. });
  19586. return min;
  19587. }
  19588. return g.node(v).order;
  19589. }
  19590. dfs(undefined);
  19591. */
  19592. }
  19593. },{"../lodash":79}],83:[function(require,module,exports){
  19594. var _ = require("../lodash");
  19595. module.exports = barycenter;
  19596. function barycenter(g, movable) {
  19597. return _.map(movable, function(v) {
  19598. var inV = g.inEdges(v);
  19599. if (!inV.length) {
  19600. return { v: v };
  19601. } else {
  19602. var result = _.reduce(inV, function(acc, e) {
  19603. var edge = g.edge(e),
  19604. nodeU = g.node(e.v);
  19605. return {
  19606. sum: acc.sum + (edge.weight * nodeU.order),
  19607. weight: acc.weight + edge.weight
  19608. };
  19609. }, { sum: 0, weight: 0 });
  19610. return {
  19611. v: v,
  19612. barycenter: result.sum / result.weight,
  19613. weight: result.weight
  19614. };
  19615. }
  19616. });
  19617. }
  19618. },{"../lodash":79}],84:[function(require,module,exports){
  19619. var _ = require("../lodash"),
  19620. Graph = require("../graphlib").Graph;
  19621. module.exports = buildLayerGraph;
  19622. /*
  19623. * Constructs a graph that can be used to sort a layer of nodes. The graph will
  19624. * contain all base and subgraph nodes from the request layer in their original
  19625. * hierarchy and any edges that are incident on these nodes and are of the type
  19626. * requested by the "relationship" parameter.
  19627. *
  19628. * Nodes from the requested rank that do not have parents are assigned a root
  19629. * node in the output graph, which is set in the root graph attribute. This
  19630. * makes it easy to walk the hierarchy of movable nodes during ordering.
  19631. *
  19632. * Pre-conditions:
  19633. *
  19634. * 1. Input graph is a DAG
  19635. * 2. Base nodes in the input graph have a rank attribute
  19636. * 3. Subgraph nodes in the input graph has minRank and maxRank attributes
  19637. * 4. Edges have an assigned weight
  19638. *
  19639. * Post-conditions:
  19640. *
  19641. * 1. Output graph has all nodes in the movable rank with preserved
  19642. * hierarchy.
  19643. * 2. Root nodes in the movable layer are made children of the node
  19644. * indicated by the root attribute of the graph.
  19645. * 3. Non-movable nodes incident on movable nodes, selected by the
  19646. * relationship parameter, are included in the graph (without hierarchy).
  19647. * 4. Edges incident on movable nodes, selected by the relationship
  19648. * parameter, are added to the output graph.
  19649. * 5. The weights for copied edges are aggregated as need, since the output
  19650. * graph is not a multi-graph.
  19651. */
  19652. function buildLayerGraph(g, rank, relationship) {
  19653. var root = createRootNode(g),
  19654. result = new Graph({ compound: true }).setGraph({ root: root })
  19655. .setDefaultNodeLabel(function(v) { return g.node(v); });
  19656. _.forEach(g.nodes(), function(v) {
  19657. var node = g.node(v),
  19658. parent = g.parent(v);
  19659. if (node.rank === rank || node.minRank <= rank && rank <= node.maxRank) {
  19660. result.setNode(v);
  19661. result.setParent(v, parent || root);
  19662. // This assumes we have only short edges!
  19663. _.forEach(g[relationship](v), function(e) {
  19664. var u = e.v === v ? e.w : e.v,
  19665. edge = result.edge(u, v),
  19666. weight = !_.isUndefined(edge) ? edge.weight : 0;
  19667. result.setEdge(u, v, { weight: g.edge(e).weight + weight });
  19668. });
  19669. if (_.has(node, "minRank")) {
  19670. result.setNode(v, {
  19671. borderLeft: node.borderLeft[rank],
  19672. borderRight: node.borderRight[rank]
  19673. });
  19674. }
  19675. }
  19676. });
  19677. return result;
  19678. }
  19679. function createRootNode(g) {
  19680. var v;
  19681. while (g.hasNode((v = _.uniqueId("_root"))));
  19682. return v;
  19683. }
  19684. },{"../graphlib":76,"../lodash":79}],85:[function(require,module,exports){
  19685. "use strict";
  19686. var _ = require("../lodash");
  19687. module.exports = crossCount;
  19688. /*
  19689. * A function that takes a layering (an array of layers, each with an array of
  19690. * ordererd nodes) and a graph and returns a weighted crossing count.
  19691. *
  19692. * Pre-conditions:
  19693. *
  19694. * 1. Input graph must be simple (not a multigraph), directed, and include
  19695. * only simple edges.
  19696. * 2. Edges in the input graph must have assigned weights.
  19697. *
  19698. * Post-conditions:
  19699. *
  19700. * 1. The graph and layering matrix are left unchanged.
  19701. *
  19702. * This algorithm is derived from Barth, et al., "Bilayer Cross Counting."
  19703. */
  19704. function crossCount(g, layering) {
  19705. var cc = 0;
  19706. for (var i = 1; i < layering.length; ++i) {
  19707. cc += twoLayerCrossCount(g, layering[i-1], layering[i]);
  19708. }
  19709. return cc;
  19710. }
  19711. function twoLayerCrossCount(g, northLayer, southLayer) {
  19712. // Sort all of the edges between the north and south layers by their position
  19713. // in the north layer and then the south. Map these edges to the position of
  19714. // their head in the south layer.
  19715. var southPos = _.zipObject(southLayer,
  19716. _.map(southLayer, function (v, i) { return i; }));
  19717. var southEntries = _.flatten(_.map(northLayer, function(v) {
  19718. return _.chain(g.outEdges(v))
  19719. .map(function(e) {
  19720. return { pos: southPos[e.w], weight: g.edge(e).weight };
  19721. })
  19722. .sortBy("pos")
  19723. .value();
  19724. }), true);
  19725. // Build the accumulator tree
  19726. var firstIndex = 1;
  19727. while (firstIndex < southLayer.length) firstIndex <<= 1;
  19728. var treeSize = 2 * firstIndex - 1;
  19729. firstIndex -= 1;
  19730. var tree = _.map(new Array(treeSize), function() { return 0; });
  19731. // Calculate the weighted crossings
  19732. var cc = 0;
  19733. _.forEach(southEntries.forEach(function(entry) {
  19734. var index = entry.pos + firstIndex;
  19735. tree[index] += entry.weight;
  19736. var weightSum = 0;
  19737. while (index > 0) {
  19738. if (index % 2) {
  19739. weightSum += tree[index + 1];
  19740. }
  19741. index = (index - 1) >> 1;
  19742. tree[index] += entry.weight;
  19743. }
  19744. cc += entry.weight * weightSum;
  19745. }));
  19746. return cc;
  19747. }
  19748. },{"../lodash":79}],86:[function(require,module,exports){
  19749. "use strict";
  19750. var _ = require("../lodash"),
  19751. initOrder = require("./init-order"),
  19752. crossCount = require("./cross-count"),
  19753. sortSubgraph = require("./sort-subgraph"),
  19754. buildLayerGraph = require("./build-layer-graph"),
  19755. addSubgraphConstraints = require("./add-subgraph-constraints"),
  19756. Graph = require("../graphlib").Graph,
  19757. util = require("../util");
  19758. module.exports = order;
  19759. /*
  19760. * Applies heuristics to minimize edge crossings in the graph and sets the best
  19761. * order solution as an order attribute on each node.
  19762. *
  19763. * Pre-conditions:
  19764. *
  19765. * 1. Graph must be DAG
  19766. * 2. Graph nodes must be objects with a "rank" attribute
  19767. * 3. Graph edges must have the "weight" attribute
  19768. *
  19769. * Post-conditions:
  19770. *
  19771. * 1. Graph nodes will have an "order" attribute based on the results of the
  19772. * algorithm.
  19773. */
  19774. function order(g) {
  19775. var maxRank = util.maxRank(g),
  19776. downLayerGraphs = buildLayerGraphs(g, _.range(1, maxRank + 1), "inEdges"),
  19777. upLayerGraphs = buildLayerGraphs(g, _.range(maxRank - 1, -1, -1), "outEdges");
  19778. var layering = initOrder(g);
  19779. assignOrder(g, layering);
  19780. var bestCC = Number.POSITIVE_INFINITY,
  19781. best;
  19782. for (var i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) {
  19783. sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2);
  19784. layering = util.buildLayerMatrix(g);
  19785. var cc = crossCount(g, layering);
  19786. if (cc < bestCC) {
  19787. lastBest = 0;
  19788. best = _.cloneDeep(layering);
  19789. bestCC = cc;
  19790. }
  19791. }
  19792. assignOrder(g, best);
  19793. }
  19794. function buildLayerGraphs(g, ranks, relationship) {
  19795. return _.map(ranks, function(rank) {
  19796. return buildLayerGraph(g, rank, relationship);
  19797. });
  19798. }
  19799. function sweepLayerGraphs(layerGraphs, biasRight) {
  19800. var cg = new Graph();
  19801. _.forEach(layerGraphs, function(lg) {
  19802. var root = lg.graph().root;
  19803. var sorted = sortSubgraph(lg, root, cg, biasRight);
  19804. _.forEach(sorted.vs, function(v, i) {
  19805. lg.node(v).order = i;
  19806. });
  19807. addSubgraphConstraints(lg, cg, sorted.vs);
  19808. });
  19809. }
  19810. function assignOrder(g, layering) {
  19811. _.forEach(layering, function(layer) {
  19812. _.forEach(layer, function(v, i) {
  19813. g.node(v).order = i;
  19814. });
  19815. });
  19816. }
  19817. },{"../graphlib":76,"../lodash":79,"../util":98,"./add-subgraph-constraints":82,"./build-layer-graph":84,"./cross-count":85,"./init-order":87,"./sort-subgraph":89}],87:[function(require,module,exports){
  19818. "use strict";
  19819. var _ = require("../lodash");
  19820. module.exports = initOrder;
  19821. /*
  19822. * Assigns an initial order value for each node by performing a DFS search
  19823. * starting from nodes in the first rank. Nodes are assigned an order in their
  19824. * rank as they are first visited.
  19825. *
  19826. * This approach comes from Gansner, et al., "A Technique for Drawing Directed
  19827. * Graphs."
  19828. *
  19829. * Returns a layering matrix with an array per layer and each layer sorted by
  19830. * the order of its nodes.
  19831. */
  19832. function initOrder(g) {
  19833. var visited = {},
  19834. simpleNodes = _.filter(g.nodes(), function(v) {
  19835. return !g.children(v).length;
  19836. }),
  19837. maxRank = _.max(_.map(simpleNodes, function(v) { return g.node(v).rank; })),
  19838. layers = _.map(_.range(maxRank + 1), function() { return []; });
  19839. function dfs(v) {
  19840. if (_.has(visited, v)) return;
  19841. visited[v] = true;
  19842. var node = g.node(v);
  19843. layers[node.rank].push(v);
  19844. _.forEach(g.successors(v), dfs);
  19845. }
  19846. var orderedVs = _.sortBy(simpleNodes, function(v) { return g.node(v).rank; });
  19847. _.forEach(orderedVs, dfs);
  19848. return layers;
  19849. }
  19850. },{"../lodash":79}],88:[function(require,module,exports){
  19851. "use strict";
  19852. var _ = require("../lodash");
  19853. module.exports = resolveConflicts;
  19854. /*
  19855. * Given a list of entries of the form {v, barycenter, weight} and a
  19856. * constraint graph this function will resolve any conflicts between the
  19857. * constraint graph and the barycenters for the entries. If the barycenters for
  19858. * an entry would violate a constraint in the constraint graph then we coalesce
  19859. * the nodes in the conflict into a new node that respects the contraint and
  19860. * aggregates barycenter and weight information.
  19861. *
  19862. * This implementation is based on the description in Forster, "A Fast and
  19863. * Simple Hueristic for Constrained Two-Level Crossing Reduction," thought it
  19864. * differs in some specific details.
  19865. *
  19866. * Pre-conditions:
  19867. *
  19868. * 1. Each entry has the form {v, barycenter, weight}, or if the node has
  19869. * no barycenter, then {v}.
  19870. *
  19871. * Returns:
  19872. *
  19873. * A new list of entries of the form {vs, i, barycenter, weight}. The list
  19874. * `vs` may either be a singleton or it may be an aggregation of nodes
  19875. * ordered such that they do not violate constraints from the constraint
  19876. * graph. The property `i` is the lowest original index of any of the
  19877. * elements in `vs`.
  19878. */
  19879. function resolveConflicts(entries, cg) {
  19880. var mappedEntries = {};
  19881. _.forEach(entries, function(entry, i) {
  19882. var tmp = mappedEntries[entry.v] = {
  19883. indegree: 0,
  19884. "in": [],
  19885. out: [],
  19886. vs: [entry.v],
  19887. i: i
  19888. };
  19889. if (!_.isUndefined(entry.barycenter)) {
  19890. tmp.barycenter = entry.barycenter;
  19891. tmp.weight = entry.weight;
  19892. }
  19893. });
  19894. _.forEach(cg.edges(), function(e) {
  19895. var entryV = mappedEntries[e.v],
  19896. entryW = mappedEntries[e.w];
  19897. if (!_.isUndefined(entryV) && !_.isUndefined(entryW)) {
  19898. entryW.indegree++;
  19899. entryV.out.push(mappedEntries[e.w]);
  19900. }
  19901. });
  19902. var sourceSet = _.filter(mappedEntries, function(entry) {
  19903. return !entry.indegree;
  19904. });
  19905. return doResolveConflicts(sourceSet);
  19906. }
  19907. function doResolveConflicts(sourceSet) {
  19908. var entries = [];
  19909. function handleIn(vEntry) {
  19910. return function(uEntry) {
  19911. if (uEntry.merged) {
  19912. return;
  19913. }
  19914. if (_.isUndefined(uEntry.barycenter) ||
  19915. _.isUndefined(vEntry.barycenter) ||
  19916. uEntry.barycenter >= vEntry.barycenter) {
  19917. mergeEntries(vEntry, uEntry);
  19918. }
  19919. };
  19920. }
  19921. function handleOut(vEntry) {
  19922. return function(wEntry) {
  19923. wEntry["in"].push(vEntry);
  19924. if (--wEntry.indegree === 0) {
  19925. sourceSet.push(wEntry);
  19926. }
  19927. };
  19928. }
  19929. while (sourceSet.length) {
  19930. var entry = sourceSet.pop();
  19931. entries.push(entry);
  19932. _.forEach(entry["in"].reverse(), handleIn(entry));
  19933. _.forEach(entry.out, handleOut(entry));
  19934. }
  19935. return _.chain(entries)
  19936. .filter(function(entry) { return !entry.merged; })
  19937. .map(function(entry) {
  19938. return _.pick(entry, ["vs", "i", "barycenter", "weight"]);
  19939. })
  19940. .value();
  19941. }
  19942. function mergeEntries(target, source) {
  19943. var sum = 0,
  19944. weight = 0;
  19945. if (target.weight) {
  19946. sum += target.barycenter * target.weight;
  19947. weight += target.weight;
  19948. }
  19949. if (source.weight) {
  19950. sum += source.barycenter * source.weight;
  19951. weight += source.weight;
  19952. }
  19953. target.vs = source.vs.concat(target.vs);
  19954. target.barycenter = sum / weight;
  19955. target.weight = weight;
  19956. target.i = Math.min(source.i, target.i);
  19957. source.merged = true;
  19958. }
  19959. },{"../lodash":79}],89:[function(require,module,exports){
  19960. var _ = require("../lodash"),
  19961. barycenter = require("./barycenter"),
  19962. resolveConflicts = require("./resolve-conflicts"),
  19963. sort = require("./sort");
  19964. module.exports = sortSubgraph;
  19965. function sortSubgraph(g, v, cg, biasRight) {
  19966. var movable = g.children(v),
  19967. node = g.node(v),
  19968. bl = node ? node.borderLeft : undefined,
  19969. br = node ? node.borderRight: undefined,
  19970. subgraphs = {};
  19971. if (bl) {
  19972. movable = _.filter(movable, function(w) {
  19973. return w !== bl && w !== br;
  19974. });
  19975. }
  19976. var barycenters = barycenter(g, movable);
  19977. _.forEach(barycenters, function(entry) {
  19978. if (g.children(entry.v).length) {
  19979. var subgraphResult = sortSubgraph(g, entry.v, cg, biasRight);
  19980. subgraphs[entry.v] = subgraphResult;
  19981. if (_.has(subgraphResult, "barycenter")) {
  19982. mergeBarycenters(entry, subgraphResult);
  19983. }
  19984. }
  19985. });
  19986. var entries = resolveConflicts(barycenters, cg);
  19987. expandSubgraphs(entries, subgraphs);
  19988. var result = sort(entries, biasRight);
  19989. if (bl) {
  19990. result.vs = _.flatten([bl, result.vs, br], true);
  19991. if (g.predecessors(bl).length) {
  19992. var blPred = g.node(g.predecessors(bl)[0]),
  19993. brPred = g.node(g.predecessors(br)[0]);
  19994. if (!_.has(result, "barycenter")) {
  19995. result.barycenter = 0;
  19996. result.weight = 0;
  19997. }
  19998. result.barycenter = (result.barycenter * result.weight +
  19999. blPred.order + brPred.order) / (result.weight + 2);
  20000. result.weight += 2;
  20001. }
  20002. }
  20003. return result;
  20004. }
  20005. function expandSubgraphs(entries, subgraphs) {
  20006. _.forEach(entries, function(entry) {
  20007. entry.vs = _.flatten(entry.vs.map(function(v) {
  20008. if (subgraphs[v]) {
  20009. return subgraphs[v].vs;
  20010. }
  20011. return v;
  20012. }), true);
  20013. });
  20014. }
  20015. function mergeBarycenters(target, other) {
  20016. if (!_.isUndefined(target.barycenter)) {
  20017. target.barycenter = (target.barycenter * target.weight +
  20018. other.barycenter * other.weight) /
  20019. (target.weight + other.weight);
  20020. target.weight += other.weight;
  20021. } else {
  20022. target.barycenter = other.barycenter;
  20023. target.weight = other.weight;
  20024. }
  20025. }
  20026. },{"../lodash":79,"./barycenter":83,"./resolve-conflicts":88,"./sort":90}],90:[function(require,module,exports){
  20027. var _ = require("../lodash"),
  20028. util = require("../util");
  20029. module.exports = sort;
  20030. function sort(entries, biasRight) {
  20031. var parts = util.partition(entries, function(entry) {
  20032. return _.has(entry, "barycenter");
  20033. });
  20034. var sortable = parts.lhs,
  20035. unsortable = _.sortBy(parts.rhs, function(entry) { return -entry.i; }),
  20036. vs = [],
  20037. sum = 0,
  20038. weight = 0,
  20039. vsIndex = 0;
  20040. sortable.sort(compareWithBias(!!biasRight));
  20041. vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  20042. _.forEach(sortable, function (entry) {
  20043. vsIndex += entry.vs.length;
  20044. vs.push(entry.vs);
  20045. sum += entry.barycenter * entry.weight;
  20046. weight += entry.weight;
  20047. vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  20048. });
  20049. var result = { vs: _.flatten(vs, true) };
  20050. if (weight) {
  20051. result.barycenter = sum / weight;
  20052. result.weight = weight;
  20053. }
  20054. return result;
  20055. }
  20056. function consumeUnsortable(vs, unsortable, index) {
  20057. var last;
  20058. while (unsortable.length && (last = _.last(unsortable)).i <= index) {
  20059. unsortable.pop();
  20060. vs.push(last.vs);
  20061. index++;
  20062. }
  20063. return index;
  20064. }
  20065. function compareWithBias(bias) {
  20066. return function(entryV, entryW) {
  20067. if (entryV.barycenter < entryW.barycenter) {
  20068. return -1;
  20069. } else if (entryV.barycenter > entryW.barycenter) {
  20070. return 1;
  20071. }
  20072. return !bias ? entryV.i - entryW.i : entryW.i - entryV.i;
  20073. };
  20074. }
  20075. },{"../lodash":79,"../util":98}],91:[function(require,module,exports){
  20076. var _ = require("./lodash");
  20077. module.exports = parentDummyChains;
  20078. function parentDummyChains(g) {
  20079. var postorderNums = postorder(g);
  20080. _.forEach(g.graph().dummyChains, function(v) {
  20081. var node = g.node(v),
  20082. edgeObj = node.edgeObj,
  20083. pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w),
  20084. path = pathData.path,
  20085. lca = pathData.lca,
  20086. pathIdx = 0,
  20087. pathV = path[pathIdx],
  20088. ascending = true;
  20089. while (v !== edgeObj.w) {
  20090. node = g.node(v);
  20091. if (ascending) {
  20092. while ((pathV = path[pathIdx]) !== lca &&
  20093. g.node(pathV).maxRank < node.rank) {
  20094. pathIdx++;
  20095. }
  20096. if (pathV === lca) {
  20097. ascending = false;
  20098. }
  20099. }
  20100. if (!ascending) {
  20101. while (pathIdx < path.length - 1 &&
  20102. g.node(pathV = path[pathIdx + 1]).minRank <= node.rank) {
  20103. pathIdx++;
  20104. }
  20105. pathV = path[pathIdx];
  20106. }
  20107. g.setParent(v, pathV);
  20108. v = g.successors(v)[0];
  20109. }
  20110. });
  20111. }
  20112. // Find a path from v to w through the lowest common ancestor (LCA). Return the
  20113. // full path and the LCA.
  20114. function findPath(g, postorderNums, v, w) {
  20115. var vPath = [],
  20116. wPath = [],
  20117. low = Math.min(postorderNums[v].low, postorderNums[w].low),
  20118. lim = Math.max(postorderNums[v].lim, postorderNums[w].lim),
  20119. parent,
  20120. lca;
  20121. // Traverse up from v to find the LCA
  20122. parent = v;
  20123. do {
  20124. parent = g.parent(parent);
  20125. vPath.push(parent);
  20126. } while (parent &&
  20127. (postorderNums[parent].low > low || lim > postorderNums[parent].lim));
  20128. lca = parent;
  20129. // Traverse from w to LCA
  20130. parent = w;
  20131. while ((parent = g.parent(parent)) !== lca) {
  20132. wPath.push(parent);
  20133. }
  20134. return { path: vPath.concat(wPath.reverse()), lca: lca };
  20135. }
  20136. function postorder(g) {
  20137. var result = {},
  20138. lim = 0;
  20139. function dfs(v) {
  20140. var low = lim;
  20141. _.forEach(g.children(v), dfs);
  20142. result[v] = { low: low, lim: lim++ };
  20143. }
  20144. _.forEach(g.children(), dfs);
  20145. return result;
  20146. }
  20147. },{"./lodash":79}],92:[function(require,module,exports){
  20148. "use strict";
  20149. var _ = require("../lodash"),
  20150. Graph = require("../graphlib").Graph,
  20151. util = require("../util");
  20152. /*
  20153. * This module provides coordinate assignment based on Brandes and Köpf, "Fast
  20154. * and Simple Horizontal Coordinate Assignment."
  20155. */
  20156. module.exports = {
  20157. positionX: positionX,
  20158. findType1Conflicts: findType1Conflicts,
  20159. findType2Conflicts: findType2Conflicts,
  20160. addConflict: addConflict,
  20161. hasConflict: hasConflict,
  20162. verticalAlignment: verticalAlignment,
  20163. horizontalCompaction: horizontalCompaction,
  20164. alignCoordinates: alignCoordinates,
  20165. findSmallestWidthAlignment: findSmallestWidthAlignment,
  20166. balance: balance
  20167. };
  20168. /*
  20169. * Marks all edges in the graph with a type-1 conflict with the "type1Conflict"
  20170. * property. A type-1 conflict is one where a non-inner segment crosses an
  20171. * inner segment. An inner segment is an edge with both incident nodes marked
  20172. * with the "dummy" property.
  20173. *
  20174. * This algorithm scans layer by layer, starting with the second, for type-1
  20175. * conflicts between the current layer and the previous layer. For each layer
  20176. * it scans the nodes from left to right until it reaches one that is incident
  20177. * on an inner segment. It then scans predecessors to determine if they have
  20178. * edges that cross that inner segment. At the end a final scan is done for all
  20179. * nodes on the current rank to see if they cross the last visited inner
  20180. * segment.
  20181. *
  20182. * This algorithm (safely) assumes that a dummy node will only be incident on a
  20183. * single node in the layers being scanned.
  20184. */
  20185. function findType1Conflicts(g, layering) {
  20186. var conflicts = {};
  20187. function visitLayer(prevLayer, layer) {
  20188. var
  20189. // last visited node in the previous layer that is incident on an inner
  20190. // segment.
  20191. k0 = 0,
  20192. // Tracks the last node in this layer scanned for crossings with a type-1
  20193. // segment.
  20194. scanPos = 0,
  20195. prevLayerLength = prevLayer.length,
  20196. lastNode = _.last(layer);
  20197. _.forEach(layer, function(v, i) {
  20198. var w = findOtherInnerSegmentNode(g, v),
  20199. k1 = w ? g.node(w).order : prevLayerLength;
  20200. if (w || v === lastNode) {
  20201. _.forEach(layer.slice(scanPos, i +1), function(scanNode) {
  20202. _.forEach(g.predecessors(scanNode), function(u) {
  20203. var uLabel = g.node(u),
  20204. uPos = uLabel.order;
  20205. if ((uPos < k0 || k1 < uPos) &&
  20206. !(uLabel.dummy && g.node(scanNode).dummy)) {
  20207. addConflict(conflicts, u, scanNode);
  20208. }
  20209. });
  20210. });
  20211. scanPos = i + 1;
  20212. k0 = k1;
  20213. }
  20214. });
  20215. return layer;
  20216. }
  20217. _.reduce(layering, visitLayer);
  20218. return conflicts;
  20219. }
  20220. function findType2Conflicts(g, layering) {
  20221. var conflicts = {};
  20222. function scan(south, southPos, southEnd, prevNorthBorder, nextNorthBorder) {
  20223. var v;
  20224. _.forEach(_.range(southPos, southEnd), function(i) {
  20225. v = south[i];
  20226. if (g.node(v).dummy) {
  20227. _.forEach(g.predecessors(v), function(u) {
  20228. var uNode = g.node(u);
  20229. if (uNode.dummy &&
  20230. (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {
  20231. addConflict(conflicts, u, v);
  20232. }
  20233. });
  20234. }
  20235. });
  20236. }
  20237. function visitLayer(north, south) {
  20238. var prevNorthPos = -1,
  20239. nextNorthPos,
  20240. southPos = 0;
  20241. _.forEach(south, function(v, southLookahead) {
  20242. if (g.node(v).dummy === "border") {
  20243. var predecessors = g.predecessors(v);
  20244. if (predecessors.length) {
  20245. nextNorthPos = g.node(predecessors[0]).order;
  20246. scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);
  20247. southPos = southLookahead;
  20248. prevNorthPos = nextNorthPos;
  20249. }
  20250. }
  20251. scan(south, southPos, south.length, nextNorthPos, north.length);
  20252. });
  20253. return south;
  20254. }
  20255. _.reduce(layering, visitLayer);
  20256. return conflicts;
  20257. }
  20258. function findOtherInnerSegmentNode(g, v) {
  20259. if (g.node(v).dummy) {
  20260. return _.find(g.predecessors(v), function(u) {
  20261. return g.node(u).dummy;
  20262. });
  20263. }
  20264. }
  20265. function addConflict(conflicts, v, w) {
  20266. if (v > w) {
  20267. var tmp = v;
  20268. v = w;
  20269. w = tmp;
  20270. }
  20271. var conflictsV = conflicts[v];
  20272. if (!conflictsV) {
  20273. conflicts[v] = conflictsV = {};
  20274. }
  20275. conflictsV[w] = true;
  20276. }
  20277. function hasConflict(conflicts, v, w) {
  20278. if (v > w) {
  20279. var tmp = v;
  20280. v = w;
  20281. w = tmp;
  20282. }
  20283. return _.has(conflicts[v], w);
  20284. }
  20285. /*
  20286. * Try to align nodes into vertical "blocks" where possible. This algorithm
  20287. * attempts to align a node with one of its median neighbors. If the edge
  20288. * connecting a neighbor is a type-1 conflict then we ignore that possibility.
  20289. * If a previous node has already formed a block with a node after the node
  20290. * we're trying to form a block with, we also ignore that possibility - our
  20291. * blocks would be split in that scenario.
  20292. */
  20293. function verticalAlignment(g, layering, conflicts, neighborFn) {
  20294. var root = {},
  20295. align = {},
  20296. pos = {};
  20297. // We cache the position here based on the layering because the graph and
  20298. // layering may be out of sync. The layering matrix is manipulated to
  20299. // generate different extreme alignments.
  20300. _.forEach(layering, function(layer) {
  20301. _.forEach(layer, function(v, order) {
  20302. root[v] = v;
  20303. align[v] = v;
  20304. pos[v] = order;
  20305. });
  20306. });
  20307. _.forEach(layering, function(layer) {
  20308. var prevIdx = -1;
  20309. _.forEach(layer, function(v) {
  20310. var ws = neighborFn(v);
  20311. if (ws.length) {
  20312. ws = _.sortBy(ws, function(w) { return pos[w]; });
  20313. var mp = (ws.length - 1) / 2;
  20314. for (var i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) {
  20315. var w = ws[i];
  20316. if (align[v] === v &&
  20317. prevIdx < pos[w] &&
  20318. !hasConflict(conflicts, v, w)) {
  20319. align[w] = v;
  20320. align[v] = root[v] = root[w];
  20321. prevIdx = pos[w];
  20322. }
  20323. }
  20324. }
  20325. });
  20326. });
  20327. return { root: root, align: align };
  20328. }
  20329. function horizontalCompaction(g, layering, root, align, reverseSep) {
  20330. // This portion of the algorithm differs from BK due to a number of problems.
  20331. // Instead of their algorithm we construct a new block graph and do two
  20332. // sweeps. The first sweep places blocks with the smallest possible
  20333. // coordinates. The second sweep removes unused space by moving blocks to the
  20334. // greatest coordinates without violating separation.
  20335. var xs = {},
  20336. blockG = buildBlockGraph(g, layering, root, reverseSep);
  20337. // First pass, assign smallest coordinates via DFS
  20338. var visited = {};
  20339. function pass1(v) {
  20340. if (!_.has(visited, v)) {
  20341. visited[v] = true;
  20342. xs[v] = _.reduce(blockG.inEdges(v), function(max, e) {
  20343. pass1(e.v);
  20344. return Math.max(max, xs[e.v] + blockG.edge(e));
  20345. }, 0);
  20346. }
  20347. }
  20348. _.forEach(blockG.nodes(), pass1);
  20349. var borderType = reverseSep ? "borderLeft" : "borderRight";
  20350. function pass2(v) {
  20351. if (visited[v] !== 2) {
  20352. visited[v]++;
  20353. var node = g.node(v);
  20354. var min = _.reduce(blockG.outEdges(v), function(min, e) {
  20355. pass2(e.w);
  20356. return Math.min(min, xs[e.w] - blockG.edge(e));
  20357. }, Number.POSITIVE_INFINITY);
  20358. if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) {
  20359. xs[v] = Math.max(xs[v], min);
  20360. }
  20361. }
  20362. }
  20363. _.forEach(blockG.nodes(), pass2);
  20364. // Assign x coordinates to all nodes
  20365. _.forEach(align, function(v) {
  20366. xs[v] = xs[root[v]];
  20367. });
  20368. return xs;
  20369. }
  20370. function buildBlockGraph(g, layering, root, reverseSep) {
  20371. var blockGraph = new Graph(),
  20372. graphLabel = g.graph(),
  20373. sepFn = sep(graphLabel.nodesep, graphLabel.edgesep, reverseSep);
  20374. _.forEach(layering, function(layer) {
  20375. var u;
  20376. _.forEach(layer, function(v) {
  20377. var vRoot = root[v];
  20378. blockGraph.setNode(vRoot);
  20379. if (u) {
  20380. var uRoot = root[u],
  20381. prevMax = blockGraph.edge(uRoot, vRoot);
  20382. blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g, v, u), prevMax || 0));
  20383. }
  20384. u = v;
  20385. });
  20386. });
  20387. return blockGraph;
  20388. }
  20389. /*
  20390. * Returns the alignment that has the smallest width of the given alignments.
  20391. */
  20392. function findSmallestWidthAlignment(g, xss) {
  20393. return _.minBy(_.values(xss), function (xs) {
  20394. var max = Number.NEGATIVE_INFINITY;
  20395. var min = Number.POSITIVE_INFINITY;
  20396. _.forIn(xs, function (x, v) {
  20397. var halfWidth = width(g, v) / 2;
  20398. max = Math.max(x + halfWidth, max);
  20399. min = Math.min(x - halfWidth, min);
  20400. });
  20401. return max - min;
  20402. });
  20403. }
  20404. /*
  20405. * Align the coordinates of each of the layout alignments such that
  20406. * left-biased alignments have their minimum coordinate at the same point as
  20407. * the minimum coordinate of the smallest width alignment and right-biased
  20408. * alignments have their maximum coordinate at the same point as the maximum
  20409. * coordinate of the smallest width alignment.
  20410. */
  20411. function alignCoordinates(xss, alignTo) {
  20412. var alignToVals = _.values(alignTo),
  20413. alignToMin = _.min(alignToVals),
  20414. alignToMax = _.max(alignToVals);
  20415. _.forEach(["u", "d"], function(vert) {
  20416. _.forEach(["l", "r"], function(horiz) {
  20417. var alignment = vert + horiz,
  20418. xs = xss[alignment],
  20419. delta;
  20420. if (xs === alignTo) return;
  20421. var xsVals = _.values(xs);
  20422. delta = horiz === "l" ? alignToMin - _.min(xsVals) : alignToMax - _.max(xsVals);
  20423. if (delta) {
  20424. xss[alignment] = _.mapValues(xs, function(x) { return x + delta; });
  20425. }
  20426. });
  20427. });
  20428. }
  20429. function balance(xss, align) {
  20430. return _.mapValues(xss.ul, function(ignore, v) {
  20431. if (align) {
  20432. return xss[align.toLowerCase()][v];
  20433. } else {
  20434. var xs = _.sortBy(_.map(xss, v));
  20435. return (xs[1] + xs[2]) / 2;
  20436. }
  20437. });
  20438. }
  20439. function positionX(g) {
  20440. var layering = util.buildLayerMatrix(g),
  20441. conflicts = _.merge(findType1Conflicts(g, layering),
  20442. findType2Conflicts(g, layering));
  20443. var xss = {},
  20444. adjustedLayering;
  20445. _.forEach(["u", "d"], function(vert) {
  20446. adjustedLayering = vert === "u" ? layering : _.values(layering).reverse();
  20447. _.forEach(["l", "r"], function(horiz) {
  20448. if (horiz === "r") {
  20449. adjustedLayering = _.map(adjustedLayering, function(inner) {
  20450. return _.values(inner).reverse();
  20451. });
  20452. }
  20453. var neighborFn = _.bind(vert === "u" ? g.predecessors : g.successors, g);
  20454. var align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn);
  20455. var xs = horizontalCompaction(g, adjustedLayering,
  20456. align.root, align.align,
  20457. horiz === "r");
  20458. if (horiz === "r") {
  20459. xs = _.mapValues(xs, function(x) { return -x; });
  20460. }
  20461. xss[vert + horiz] = xs;
  20462. });
  20463. });
  20464. var smallestWidth = findSmallestWidthAlignment(g, xss);
  20465. alignCoordinates(xss, smallestWidth);
  20466. return balance(xss, g.graph().align);
  20467. }
  20468. function sep(nodeSep, edgeSep, reverseSep) {
  20469. return function(g, v, w) {
  20470. var vLabel = g.node(v),
  20471. wLabel = g.node(w),
  20472. sum = 0,
  20473. delta;
  20474. sum += vLabel.width / 2;
  20475. if (_.has(vLabel, "labelpos")) {
  20476. switch (vLabel.labelpos.toLowerCase()) {
  20477. case "l": delta = -vLabel.width / 2; break;
  20478. case "r": delta = vLabel.width / 2; break;
  20479. }
  20480. }
  20481. if (delta) {
  20482. sum += reverseSep ? delta : -delta;
  20483. }
  20484. delta = 0;
  20485. sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;
  20486. sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;
  20487. sum += wLabel.width / 2;
  20488. if (_.has(wLabel, "labelpos")) {
  20489. switch (wLabel.labelpos.toLowerCase()) {
  20490. case "l": delta = wLabel.width / 2; break;
  20491. case "r": delta = -wLabel.width / 2; break;
  20492. }
  20493. }
  20494. if (delta) {
  20495. sum += reverseSep ? delta : -delta;
  20496. }
  20497. delta = 0;
  20498. return sum;
  20499. };
  20500. }
  20501. function width(g, v) {
  20502. return g.node(v).width;
  20503. }
  20504. },{"../graphlib":76,"../lodash":79,"../util":98}],93:[function(require,module,exports){
  20505. "use strict";
  20506. var _ = require("../lodash"),
  20507. util = require("../util"),
  20508. positionX = require("./bk").positionX;
  20509. module.exports = position;
  20510. function position(g) {
  20511. g = util.asNonCompoundGraph(g);
  20512. positionY(g);
  20513. _.forEach(positionX(g), function(x, v) {
  20514. g.node(v).x = x;
  20515. });
  20516. }
  20517. function positionY(g) {
  20518. var layering = util.buildLayerMatrix(g),
  20519. rankSep = g.graph().ranksep,
  20520. prevY = 0;
  20521. _.forEach(layering, function(layer) {
  20522. var maxHeight = _.max(_.map(layer, function(v) { return g.node(v).height; }));
  20523. _.forEach(layer, function(v) {
  20524. g.node(v).y = prevY + maxHeight / 2;
  20525. });
  20526. prevY += maxHeight + rankSep;
  20527. });
  20528. }
  20529. },{"../lodash":79,"../util":98,"./bk":92}],94:[function(require,module,exports){
  20530. "use strict";
  20531. var _ = require("../lodash"),
  20532. Graph = require("../graphlib").Graph,
  20533. slack = require("./util").slack;
  20534. module.exports = feasibleTree;
  20535. /*
  20536. * Constructs a spanning tree with tight edges and adjusted the input node's
  20537. * ranks to achieve this. A tight edge is one that is has a length that matches
  20538. * its "minlen" attribute.
  20539. *
  20540. * The basic structure for this function is derived from Gansner, et al., "A
  20541. * Technique for Drawing Directed Graphs."
  20542. *
  20543. * Pre-conditions:
  20544. *
  20545. * 1. Graph must be a DAG.
  20546. * 2. Graph must be connected.
  20547. * 3. Graph must have at least one node.
  20548. * 5. Graph nodes must have been previously assigned a "rank" property that
  20549. * respects the "minlen" property of incident edges.
  20550. * 6. Graph edges must have a "minlen" property.
  20551. *
  20552. * Post-conditions:
  20553. *
  20554. * - Graph nodes will have their rank adjusted to ensure that all edges are
  20555. * tight.
  20556. *
  20557. * Returns a tree (undirected graph) that is constructed using only "tight"
  20558. * edges.
  20559. */
  20560. function feasibleTree(g) {
  20561. var t = new Graph({ directed: false });
  20562. // Choose arbitrary node from which to start our tree
  20563. var start = g.nodes()[0],
  20564. size = g.nodeCount();
  20565. t.setNode(start, {});
  20566. var edge, delta;
  20567. while (tightTree(t, g) < size) {
  20568. edge = findMinSlackEdge(t, g);
  20569. delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge);
  20570. shiftRanks(t, g, delta);
  20571. }
  20572. return t;
  20573. }
  20574. /*
  20575. * Finds a maximal tree of tight edges and returns the number of nodes in the
  20576. * tree.
  20577. */
  20578. function tightTree(t, g) {
  20579. function dfs(v) {
  20580. _.forEach(g.nodeEdges(v), function(e) {
  20581. var edgeV = e.v,
  20582. w = (v === edgeV) ? e.w : edgeV;
  20583. if (!t.hasNode(w) && !slack(g, e)) {
  20584. t.setNode(w, {});
  20585. t.setEdge(v, w, {});
  20586. dfs(w);
  20587. }
  20588. });
  20589. }
  20590. _.forEach(t.nodes(), dfs);
  20591. return t.nodeCount();
  20592. }
  20593. /*
  20594. * Finds the edge with the smallest slack that is incident on tree and returns
  20595. * it.
  20596. */
  20597. function findMinSlackEdge(t, g) {
  20598. return _.minBy(g.edges(), function(e) {
  20599. if (t.hasNode(e.v) !== t.hasNode(e.w)) {
  20600. return slack(g, e);
  20601. }
  20602. });
  20603. }
  20604. function shiftRanks(t, g, delta) {
  20605. _.forEach(t.nodes(), function(v) {
  20606. g.node(v).rank += delta;
  20607. });
  20608. }
  20609. },{"../graphlib":76,"../lodash":79,"./util":97}],95:[function(require,module,exports){
  20610. "use strict";
  20611. var rankUtil = require("./util"),
  20612. longestPath = rankUtil.longestPath,
  20613. feasibleTree = require("./feasible-tree"),
  20614. networkSimplex = require("./network-simplex");
  20615. module.exports = rank;
  20616. /*
  20617. * Assigns a rank to each node in the input graph that respects the "minlen"
  20618. * constraint specified on edges between nodes.
  20619. *
  20620. * This basic structure is derived from Gansner, et al., "A Technique for
  20621. * Drawing Directed Graphs."
  20622. *
  20623. * Pre-conditions:
  20624. *
  20625. * 1. Graph must be a connected DAG
  20626. * 2. Graph nodes must be objects
  20627. * 3. Graph edges must have "weight" and "minlen" attributes
  20628. *
  20629. * Post-conditions:
  20630. *
  20631. * 1. Graph nodes will have a "rank" attribute based on the results of the
  20632. * algorithm. Ranks can start at any index (including negative), we'll
  20633. * fix them up later.
  20634. */
  20635. function rank(g) {
  20636. switch(g.graph().ranker) {
  20637. case "network-simplex": networkSimplexRanker(g); break;
  20638. case "tight-tree": tightTreeRanker(g); break;
  20639. case "longest-path": longestPathRanker(g); break;
  20640. default: networkSimplexRanker(g);
  20641. }
  20642. }
  20643. // A fast and simple ranker, but results are far from optimal.
  20644. var longestPathRanker = longestPath;
  20645. function tightTreeRanker(g) {
  20646. longestPath(g);
  20647. feasibleTree(g);
  20648. }
  20649. function networkSimplexRanker(g) {
  20650. networkSimplex(g);
  20651. }
  20652. },{"./feasible-tree":94,"./network-simplex":96,"./util":97}],96:[function(require,module,exports){
  20653. "use strict";
  20654. var _ = require("../lodash"),
  20655. feasibleTree = require("./feasible-tree"),
  20656. slack = require("./util").slack,
  20657. initRank = require("./util").longestPath,
  20658. preorder = require("../graphlib").alg.preorder,
  20659. postorder = require("../graphlib").alg.postorder,
  20660. simplify = require("../util").simplify;
  20661. module.exports = networkSimplex;
  20662. // Expose some internals for testing purposes
  20663. networkSimplex.initLowLimValues = initLowLimValues;
  20664. networkSimplex.initCutValues = initCutValues;
  20665. networkSimplex.calcCutValue = calcCutValue;
  20666. networkSimplex.leaveEdge = leaveEdge;
  20667. networkSimplex.enterEdge = enterEdge;
  20668. networkSimplex.exchangeEdges = exchangeEdges;
  20669. /*
  20670. * The network simplex algorithm assigns ranks to each node in the input graph
  20671. * and iteratively improves the ranking to reduce the length of edges.
  20672. *
  20673. * Preconditions:
  20674. *
  20675. * 1. The input graph must be a DAG.
  20676. * 2. All nodes in the graph must have an object value.
  20677. * 3. All edges in the graph must have "minlen" and "weight" attributes.
  20678. *
  20679. * Postconditions:
  20680. *
  20681. * 1. All nodes in the graph will have an assigned "rank" attribute that has
  20682. * been optimized by the network simplex algorithm. Ranks start at 0.
  20683. *
  20684. *
  20685. * A rough sketch of the algorithm is as follows:
  20686. *
  20687. * 1. Assign initial ranks to each node. We use the longest path algorithm,
  20688. * which assigns ranks to the lowest position possible. In general this
  20689. * leads to very wide bottom ranks and unnecessarily long edges.
  20690. * 2. Construct a feasible tight tree. A tight tree is one such that all
  20691. * edges in the tree have no slack (difference between length of edge
  20692. * and minlen for the edge). This by itself greatly improves the assigned
  20693. * rankings by shorting edges.
  20694. * 3. Iteratively find edges that have negative cut values. Generally a
  20695. * negative cut value indicates that the edge could be removed and a new
  20696. * tree edge could be added to produce a more compact graph.
  20697. *
  20698. * Much of the algorithms here are derived from Gansner, et al., "A Technique
  20699. * for Drawing Directed Graphs." The structure of the file roughly follows the
  20700. * structure of the overall algorithm.
  20701. */
  20702. function networkSimplex(g) {
  20703. g = simplify(g);
  20704. initRank(g);
  20705. var t = feasibleTree(g);
  20706. initLowLimValues(t);
  20707. initCutValues(t, g);
  20708. var e, f;
  20709. while ((e = leaveEdge(t))) {
  20710. f = enterEdge(t, g, e);
  20711. exchangeEdges(t, g, e, f);
  20712. }
  20713. }
  20714. /*
  20715. * Initializes cut values for all edges in the tree.
  20716. */
  20717. function initCutValues(t, g) {
  20718. var vs = postorder(t, t.nodes());
  20719. vs = vs.slice(0, vs.length - 1);
  20720. _.forEach(vs, function(v) {
  20721. assignCutValue(t, g, v);
  20722. });
  20723. }
  20724. function assignCutValue(t, g, child) {
  20725. var childLab = t.node(child),
  20726. parent = childLab.parent;
  20727. t.edge(child, parent).cutvalue = calcCutValue(t, g, child);
  20728. }
  20729. /*
  20730. * Given the tight tree, its graph, and a child in the graph calculate and
  20731. * return the cut value for the edge between the child and its parent.
  20732. */
  20733. function calcCutValue(t, g, child) {
  20734. var childLab = t.node(child),
  20735. parent = childLab.parent,
  20736. // True if the child is on the tail end of the edge in the directed graph
  20737. childIsTail = true,
  20738. // The graph's view of the tree edge we're inspecting
  20739. graphEdge = g.edge(child, parent),
  20740. // The accumulated cut value for the edge between this node and its parent
  20741. cutValue = 0;
  20742. if (!graphEdge) {
  20743. childIsTail = false;
  20744. graphEdge = g.edge(parent, child);
  20745. }
  20746. cutValue = graphEdge.weight;
  20747. _.forEach(g.nodeEdges(child), function(e) {
  20748. var isOutEdge = e.v === child,
  20749. other = isOutEdge ? e.w : e.v;
  20750. if (other !== parent) {
  20751. var pointsToHead = isOutEdge === childIsTail,
  20752. otherWeight = g.edge(e).weight;
  20753. cutValue += pointsToHead ? otherWeight : -otherWeight;
  20754. if (isTreeEdge(t, child, other)) {
  20755. var otherCutValue = t.edge(child, other).cutvalue;
  20756. cutValue += pointsToHead ? -otherCutValue : otherCutValue;
  20757. }
  20758. }
  20759. });
  20760. return cutValue;
  20761. }
  20762. function initLowLimValues(tree, root) {
  20763. if (arguments.length < 2) {
  20764. root = tree.nodes()[0];
  20765. }
  20766. dfsAssignLowLim(tree, {}, 1, root);
  20767. }
  20768. function dfsAssignLowLim(tree, visited, nextLim, v, parent) {
  20769. var low = nextLim,
  20770. label = tree.node(v);
  20771. visited[v] = true;
  20772. _.forEach(tree.neighbors(v), function(w) {
  20773. if (!_.has(visited, w)) {
  20774. nextLim = dfsAssignLowLim(tree, visited, nextLim, w, v);
  20775. }
  20776. });
  20777. label.low = low;
  20778. label.lim = nextLim++;
  20779. if (parent) {
  20780. label.parent = parent;
  20781. } else {
  20782. // TODO should be able to remove this when we incrementally update low lim
  20783. delete label.parent;
  20784. }
  20785. return nextLim;
  20786. }
  20787. function leaveEdge(tree) {
  20788. return _.find(tree.edges(), function(e) {
  20789. return tree.edge(e).cutvalue < 0;
  20790. });
  20791. }
  20792. function enterEdge(t, g, edge) {
  20793. var v = edge.v,
  20794. w = edge.w;
  20795. // For the rest of this function we assume that v is the tail and w is the
  20796. // head, so if we don't have this edge in the graph we should flip it to
  20797. // match the correct orientation.
  20798. if (!g.hasEdge(v, w)) {
  20799. v = edge.w;
  20800. w = edge.v;
  20801. }
  20802. var vLabel = t.node(v),
  20803. wLabel = t.node(w),
  20804. tailLabel = vLabel,
  20805. flip = false;
  20806. // If the root is in the tail of the edge then we need to flip the logic that
  20807. // checks for the head and tail nodes in the candidates function below.
  20808. if (vLabel.lim > wLabel.lim) {
  20809. tailLabel = wLabel;
  20810. flip = true;
  20811. }
  20812. var candidates = _.filter(g.edges(), function(edge) {
  20813. return flip === isDescendant(t, t.node(edge.v), tailLabel) &&
  20814. flip !== isDescendant(t, t.node(edge.w), tailLabel);
  20815. });
  20816. return _.minBy(candidates, function(edge) { return slack(g, edge); });
  20817. }
  20818. function exchangeEdges(t, g, e, f) {
  20819. var v = e.v,
  20820. w = e.w;
  20821. t.removeEdge(v, w);
  20822. t.setEdge(f.v, f.w, {});
  20823. initLowLimValues(t);
  20824. initCutValues(t, g);
  20825. updateRanks(t, g);
  20826. }
  20827. function updateRanks(t, g) {
  20828. var root = _.find(t.nodes(), function(v) { return !g.node(v).parent; }),
  20829. vs = preorder(t, root);
  20830. vs = vs.slice(1);
  20831. _.forEach(vs, function(v) {
  20832. var parent = t.node(v).parent,
  20833. edge = g.edge(v, parent),
  20834. flipped = false;
  20835. if (!edge) {
  20836. edge = g.edge(parent, v);
  20837. flipped = true;
  20838. }
  20839. g.node(v).rank = g.node(parent).rank + (flipped ? edge.minlen : -edge.minlen);
  20840. });
  20841. }
  20842. /*
  20843. * Returns true if the edge is in the tree.
  20844. */
  20845. function isTreeEdge(tree, u, v) {
  20846. return tree.hasEdge(u, v);
  20847. }
  20848. /*
  20849. * Returns true if the specified node is descendant of the root node per the
  20850. * assigned low and lim attributes in the tree.
  20851. */
  20852. function isDescendant(tree, vLabel, rootLabel) {
  20853. return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim;
  20854. }
  20855. },{"../graphlib":76,"../lodash":79,"../util":98,"./feasible-tree":94,"./util":97}],97:[function(require,module,exports){
  20856. "use strict";
  20857. var _ = require("../lodash");
  20858. module.exports = {
  20859. longestPath: longestPath,
  20860. slack: slack
  20861. };
  20862. /*
  20863. * Initializes ranks for the input graph using the longest path algorithm. This
  20864. * algorithm scales well and is fast in practice, it yields rather poor
  20865. * solutions. Nodes are pushed to the lowest layer possible, leaving the bottom
  20866. * ranks wide and leaving edges longer than necessary. However, due to its
  20867. * speed, this algorithm is good for getting an initial ranking that can be fed
  20868. * into other algorithms.
  20869. *
  20870. * This algorithm does not normalize layers because it will be used by other
  20871. * algorithms in most cases. If using this algorithm directly, be sure to
  20872. * run normalize at the end.
  20873. *
  20874. * Pre-conditions:
  20875. *
  20876. * 1. Input graph is a DAG.
  20877. * 2. Input graph node labels can be assigned properties.
  20878. *
  20879. * Post-conditions:
  20880. *
  20881. * 1. Each node will be assign an (unnormalized) "rank" property.
  20882. */
  20883. function longestPath(g) {
  20884. var visited = {};
  20885. function dfs(v) {
  20886. var label = g.node(v);
  20887. if (_.has(visited, v)) {
  20888. return label.rank;
  20889. }
  20890. visited[v] = true;
  20891. var rank = _.minBy(_.map(g.outEdges(v), function(e) {
  20892. return dfs(e.w) - g.edge(e).minlen;
  20893. }));
  20894. if (rank === Number.POSITIVE_INFINITY || // return value of _.map([]) for Lodash 3
  20895. rank === undefined || // return value of _.map([]) for Lodash 4
  20896. rank === null) { // return value of _.map([null])
  20897. rank = 0;
  20898. }
  20899. return (label.rank = rank);
  20900. }
  20901. _.forEach(g.sources(), dfs);
  20902. }
  20903. /*
  20904. * Returns the amount of slack for the given edge. The slack is defined as the
  20905. * difference between the length of the edge and its minimum length.
  20906. */
  20907. function slack(g, e) {
  20908. return g.node(e.w).rank - g.node(e.v).rank - g.edge(e).minlen;
  20909. }
  20910. },{"../lodash":79}],98:[function(require,module,exports){
  20911. "use strict";
  20912. var _ = require("./lodash"),
  20913. Graph = require("./graphlib").Graph;
  20914. module.exports = {
  20915. addDummyNode: addDummyNode,
  20916. simplify: simplify,
  20917. asNonCompoundGraph: asNonCompoundGraph,
  20918. successorWeights: successorWeights,
  20919. predecessorWeights: predecessorWeights,
  20920. intersectRect: intersectRect,
  20921. buildLayerMatrix: buildLayerMatrix,
  20922. normalizeRanks: normalizeRanks,
  20923. removeEmptyRanks: removeEmptyRanks,
  20924. addBorderNode: addBorderNode,
  20925. maxRank: maxRank,
  20926. partition: partition,
  20927. time: time,
  20928. notime: notime
  20929. };
  20930. /*
  20931. * Adds a dummy node to the graph and return v.
  20932. */
  20933. function addDummyNode(g, type, attrs, name) {
  20934. var v;
  20935. do {
  20936. v = _.uniqueId(name);
  20937. } while (g.hasNode(v));
  20938. attrs.dummy = type;
  20939. g.setNode(v, attrs);
  20940. return v;
  20941. }
  20942. /*
  20943. * Returns a new graph with only simple edges. Handles aggregation of data
  20944. * associated with multi-edges.
  20945. */
  20946. function simplify(g) {
  20947. var simplified = new Graph().setGraph(g.graph());
  20948. _.forEach(g.nodes(), function(v) { simplified.setNode(v, g.node(v)); });
  20949. _.forEach(g.edges(), function(e) {
  20950. var simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 },
  20951. label = g.edge(e);
  20952. simplified.setEdge(e.v, e.w, {
  20953. weight: simpleLabel.weight + label.weight,
  20954. minlen: Math.max(simpleLabel.minlen, label.minlen)
  20955. });
  20956. });
  20957. return simplified;
  20958. }
  20959. function asNonCompoundGraph(g) {
  20960. var simplified = new Graph({ multigraph: g.isMultigraph() }).setGraph(g.graph());
  20961. _.forEach(g.nodes(), function(v) {
  20962. if (!g.children(v).length) {
  20963. simplified.setNode(v, g.node(v));
  20964. }
  20965. });
  20966. _.forEach(g.edges(), function(e) {
  20967. simplified.setEdge(e, g.edge(e));
  20968. });
  20969. return simplified;
  20970. }
  20971. function successorWeights(g) {
  20972. var weightMap = _.map(g.nodes(), function(v) {
  20973. var sucs = {};
  20974. _.forEach(g.outEdges(v), function(e) {
  20975. sucs[e.w] = (sucs[e.w] || 0) + g.edge(e).weight;
  20976. });
  20977. return sucs;
  20978. });
  20979. return _.zipObject(g.nodes(), weightMap);
  20980. }
  20981. function predecessorWeights(g) {
  20982. var weightMap = _.map(g.nodes(), function(v) {
  20983. var preds = {};
  20984. _.forEach(g.inEdges(v), function(e) {
  20985. preds[e.v] = (preds[e.v] || 0) + g.edge(e).weight;
  20986. });
  20987. return preds;
  20988. });
  20989. return _.zipObject(g.nodes(), weightMap);
  20990. }
  20991. /*
  20992. * Finds where a line starting at point ({x, y}) would intersect a rectangle
  20993. * ({x, y, width, height}) if it were pointing at the rectangle's center.
  20994. */
  20995. function intersectRect(rect, point) {
  20996. var x = rect.x;
  20997. var y = rect.y;
  20998. // Rectangle intersection algorithm from:
  20999. // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
  21000. var dx = point.x - x;
  21001. var dy = point.y - y;
  21002. var w = rect.width / 2;
  21003. var h = rect.height / 2;
  21004. if (!dx && !dy) {
  21005. throw new Error("Not possible to find intersection inside of the rectangle");
  21006. }
  21007. var sx, sy;
  21008. if (Math.abs(dy) * w > Math.abs(dx) * h) {
  21009. // Intersection is top or bottom of rect.
  21010. if (dy < 0) {
  21011. h = -h;
  21012. }
  21013. sx = h * dx / dy;
  21014. sy = h;
  21015. } else {
  21016. // Intersection is left or right of rect.
  21017. if (dx < 0) {
  21018. w = -w;
  21019. }
  21020. sx = w;
  21021. sy = w * dy / dx;
  21022. }
  21023. return { x: x + sx, y: y + sy };
  21024. }
  21025. /*
  21026. * Given a DAG with each node assigned "rank" and "order" properties, this
  21027. * function will produce a matrix with the ids of each node.
  21028. */
  21029. function buildLayerMatrix(g) {
  21030. var layering = _.map(_.range(maxRank(g) + 1), function() { return []; });
  21031. _.forEach(g.nodes(), function(v) {
  21032. var node = g.node(v),
  21033. rank = node.rank;
  21034. if (!_.isUndefined(rank)) {
  21035. layering[rank][node.order] = v;
  21036. }
  21037. });
  21038. return layering;
  21039. }
  21040. /*
  21041. * Adjusts the ranks for all nodes in the graph such that all nodes v have
  21042. * rank(v) >= 0 and at least one node w has rank(w) = 0.
  21043. */
  21044. function normalizeRanks(g) {
  21045. var min = _.minBy(_.map(g.nodes(), function(v) { return g.node(v).rank; }));
  21046. _.forEach(g.nodes(), function(v) {
  21047. var node = g.node(v);
  21048. if (_.has(node, "rank")) {
  21049. node.rank -= min;
  21050. }
  21051. });
  21052. }
  21053. function removeEmptyRanks(g) {
  21054. // Ranks may not start at 0, so we need to offset them
  21055. var offset = _.minBy(_.map(g.nodes(), function(v) { return g.node(v).rank; }));
  21056. var layers = [];
  21057. _.forEach(g.nodes(), function(v) {
  21058. var rank = g.node(v).rank - offset;
  21059. if (!layers[rank]) {
  21060. layers[rank] = [];
  21061. }
  21062. layers[rank].push(v);
  21063. });
  21064. var delta = 0,
  21065. nodeRankFactor = g.graph().nodeRankFactor;
  21066. _.forEach(layers, function(vs, i) {
  21067. if (_.isUndefined(vs) && i % nodeRankFactor !== 0) {
  21068. --delta;
  21069. } else if (delta) {
  21070. _.forEach(vs, function(v) { g.node(v).rank += delta; });
  21071. }
  21072. });
  21073. }
  21074. function addBorderNode(g, prefix, rank, order) {
  21075. var node = {
  21076. width: 0,
  21077. height: 0
  21078. };
  21079. if (arguments.length >= 4) {
  21080. node.rank = rank;
  21081. node.order = order;
  21082. }
  21083. return addDummyNode(g, "border", node, prefix);
  21084. }
  21085. function maxRank(g) {
  21086. return _.max(_.map(g.nodes(), function(v) {
  21087. var rank = g.node(v).rank;
  21088. if (!_.isUndefined(rank)) {
  21089. return rank;
  21090. }
  21091. }));
  21092. }
  21093. /*
  21094. * Partition a collection into two groups: `lhs` and `rhs`. If the supplied
  21095. * function returns true for an entry it goes into `lhs`. Otherwise it goes
  21096. * into `rhs.
  21097. */
  21098. function partition(collection, fn) {
  21099. var result = { lhs: [], rhs: [] };
  21100. _.forEach(collection, function(value) {
  21101. if (fn(value)) {
  21102. result.lhs.push(value);
  21103. } else {
  21104. result.rhs.push(value);
  21105. }
  21106. });
  21107. return result;
  21108. }
  21109. /*
  21110. * Returns a new function that wraps `fn` with a timer. The wrapper logs the
  21111. * time it takes to execute the function.
  21112. */
  21113. function time(name, fn) {
  21114. var start = _.now();
  21115. try {
  21116. return fn();
  21117. } finally {
  21118. console.log(name + " time: " + (_.now() - start) + "ms");
  21119. }
  21120. }
  21121. function notime(name, fn) {
  21122. return fn();
  21123. }
  21124. },{"./graphlib":76,"./lodash":79}],99:[function(require,module,exports){
  21125. module.exports = "0.8.1";
  21126. },{}],100:[function(require,module,exports){
  21127. /**
  21128. * Copyright (c) 2014, Chris Pettitt
  21129. * All rights reserved.
  21130. *
  21131. * Redistribution and use in source and binary forms, with or without
  21132. * modification, are permitted provided that the following conditions are met:
  21133. *
  21134. * 1. Redistributions of source code must retain the above copyright notice, this
  21135. * list of conditions and the following disclaimer.
  21136. *
  21137. * 2. Redistributions in binary form must reproduce the above copyright notice,
  21138. * this list of conditions and the following disclaimer in the documentation
  21139. * and/or other materials provided with the distribution.
  21140. *
  21141. * 3. Neither the name of the copyright holder nor the names of its contributors
  21142. * may be used to endorse or promote products derived from this software without
  21143. * specific prior written permission.
  21144. *
  21145. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  21146. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  21147. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21148. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  21149. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21150. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21151. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  21152. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  21153. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  21154. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  21155. */
  21156. var lib = require("./lib");
  21157. module.exports = {
  21158. Graph: lib.Graph,
  21159. json: require("./lib/json"),
  21160. alg: require("./lib/alg"),
  21161. version: lib.version
  21162. };
  21163. },{"./lib":116,"./lib/alg":107,"./lib/json":117}],101:[function(require,module,exports){
  21164. var _ = require("../lodash");
  21165. module.exports = components;
  21166. function components(g) {
  21167. var visited = {},
  21168. cmpts = [],
  21169. cmpt;
  21170. function dfs(v) {
  21171. if (_.has(visited, v)) return;
  21172. visited[v] = true;
  21173. cmpt.push(v);
  21174. _.each(g.successors(v), dfs);
  21175. _.each(g.predecessors(v), dfs);
  21176. }
  21177. _.each(g.nodes(), function(v) {
  21178. cmpt = [];
  21179. dfs(v);
  21180. if (cmpt.length) {
  21181. cmpts.push(cmpt);
  21182. }
  21183. });
  21184. return cmpts;
  21185. }
  21186. },{"../lodash":118}],102:[function(require,module,exports){
  21187. var _ = require("../lodash");
  21188. module.exports = dfs;
  21189. /*
  21190. * A helper that preforms a pre- or post-order traversal on the input graph
  21191. * and returns the nodes in the order they were visited. If the graph is
  21192. * undirected then this algorithm will navigate using neighbors. If the graph
  21193. * is directed then this algorithm will navigate using successors.
  21194. *
  21195. * Order must be one of "pre" or "post".
  21196. */
  21197. function dfs(g, vs, order) {
  21198. if (!_.isArray(vs)) {
  21199. vs = [vs];
  21200. }
  21201. var navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g);
  21202. var acc = [],
  21203. visited = {};
  21204. _.each(vs, function(v) {
  21205. if (!g.hasNode(v)) {
  21206. throw new Error("Graph does not have node: " + v);
  21207. }
  21208. doDfs(g, v, order === "post", visited, navigation, acc);
  21209. });
  21210. return acc;
  21211. }
  21212. function doDfs(g, v, postorder, visited, navigation, acc) {
  21213. if (!_.has(visited, v)) {
  21214. visited[v] = true;
  21215. if (!postorder) { acc.push(v); }
  21216. _.each(navigation(v), function(w) {
  21217. doDfs(g, w, postorder, visited, navigation, acc);
  21218. });
  21219. if (postorder) { acc.push(v); }
  21220. }
  21221. }
  21222. },{"../lodash":118}],103:[function(require,module,exports){
  21223. var dijkstra = require("./dijkstra"),
  21224. _ = require("../lodash");
  21225. module.exports = dijkstraAll;
  21226. function dijkstraAll(g, weightFunc, edgeFunc) {
  21227. return _.transform(g.nodes(), function(acc, v) {
  21228. acc[v] = dijkstra(g, v, weightFunc, edgeFunc);
  21229. }, {});
  21230. }
  21231. },{"../lodash":118,"./dijkstra":104}],104:[function(require,module,exports){
  21232. var _ = require("../lodash"),
  21233. PriorityQueue = require("../data/priority-queue");
  21234. module.exports = dijkstra;
  21235. var DEFAULT_WEIGHT_FUNC = _.constant(1);
  21236. function dijkstra(g, source, weightFn, edgeFn) {
  21237. return runDijkstra(g, String(source),
  21238. weightFn || DEFAULT_WEIGHT_FUNC,
  21239. edgeFn || function(v) { return g.outEdges(v); });
  21240. }
  21241. function runDijkstra(g, source, weightFn, edgeFn) {
  21242. var results = {},
  21243. pq = new PriorityQueue(),
  21244. v, vEntry;
  21245. var updateNeighbors = function(edge) {
  21246. var w = edge.v !== v ? edge.v : edge.w,
  21247. wEntry = results[w],
  21248. weight = weightFn(edge),
  21249. distance = vEntry.distance + weight;
  21250. if (weight < 0) {
  21251. throw new Error("dijkstra does not allow negative edge weights. " +
  21252. "Bad edge: " + edge + " Weight: " + weight);
  21253. }
  21254. if (distance < wEntry.distance) {
  21255. wEntry.distance = distance;
  21256. wEntry.predecessor = v;
  21257. pq.decrease(w, distance);
  21258. }
  21259. };
  21260. g.nodes().forEach(function(v) {
  21261. var distance = v === source ? 0 : Number.POSITIVE_INFINITY;
  21262. results[v] = { distance: distance };
  21263. pq.add(v, distance);
  21264. });
  21265. while (pq.size() > 0) {
  21266. v = pq.removeMin();
  21267. vEntry = results[v];
  21268. if (vEntry.distance === Number.POSITIVE_INFINITY) {
  21269. break;
  21270. }
  21271. edgeFn(v).forEach(updateNeighbors);
  21272. }
  21273. return results;
  21274. }
  21275. },{"../data/priority-queue":114,"../lodash":118}],105:[function(require,module,exports){
  21276. var _ = require("../lodash"),
  21277. tarjan = require("./tarjan");
  21278. module.exports = findCycles;
  21279. function findCycles(g) {
  21280. return _.filter(tarjan(g), function(cmpt) {
  21281. return cmpt.length > 1 || (cmpt.length === 1 && g.hasEdge(cmpt[0], cmpt[0]));
  21282. });
  21283. }
  21284. },{"../lodash":118,"./tarjan":112}],106:[function(require,module,exports){
  21285. var _ = require("../lodash");
  21286. module.exports = floydWarshall;
  21287. var DEFAULT_WEIGHT_FUNC = _.constant(1);
  21288. function floydWarshall(g, weightFn, edgeFn) {
  21289. return runFloydWarshall(g,
  21290. weightFn || DEFAULT_WEIGHT_FUNC,
  21291. edgeFn || function(v) { return g.outEdges(v); });
  21292. }
  21293. function runFloydWarshall(g, weightFn, edgeFn) {
  21294. var results = {},
  21295. nodes = g.nodes();
  21296. nodes.forEach(function(v) {
  21297. results[v] = {};
  21298. results[v][v] = { distance: 0 };
  21299. nodes.forEach(function(w) {
  21300. if (v !== w) {
  21301. results[v][w] = { distance: Number.POSITIVE_INFINITY };
  21302. }
  21303. });
  21304. edgeFn(v).forEach(function(edge) {
  21305. var w = edge.v === v ? edge.w : edge.v,
  21306. d = weightFn(edge);
  21307. results[v][w] = { distance: d, predecessor: v };
  21308. });
  21309. });
  21310. nodes.forEach(function(k) {
  21311. var rowK = results[k];
  21312. nodes.forEach(function(i) {
  21313. var rowI = results[i];
  21314. nodes.forEach(function(j) {
  21315. var ik = rowI[k];
  21316. var kj = rowK[j];
  21317. var ij = rowI[j];
  21318. var altDistance = ik.distance + kj.distance;
  21319. if (altDistance < ij.distance) {
  21320. ij.distance = altDistance;
  21321. ij.predecessor = kj.predecessor;
  21322. }
  21323. });
  21324. });
  21325. });
  21326. return results;
  21327. }
  21328. },{"../lodash":118}],107:[function(require,module,exports){
  21329. module.exports = {
  21330. components: require("./components"),
  21331. dijkstra: require("./dijkstra"),
  21332. dijkstraAll: require("./dijkstra-all"),
  21333. findCycles: require("./find-cycles"),
  21334. floydWarshall: require("./floyd-warshall"),
  21335. isAcyclic: require("./is-acyclic"),
  21336. postorder: require("./postorder"),
  21337. preorder: require("./preorder"),
  21338. prim: require("./prim"),
  21339. tarjan: require("./tarjan"),
  21340. topsort: require("./topsort")
  21341. };
  21342. },{"./components":101,"./dijkstra":104,"./dijkstra-all":103,"./find-cycles":105,"./floyd-warshall":106,"./is-acyclic":108,"./postorder":109,"./preorder":110,"./prim":111,"./tarjan":112,"./topsort":113}],108:[function(require,module,exports){
  21343. var topsort = require("./topsort");
  21344. module.exports = isAcyclic;
  21345. function isAcyclic(g) {
  21346. try {
  21347. topsort(g);
  21348. } catch (e) {
  21349. if (e instanceof topsort.CycleException) {
  21350. return false;
  21351. }
  21352. throw e;
  21353. }
  21354. return true;
  21355. }
  21356. },{"./topsort":113}],109:[function(require,module,exports){
  21357. var dfs = require("./dfs");
  21358. module.exports = postorder;
  21359. function postorder(g, vs) {
  21360. return dfs(g, vs, "post");
  21361. }
  21362. },{"./dfs":102}],110:[function(require,module,exports){
  21363. var dfs = require("./dfs");
  21364. module.exports = preorder;
  21365. function preorder(g, vs) {
  21366. return dfs(g, vs, "pre");
  21367. }
  21368. },{"./dfs":102}],111:[function(require,module,exports){
  21369. var _ = require("../lodash"),
  21370. Graph = require("../graph"),
  21371. PriorityQueue = require("../data/priority-queue");
  21372. module.exports = prim;
  21373. function prim(g, weightFunc) {
  21374. var result = new Graph(),
  21375. parents = {},
  21376. pq = new PriorityQueue(),
  21377. v;
  21378. function updateNeighbors(edge) {
  21379. var w = edge.v === v ? edge.w : edge.v,
  21380. pri = pq.priority(w);
  21381. if (pri !== undefined) {
  21382. var edgeWeight = weightFunc(edge);
  21383. if (edgeWeight < pri) {
  21384. parents[w] = v;
  21385. pq.decrease(w, edgeWeight);
  21386. }
  21387. }
  21388. }
  21389. if (g.nodeCount() === 0) {
  21390. return result;
  21391. }
  21392. _.each(g.nodes(), function(v) {
  21393. pq.add(v, Number.POSITIVE_INFINITY);
  21394. result.setNode(v);
  21395. });
  21396. // Start from an arbitrary node
  21397. pq.decrease(g.nodes()[0], 0);
  21398. var init = false;
  21399. while (pq.size() > 0) {
  21400. v = pq.removeMin();
  21401. if (_.has(parents, v)) {
  21402. result.setEdge(v, parents[v]);
  21403. } else if (init) {
  21404. throw new Error("Input graph is not connected: " + g);
  21405. } else {
  21406. init = true;
  21407. }
  21408. g.nodeEdges(v).forEach(updateNeighbors);
  21409. }
  21410. return result;
  21411. }
  21412. },{"../data/priority-queue":114,"../graph":115,"../lodash":118}],112:[function(require,module,exports){
  21413. var _ = require("../lodash");
  21414. module.exports = tarjan;
  21415. function tarjan(g) {
  21416. var index = 0,
  21417. stack = [],
  21418. visited = {}, // node id -> { onStack, lowlink, index }
  21419. results = [];
  21420. function dfs(v) {
  21421. var entry = visited[v] = {
  21422. onStack: true,
  21423. lowlink: index,
  21424. index: index++
  21425. };
  21426. stack.push(v);
  21427. g.successors(v).forEach(function(w) {
  21428. if (!_.has(visited, w)) {
  21429. dfs(w);
  21430. entry.lowlink = Math.min(entry.lowlink, visited[w].lowlink);
  21431. } else if (visited[w].onStack) {
  21432. entry.lowlink = Math.min(entry.lowlink, visited[w].index);
  21433. }
  21434. });
  21435. if (entry.lowlink === entry.index) {
  21436. var cmpt = [],
  21437. w;
  21438. do {
  21439. w = stack.pop();
  21440. visited[w].onStack = false;
  21441. cmpt.push(w);
  21442. } while (v !== w);
  21443. results.push(cmpt);
  21444. }
  21445. }
  21446. g.nodes().forEach(function(v) {
  21447. if (!_.has(visited, v)) {
  21448. dfs(v);
  21449. }
  21450. });
  21451. return results;
  21452. }
  21453. },{"../lodash":118}],113:[function(require,module,exports){
  21454. var _ = require("../lodash");
  21455. module.exports = topsort;
  21456. topsort.CycleException = CycleException;
  21457. function topsort(g) {
  21458. var visited = {},
  21459. stack = {},
  21460. results = [];
  21461. function visit(node) {
  21462. if (_.has(stack, node)) {
  21463. throw new CycleException();
  21464. }
  21465. if (!_.has(visited, node)) {
  21466. stack[node] = true;
  21467. visited[node] = true;
  21468. _.each(g.predecessors(node), visit);
  21469. delete stack[node];
  21470. results.push(node);
  21471. }
  21472. }
  21473. _.each(g.sinks(), visit);
  21474. if (_.size(visited) !== g.nodeCount()) {
  21475. throw new CycleException();
  21476. }
  21477. return results;
  21478. }
  21479. function CycleException() {}
  21480. },{"../lodash":118}],114:[function(require,module,exports){
  21481. var _ = require("../lodash");
  21482. module.exports = PriorityQueue;
  21483. /**
  21484. * A min-priority queue data structure. This algorithm is derived from Cormen,
  21485. * et al., "Introduction to Algorithms". The basic idea of a min-priority
  21486. * queue is that you can efficiently (in O(1) time) get the smallest key in
  21487. * the queue. Adding and removing elements takes O(log n) time. A key can
  21488. * have its priority decreased in O(log n) time.
  21489. */
  21490. function PriorityQueue() {
  21491. this._arr = [];
  21492. this._keyIndices = {};
  21493. }
  21494. /**
  21495. * Returns the number of elements in the queue. Takes `O(1)` time.
  21496. */
  21497. PriorityQueue.prototype.size = function() {
  21498. return this._arr.length;
  21499. };
  21500. /**
  21501. * Returns the keys that are in the queue. Takes `O(n)` time.
  21502. */
  21503. PriorityQueue.prototype.keys = function() {
  21504. return this._arr.map(function(x) { return x.key; });
  21505. };
  21506. /**
  21507. * Returns `true` if **key** is in the queue and `false` if not.
  21508. */
  21509. PriorityQueue.prototype.has = function(key) {
  21510. return _.has(this._keyIndices, key);
  21511. };
  21512. /**
  21513. * Returns the priority for **key**. If **key** is not present in the queue
  21514. * then this function returns `undefined`. Takes `O(1)` time.
  21515. *
  21516. * @param {Object} key
  21517. */
  21518. PriorityQueue.prototype.priority = function(key) {
  21519. var index = this._keyIndices[key];
  21520. if (index !== undefined) {
  21521. return this._arr[index].priority;
  21522. }
  21523. };
  21524. /**
  21525. * Returns the key for the minimum element in this queue. If the queue is
  21526. * empty this function throws an Error. Takes `O(1)` time.
  21527. */
  21528. PriorityQueue.prototype.min = function() {
  21529. if (this.size() === 0) {
  21530. throw new Error("Queue underflow");
  21531. }
  21532. return this._arr[0].key;
  21533. };
  21534. /**
  21535. * Inserts a new key into the priority queue. If the key already exists in
  21536. * the queue this function returns `false`; otherwise it will return `true`.
  21537. * Takes `O(n)` time.
  21538. *
  21539. * @param {Object} key the key to add
  21540. * @param {Number} priority the initial priority for the key
  21541. */
  21542. PriorityQueue.prototype.add = function(key, priority) {
  21543. var keyIndices = this._keyIndices;
  21544. key = String(key);
  21545. if (!_.has(keyIndices, key)) {
  21546. var arr = this._arr;
  21547. var index = arr.length;
  21548. keyIndices[key] = index;
  21549. arr.push({key: key, priority: priority});
  21550. this._decrease(index);
  21551. return true;
  21552. }
  21553. return false;
  21554. };
  21555. /**
  21556. * Removes and returns the smallest key in the queue. Takes `O(log n)` time.
  21557. */
  21558. PriorityQueue.prototype.removeMin = function() {
  21559. this._swap(0, this._arr.length - 1);
  21560. var min = this._arr.pop();
  21561. delete this._keyIndices[min.key];
  21562. this._heapify(0);
  21563. return min.key;
  21564. };
  21565. /**
  21566. * Decreases the priority for **key** to **priority**. If the new priority is
  21567. * greater than the previous priority, this function will throw an Error.
  21568. *
  21569. * @param {Object} key the key for which to raise priority
  21570. * @param {Number} priority the new priority for the key
  21571. */
  21572. PriorityQueue.prototype.decrease = function(key, priority) {
  21573. var index = this._keyIndices[key];
  21574. if (priority > this._arr[index].priority) {
  21575. throw new Error("New priority is greater than current priority. " +
  21576. "Key: " + key + " Old: " + this._arr[index].priority + " New: " + priority);
  21577. }
  21578. this._arr[index].priority = priority;
  21579. this._decrease(index);
  21580. };
  21581. PriorityQueue.prototype._heapify = function(i) {
  21582. var arr = this._arr;
  21583. var l = 2 * i,
  21584. r = l + 1,
  21585. largest = i;
  21586. if (l < arr.length) {
  21587. largest = arr[l].priority < arr[largest].priority ? l : largest;
  21588. if (r < arr.length) {
  21589. largest = arr[r].priority < arr[largest].priority ? r : largest;
  21590. }
  21591. if (largest !== i) {
  21592. this._swap(i, largest);
  21593. this._heapify(largest);
  21594. }
  21595. }
  21596. };
  21597. PriorityQueue.prototype._decrease = function(index) {
  21598. var arr = this._arr;
  21599. var priority = arr[index].priority;
  21600. var parent;
  21601. while (index !== 0) {
  21602. parent = index >> 1;
  21603. if (arr[parent].priority < priority) {
  21604. break;
  21605. }
  21606. this._swap(index, parent);
  21607. index = parent;
  21608. }
  21609. };
  21610. PriorityQueue.prototype._swap = function(i, j) {
  21611. var arr = this._arr;
  21612. var keyIndices = this._keyIndices;
  21613. var origArrI = arr[i];
  21614. var origArrJ = arr[j];
  21615. arr[i] = origArrJ;
  21616. arr[j] = origArrI;
  21617. keyIndices[origArrJ.key] = i;
  21618. keyIndices[origArrI.key] = j;
  21619. };
  21620. },{"../lodash":118}],115:[function(require,module,exports){
  21621. "use strict";
  21622. var _ = require("./lodash");
  21623. module.exports = Graph;
  21624. var DEFAULT_EDGE_NAME = "\x00",
  21625. GRAPH_NODE = "\x00",
  21626. EDGE_KEY_DELIM = "\x01";
  21627. // Implementation notes:
  21628. //
  21629. // * Node id query functions should return string ids for the nodes
  21630. // * Edge id query functions should return an "edgeObj", edge object, that is
  21631. // composed of enough information to uniquely identify an edge: {v, w, name}.
  21632. // * Internally we use an "edgeId", a stringified form of the edgeObj, to
  21633. // reference edges. This is because we need a performant way to look these
  21634. // edges up and, object properties, which have string keys, are the closest
  21635. // we're going to get to a performant hashtable in JavaScript.
  21636. function Graph(opts) {
  21637. this._isDirected = _.has(opts, "directed") ? opts.directed : true;
  21638. this._isMultigraph = _.has(opts, "multigraph") ? opts.multigraph : false;
  21639. this._isCompound = _.has(opts, "compound") ? opts.compound : false;
  21640. // Label for the graph itself
  21641. this._label = undefined;
  21642. // Defaults to be set when creating a new node
  21643. this._defaultNodeLabelFn = _.constant(undefined);
  21644. // Defaults to be set when creating a new edge
  21645. this._defaultEdgeLabelFn = _.constant(undefined);
  21646. // v -> label
  21647. this._nodes = {};
  21648. if (this._isCompound) {
  21649. // v -> parent
  21650. this._parent = {};
  21651. // v -> children
  21652. this._children = {};
  21653. this._children[GRAPH_NODE] = {};
  21654. }
  21655. // v -> edgeObj
  21656. this._in = {};
  21657. // u -> v -> Number
  21658. this._preds = {};
  21659. // v -> edgeObj
  21660. this._out = {};
  21661. // v -> w -> Number
  21662. this._sucs = {};
  21663. // e -> edgeObj
  21664. this._edgeObjs = {};
  21665. // e -> label
  21666. this._edgeLabels = {};
  21667. }
  21668. /* Number of nodes in the graph. Should only be changed by the implementation. */
  21669. Graph.prototype._nodeCount = 0;
  21670. /* Number of edges in the graph. Should only be changed by the implementation. */
  21671. Graph.prototype._edgeCount = 0;
  21672. /* === Graph functions ========= */
  21673. Graph.prototype.isDirected = function() {
  21674. return this._isDirected;
  21675. };
  21676. Graph.prototype.isMultigraph = function() {
  21677. return this._isMultigraph;
  21678. };
  21679. Graph.prototype.isCompound = function() {
  21680. return this._isCompound;
  21681. };
  21682. Graph.prototype.setGraph = function(label) {
  21683. this._label = label;
  21684. return this;
  21685. };
  21686. Graph.prototype.graph = function() {
  21687. return this._label;
  21688. };
  21689. /* === Node functions ========== */
  21690. Graph.prototype.setDefaultNodeLabel = function(newDefault) {
  21691. if (!_.isFunction(newDefault)) {
  21692. newDefault = _.constant(newDefault);
  21693. }
  21694. this._defaultNodeLabelFn = newDefault;
  21695. return this;
  21696. };
  21697. Graph.prototype.nodeCount = function() {
  21698. return this._nodeCount;
  21699. };
  21700. Graph.prototype.nodes = function() {
  21701. return _.keys(this._nodes);
  21702. };
  21703. Graph.prototype.sources = function() {
  21704. var self = this;
  21705. return _.filter(this.nodes(), function(v) {
  21706. return _.isEmpty(self._in[v]);
  21707. });
  21708. };
  21709. Graph.prototype.sinks = function() {
  21710. var self = this;
  21711. return _.filter(this.nodes(), function(v) {
  21712. return _.isEmpty(self._out[v]);
  21713. });
  21714. };
  21715. Graph.prototype.setNodes = function(vs, value) {
  21716. var args = arguments;
  21717. var self = this;
  21718. _.each(vs, function(v) {
  21719. if (args.length > 1) {
  21720. self.setNode(v, value);
  21721. } else {
  21722. self.setNode(v);
  21723. }
  21724. });
  21725. return this;
  21726. };
  21727. Graph.prototype.setNode = function(v, value) {
  21728. if (_.has(this._nodes, v)) {
  21729. if (arguments.length > 1) {
  21730. this._nodes[v] = value;
  21731. }
  21732. return this;
  21733. }
  21734. this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v);
  21735. if (this._isCompound) {
  21736. this._parent[v] = GRAPH_NODE;
  21737. this._children[v] = {};
  21738. this._children[GRAPH_NODE][v] = true;
  21739. }
  21740. this._in[v] = {};
  21741. this._preds[v] = {};
  21742. this._out[v] = {};
  21743. this._sucs[v] = {};
  21744. ++this._nodeCount;
  21745. return this;
  21746. };
  21747. Graph.prototype.node = function(v) {
  21748. return this._nodes[v];
  21749. };
  21750. Graph.prototype.hasNode = function(v) {
  21751. return _.has(this._nodes, v);
  21752. };
  21753. Graph.prototype.removeNode = function(v) {
  21754. var self = this;
  21755. if (_.has(this._nodes, v)) {
  21756. var removeEdge = function(e) { self.removeEdge(self._edgeObjs[e]); };
  21757. delete this._nodes[v];
  21758. if (this._isCompound) {
  21759. this._removeFromParentsChildList(v);
  21760. delete this._parent[v];
  21761. _.each(this.children(v), function(child) {
  21762. self.setParent(child);
  21763. });
  21764. delete this._children[v];
  21765. }
  21766. _.each(_.keys(this._in[v]), removeEdge);
  21767. delete this._in[v];
  21768. delete this._preds[v];
  21769. _.each(_.keys(this._out[v]), removeEdge);
  21770. delete this._out[v];
  21771. delete this._sucs[v];
  21772. --this._nodeCount;
  21773. }
  21774. return this;
  21775. };
  21776. Graph.prototype.setParent = function(v, parent) {
  21777. if (!this._isCompound) {
  21778. throw new Error("Cannot set parent in a non-compound graph");
  21779. }
  21780. if (_.isUndefined(parent)) {
  21781. parent = GRAPH_NODE;
  21782. } else {
  21783. // Coerce parent to string
  21784. parent += "";
  21785. for (var ancestor = parent;
  21786. !_.isUndefined(ancestor);
  21787. ancestor = this.parent(ancestor)) {
  21788. if (ancestor === v) {
  21789. throw new Error("Setting " + parent+ " as parent of " + v +
  21790. " would create a cycle");
  21791. }
  21792. }
  21793. this.setNode(parent);
  21794. }
  21795. this.setNode(v);
  21796. this._removeFromParentsChildList(v);
  21797. this._parent[v] = parent;
  21798. this._children[parent][v] = true;
  21799. return this;
  21800. };
  21801. Graph.prototype._removeFromParentsChildList = function(v) {
  21802. delete this._children[this._parent[v]][v];
  21803. };
  21804. Graph.prototype.parent = function(v) {
  21805. if (this._isCompound) {
  21806. var parent = this._parent[v];
  21807. if (parent !== GRAPH_NODE) {
  21808. return parent;
  21809. }
  21810. }
  21811. };
  21812. Graph.prototype.children = function(v) {
  21813. if (_.isUndefined(v)) {
  21814. v = GRAPH_NODE;
  21815. }
  21816. if (this._isCompound) {
  21817. var children = this._children[v];
  21818. if (children) {
  21819. return _.keys(children);
  21820. }
  21821. } else if (v === GRAPH_NODE) {
  21822. return this.nodes();
  21823. } else if (this.hasNode(v)) {
  21824. return [];
  21825. }
  21826. };
  21827. Graph.prototype.predecessors = function(v) {
  21828. var predsV = this._preds[v];
  21829. if (predsV) {
  21830. return _.keys(predsV);
  21831. }
  21832. };
  21833. Graph.prototype.successors = function(v) {
  21834. var sucsV = this._sucs[v];
  21835. if (sucsV) {
  21836. return _.keys(sucsV);
  21837. }
  21838. };
  21839. Graph.prototype.neighbors = function(v) {
  21840. var preds = this.predecessors(v);
  21841. if (preds) {
  21842. return _.union(preds, this.successors(v));
  21843. }
  21844. };
  21845. Graph.prototype.isLeaf = function (v) {
  21846. var neighbors;
  21847. if (this.isDirected()) {
  21848. neighbors = this.successors(v);
  21849. } else {
  21850. neighbors = this.neighbors(v);
  21851. }
  21852. return neighbors.length === 0;
  21853. };
  21854. Graph.prototype.filterNodes = function(filter) {
  21855. var copy = new this.constructor({
  21856. directed: this._isDirected,
  21857. multigraph: this._isMultigraph,
  21858. compound: this._isCompound
  21859. });
  21860. copy.setGraph(this.graph());
  21861. var self = this;
  21862. _.each(this._nodes, function(value, v) {
  21863. if (filter(v)) {
  21864. copy.setNode(v, value);
  21865. }
  21866. });
  21867. _.each(this._edgeObjs, function(e) {
  21868. if (copy.hasNode(e.v) && copy.hasNode(e.w)) {
  21869. copy.setEdge(e, self.edge(e));
  21870. }
  21871. });
  21872. var parents = {};
  21873. function findParent(v) {
  21874. var parent = self.parent(v);
  21875. if (parent === undefined || copy.hasNode(parent)) {
  21876. parents[v] = parent;
  21877. return parent;
  21878. } else if (parent in parents) {
  21879. return parents[parent];
  21880. } else {
  21881. return findParent(parent);
  21882. }
  21883. }
  21884. if (this._isCompound) {
  21885. _.each(copy.nodes(), function(v) {
  21886. copy.setParent(v, findParent(v));
  21887. });
  21888. }
  21889. return copy;
  21890. };
  21891. /* === Edge functions ========== */
  21892. Graph.prototype.setDefaultEdgeLabel = function(newDefault) {
  21893. if (!_.isFunction(newDefault)) {
  21894. newDefault = _.constant(newDefault);
  21895. }
  21896. this._defaultEdgeLabelFn = newDefault;
  21897. return this;
  21898. };
  21899. Graph.prototype.edgeCount = function() {
  21900. return this._edgeCount;
  21901. };
  21902. Graph.prototype.edges = function() {
  21903. return _.values(this._edgeObjs);
  21904. };
  21905. Graph.prototype.setPath = function(vs, value) {
  21906. var self = this,
  21907. args = arguments;
  21908. _.reduce(vs, function(v, w) {
  21909. if (args.length > 1) {
  21910. self.setEdge(v, w, value);
  21911. } else {
  21912. self.setEdge(v, w);
  21913. }
  21914. return w;
  21915. });
  21916. return this;
  21917. };
  21918. /*
  21919. * setEdge(v, w, [value, [name]])
  21920. * setEdge({ v, w, [name] }, [value])
  21921. */
  21922. Graph.prototype.setEdge = function() {
  21923. var v, w, name, value,
  21924. valueSpecified = false,
  21925. arg0 = arguments[0];
  21926. if (typeof arg0 === "object" && arg0 !== null && "v" in arg0) {
  21927. v = arg0.v;
  21928. w = arg0.w;
  21929. name = arg0.name;
  21930. if (arguments.length === 2) {
  21931. value = arguments[1];
  21932. valueSpecified = true;
  21933. }
  21934. } else {
  21935. v = arg0;
  21936. w = arguments[1];
  21937. name = arguments[3];
  21938. if (arguments.length > 2) {
  21939. value = arguments[2];
  21940. valueSpecified = true;
  21941. }
  21942. }
  21943. v = "" + v;
  21944. w = "" + w;
  21945. if (!_.isUndefined(name)) {
  21946. name = "" + name;
  21947. }
  21948. var e = edgeArgsToId(this._isDirected, v, w, name);
  21949. if (_.has(this._edgeLabels, e)) {
  21950. if (valueSpecified) {
  21951. this._edgeLabels[e] = value;
  21952. }
  21953. return this;
  21954. }
  21955. if (!_.isUndefined(name) && !this._isMultigraph) {
  21956. throw new Error("Cannot set a named edge when isMultigraph = false");
  21957. }
  21958. // It didn't exist, so we need to create it.
  21959. // First ensure the nodes exist.
  21960. this.setNode(v);
  21961. this.setNode(w);
  21962. this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name);
  21963. var edgeObj = edgeArgsToObj(this._isDirected, v, w, name);
  21964. // Ensure we add undirected edges in a consistent way.
  21965. v = edgeObj.v;
  21966. w = edgeObj.w;
  21967. Object.freeze(edgeObj);
  21968. this._edgeObjs[e] = edgeObj;
  21969. incrementOrInitEntry(this._preds[w], v);
  21970. incrementOrInitEntry(this._sucs[v], w);
  21971. this._in[w][e] = edgeObj;
  21972. this._out[v][e] = edgeObj;
  21973. this._edgeCount++;
  21974. return this;
  21975. };
  21976. Graph.prototype.edge = function(v, w, name) {
  21977. var e = (arguments.length === 1
  21978. ? edgeObjToId(this._isDirected, arguments[0])
  21979. : edgeArgsToId(this._isDirected, v, w, name));
  21980. return this._edgeLabels[e];
  21981. };
  21982. Graph.prototype.hasEdge = function(v, w, name) {
  21983. var e = (arguments.length === 1
  21984. ? edgeObjToId(this._isDirected, arguments[0])
  21985. : edgeArgsToId(this._isDirected, v, w, name));
  21986. return _.has(this._edgeLabels, e);
  21987. };
  21988. Graph.prototype.removeEdge = function(v, w, name) {
  21989. var e = (arguments.length === 1
  21990. ? edgeObjToId(this._isDirected, arguments[0])
  21991. : edgeArgsToId(this._isDirected, v, w, name)),
  21992. edge = this._edgeObjs[e];
  21993. if (edge) {
  21994. v = edge.v;
  21995. w = edge.w;
  21996. delete this._edgeLabels[e];
  21997. delete this._edgeObjs[e];
  21998. decrementOrRemoveEntry(this._preds[w], v);
  21999. decrementOrRemoveEntry(this._sucs[v], w);
  22000. delete this._in[w][e];
  22001. delete this._out[v][e];
  22002. this._edgeCount--;
  22003. }
  22004. return this;
  22005. };
  22006. Graph.prototype.inEdges = function(v, u) {
  22007. var inV = this._in[v];
  22008. if (inV) {
  22009. var edges = _.values(inV);
  22010. if (!u) {
  22011. return edges;
  22012. }
  22013. return _.filter(edges, function(edge) { return edge.v === u; });
  22014. }
  22015. };
  22016. Graph.prototype.outEdges = function(v, w) {
  22017. var outV = this._out[v];
  22018. if (outV) {
  22019. var edges = _.values(outV);
  22020. if (!w) {
  22021. return edges;
  22022. }
  22023. return _.filter(edges, function(edge) { return edge.w === w; });
  22024. }
  22025. };
  22026. Graph.prototype.nodeEdges = function(v, w) {
  22027. var inEdges = this.inEdges(v, w);
  22028. if (inEdges) {
  22029. return inEdges.concat(this.outEdges(v, w));
  22030. }
  22031. };
  22032. function incrementOrInitEntry(map, k) {
  22033. if (map[k]) {
  22034. map[k]++;
  22035. } else {
  22036. map[k] = 1;
  22037. }
  22038. }
  22039. function decrementOrRemoveEntry(map, k) {
  22040. if (!--map[k]) { delete map[k]; }
  22041. }
  22042. function edgeArgsToId(isDirected, v_, w_, name) {
  22043. var v = "" + v_;
  22044. var w = "" + w_;
  22045. if (!isDirected && v > w) {
  22046. var tmp = v;
  22047. v = w;
  22048. w = tmp;
  22049. }
  22050. return v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM +
  22051. (_.isUndefined(name) ? DEFAULT_EDGE_NAME : name);
  22052. }
  22053. function edgeArgsToObj(isDirected, v_, w_, name) {
  22054. var v = "" + v_;
  22055. var w = "" + w_;
  22056. if (!isDirected && v > w) {
  22057. var tmp = v;
  22058. v = w;
  22059. w = tmp;
  22060. }
  22061. var edgeObj = { v: v, w: w };
  22062. if (name) {
  22063. edgeObj.name = name;
  22064. }
  22065. return edgeObj;
  22066. }
  22067. function edgeObjToId(isDirected, edgeObj) {
  22068. return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name);
  22069. }
  22070. },{"./lodash":118}],116:[function(require,module,exports){
  22071. // Includes only the "core" of graphlib
  22072. module.exports = {
  22073. Graph: require("./graph"),
  22074. version: require("./version")
  22075. };
  22076. },{"./graph":115,"./version":119}],117:[function(require,module,exports){
  22077. var _ = require("./lodash"),
  22078. Graph = require("./graph");
  22079. module.exports = {
  22080. write: write,
  22081. read: read
  22082. };
  22083. function write(g) {
  22084. var json = {
  22085. options: {
  22086. directed: g.isDirected(),
  22087. multigraph: g.isMultigraph(),
  22088. compound: g.isCompound()
  22089. },
  22090. nodes: writeNodes(g),
  22091. edges: writeEdges(g)
  22092. };
  22093. if (!_.isUndefined(g.graph())) {
  22094. json.value = _.clone(g.graph());
  22095. }
  22096. return json;
  22097. }
  22098. function writeNodes(g) {
  22099. return _.map(g.nodes(), function(v) {
  22100. var nodeValue = g.node(v),
  22101. parent = g.parent(v),
  22102. node = { v: v };
  22103. if (!_.isUndefined(nodeValue)) {
  22104. node.value = nodeValue;
  22105. }
  22106. if (!_.isUndefined(parent)) {
  22107. node.parent = parent;
  22108. }
  22109. return node;
  22110. });
  22111. }
  22112. function writeEdges(g) {
  22113. return _.map(g.edges(), function(e) {
  22114. var edgeValue = g.edge(e),
  22115. edge = { v: e.v, w: e.w };
  22116. if (!_.isUndefined(e.name)) {
  22117. edge.name = e.name;
  22118. }
  22119. if (!_.isUndefined(edgeValue)) {
  22120. edge.value = edgeValue;
  22121. }
  22122. return edge;
  22123. });
  22124. }
  22125. function read(json) {
  22126. var g = new Graph(json.options).setGraph(json.value);
  22127. _.each(json.nodes, function(entry) {
  22128. g.setNode(entry.v, entry.value);
  22129. if (entry.parent) {
  22130. g.setParent(entry.v, entry.parent);
  22131. }
  22132. });
  22133. _.each(json.edges, function(entry) {
  22134. g.setEdge({ v: entry.v, w: entry.w, name: entry.name }, entry.value);
  22135. });
  22136. return g;
  22137. }
  22138. },{"./graph":115,"./lodash":118}],118:[function(require,module,exports){
  22139. arguments[4][79][0].apply(exports,arguments)
  22140. },{"dup":79,"lodash":123}],119:[function(require,module,exports){
  22141. module.exports = '2.1.5';
  22142. },{}],120:[function(require,module,exports){
  22143. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  22144. var e, m
  22145. var eLen = nBytes * 8 - mLen - 1
  22146. var eMax = (1 << eLen) - 1
  22147. var eBias = eMax >> 1
  22148. var nBits = -7
  22149. var i = isLE ? (nBytes - 1) : 0
  22150. var d = isLE ? -1 : 1
  22151. var s = buffer[offset + i]
  22152. i += d
  22153. e = s & ((1 << (-nBits)) - 1)
  22154. s >>= (-nBits)
  22155. nBits += eLen
  22156. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  22157. m = e & ((1 << (-nBits)) - 1)
  22158. e >>= (-nBits)
  22159. nBits += mLen
  22160. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  22161. if (e === 0) {
  22162. e = 1 - eBias
  22163. } else if (e === eMax) {
  22164. return m ? NaN : ((s ? -1 : 1) * Infinity)
  22165. } else {
  22166. m = m + Math.pow(2, mLen)
  22167. e = e - eBias
  22168. }
  22169. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  22170. }
  22171. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  22172. var e, m, c
  22173. var eLen = nBytes * 8 - mLen - 1
  22174. var eMax = (1 << eLen) - 1
  22175. var eBias = eMax >> 1
  22176. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  22177. var i = isLE ? 0 : (nBytes - 1)
  22178. var d = isLE ? 1 : -1
  22179. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  22180. value = Math.abs(value)
  22181. if (isNaN(value) || value === Infinity) {
  22182. m = isNaN(value) ? 1 : 0
  22183. e = eMax
  22184. } else {
  22185. e = Math.floor(Math.log(value) / Math.LN2)
  22186. if (value * (c = Math.pow(2, -e)) < 1) {
  22187. e--
  22188. c *= 2
  22189. }
  22190. if (e + eBias >= 1) {
  22191. value += rt / c
  22192. } else {
  22193. value += rt * Math.pow(2, 1 - eBias)
  22194. }
  22195. if (value * c >= 2) {
  22196. e++
  22197. c /= 2
  22198. }
  22199. if (e + eBias >= eMax) {
  22200. m = 0
  22201. e = eMax
  22202. } else if (e + eBias >= 1) {
  22203. m = (value * c - 1) * Math.pow(2, mLen)
  22204. e = e + eBias
  22205. } else {
  22206. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  22207. e = 0
  22208. }
  22209. }
  22210. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  22211. e = (e << mLen) | m
  22212. eLen += mLen
  22213. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  22214. buffer[offset + i - d] |= s * 128
  22215. }
  22216. },{}],121:[function(require,module,exports){
  22217. if (typeof Object.create === 'function') {
  22218. // implementation from standard node.js 'util' module
  22219. module.exports = function inherits(ctor, superCtor) {
  22220. ctor.super_ = superCtor
  22221. ctor.prototype = Object.create(superCtor.prototype, {
  22222. constructor: {
  22223. value: ctor,
  22224. enumerable: false,
  22225. writable: true,
  22226. configurable: true
  22227. }
  22228. });
  22229. };
  22230. } else {
  22231. // old school shim for old browsers
  22232. module.exports = function inherits(ctor, superCtor) {
  22233. ctor.super_ = superCtor
  22234. var TempCtor = function () {}
  22235. TempCtor.prototype = superCtor.prototype
  22236. ctor.prototype = new TempCtor()
  22237. ctor.prototype.constructor = ctor
  22238. }
  22239. }
  22240. },{}],122:[function(require,module,exports){
  22241. /*!
  22242. * Determine if an object is a Buffer
  22243. *
  22244. * @author Feross Aboukhadijeh <https://feross.org>
  22245. * @license MIT
  22246. */
  22247. // The _isBuffer check is for Safari 5-7 support, because it's missing
  22248. // Object.prototype.constructor. Remove this eventually
  22249. module.exports = function (obj) {
  22250. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  22251. }
  22252. function isBuffer (obj) {
  22253. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  22254. }
  22255. // For Node v0.10 support. Remove this eventually.
  22256. function isSlowBuffer (obj) {
  22257. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  22258. }
  22259. },{}],123:[function(require,module,exports){
  22260. (function (global){
  22261. /**
  22262. * @license
  22263. * Lodash <https://lodash.com/>
  22264. * Copyright JS Foundation and other contributors <https://js.foundation/>
  22265. * Released under MIT license <https://lodash.com/license>
  22266. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  22267. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  22268. */
  22269. ;(function() {
  22270. /** Used as a safe reference for `undefined` in pre-ES5 environments. */
  22271. var undefined;
  22272. /** Used as the semantic version number. */
  22273. var VERSION = '4.17.4';
  22274. /** Used as the size to enable large array optimizations. */
  22275. var LARGE_ARRAY_SIZE = 200;
  22276. /** Error message constants. */
  22277. var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
  22278. FUNC_ERROR_TEXT = 'Expected a function';
  22279. /** Used to stand-in for `undefined` hash values. */
  22280. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  22281. /** Used as the maximum memoize cache size. */
  22282. var MAX_MEMOIZE_SIZE = 500;
  22283. /** Used as the internal argument placeholder. */
  22284. var PLACEHOLDER = '__lodash_placeholder__';
  22285. /** Used to compose bitmasks for cloning. */
  22286. var CLONE_DEEP_FLAG = 1,
  22287. CLONE_FLAT_FLAG = 2,
  22288. CLONE_SYMBOLS_FLAG = 4;
  22289. /** Used to compose bitmasks for value comparisons. */
  22290. var COMPARE_PARTIAL_FLAG = 1,
  22291. COMPARE_UNORDERED_FLAG = 2;
  22292. /** Used to compose bitmasks for function metadata. */
  22293. var WRAP_BIND_FLAG = 1,
  22294. WRAP_BIND_KEY_FLAG = 2,
  22295. WRAP_CURRY_BOUND_FLAG = 4,
  22296. WRAP_CURRY_FLAG = 8,
  22297. WRAP_CURRY_RIGHT_FLAG = 16,
  22298. WRAP_PARTIAL_FLAG = 32,
  22299. WRAP_PARTIAL_RIGHT_FLAG = 64,
  22300. WRAP_ARY_FLAG = 128,
  22301. WRAP_REARG_FLAG = 256,
  22302. WRAP_FLIP_FLAG = 512;
  22303. /** Used as default options for `_.truncate`. */
  22304. var DEFAULT_TRUNC_LENGTH = 30,
  22305. DEFAULT_TRUNC_OMISSION = '...';
  22306. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  22307. var HOT_COUNT = 800,
  22308. HOT_SPAN = 16;
  22309. /** Used to indicate the type of lazy iteratees. */
  22310. var LAZY_FILTER_FLAG = 1,
  22311. LAZY_MAP_FLAG = 2,
  22312. LAZY_WHILE_FLAG = 3;
  22313. /** Used as references for various `Number` constants. */
  22314. var INFINITY = 1 / 0,
  22315. MAX_SAFE_INTEGER = 9007199254740991,
  22316. MAX_INTEGER = 1.7976931348623157e+308,
  22317. NAN = 0 / 0;
  22318. /** Used as references for the maximum length and index of an array. */
  22319. var MAX_ARRAY_LENGTH = 4294967295,
  22320. MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
  22321. HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
  22322. /** Used to associate wrap methods with their bit flags. */
  22323. var wrapFlags = [
  22324. ['ary', WRAP_ARY_FLAG],
  22325. ['bind', WRAP_BIND_FLAG],
  22326. ['bindKey', WRAP_BIND_KEY_FLAG],
  22327. ['curry', WRAP_CURRY_FLAG],
  22328. ['curryRight', WRAP_CURRY_RIGHT_FLAG],
  22329. ['flip', WRAP_FLIP_FLAG],
  22330. ['partial', WRAP_PARTIAL_FLAG],
  22331. ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
  22332. ['rearg', WRAP_REARG_FLAG]
  22333. ];
  22334. /** `Object#toString` result references. */
  22335. var argsTag = '[object Arguments]',
  22336. arrayTag = '[object Array]',
  22337. asyncTag = '[object AsyncFunction]',
  22338. boolTag = '[object Boolean]',
  22339. dateTag = '[object Date]',
  22340. domExcTag = '[object DOMException]',
  22341. errorTag = '[object Error]',
  22342. funcTag = '[object Function]',
  22343. genTag = '[object GeneratorFunction]',
  22344. mapTag = '[object Map]',
  22345. numberTag = '[object Number]',
  22346. nullTag = '[object Null]',
  22347. objectTag = '[object Object]',
  22348. promiseTag = '[object Promise]',
  22349. proxyTag = '[object Proxy]',
  22350. regexpTag = '[object RegExp]',
  22351. setTag = '[object Set]',
  22352. stringTag = '[object String]',
  22353. symbolTag = '[object Symbol]',
  22354. undefinedTag = '[object Undefined]',
  22355. weakMapTag = '[object WeakMap]',
  22356. weakSetTag = '[object WeakSet]';
  22357. var arrayBufferTag = '[object ArrayBuffer]',
  22358. dataViewTag = '[object DataView]',
  22359. float32Tag = '[object Float32Array]',
  22360. float64Tag = '[object Float64Array]',
  22361. int8Tag = '[object Int8Array]',
  22362. int16Tag = '[object Int16Array]',
  22363. int32Tag = '[object Int32Array]',
  22364. uint8Tag = '[object Uint8Array]',
  22365. uint8ClampedTag = '[object Uint8ClampedArray]',
  22366. uint16Tag = '[object Uint16Array]',
  22367. uint32Tag = '[object Uint32Array]';
  22368. /** Used to match empty string literals in compiled template source. */
  22369. var reEmptyStringLeading = /\b__p \+= '';/g,
  22370. reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
  22371. reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
  22372. /** Used to match HTML entities and HTML characters. */
  22373. var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
  22374. reUnescapedHtml = /[&<>"']/g,
  22375. reHasEscapedHtml = RegExp(reEscapedHtml.source),
  22376. reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
  22377. /** Used to match template delimiters. */
  22378. var reEscape = /<%-([\s\S]+?)%>/g,
  22379. reEvaluate = /<%([\s\S]+?)%>/g,
  22380. reInterpolate = /<%=([\s\S]+?)%>/g;
  22381. /** Used to match property names within property paths. */
  22382. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  22383. reIsPlainProp = /^\w*$/,
  22384. reLeadingDot = /^\./,
  22385. rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  22386. /**
  22387. * Used to match `RegExp`
  22388. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  22389. */
  22390. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
  22391. reHasRegExpChar = RegExp(reRegExpChar.source);
  22392. /** Used to match leading and trailing whitespace. */
  22393. var reTrim = /^\s+|\s+$/g,
  22394. reTrimStart = /^\s+/,
  22395. reTrimEnd = /\s+$/;
  22396. /** Used to match wrap detail comments. */
  22397. var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
  22398. reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
  22399. reSplitDetails = /,? & /;
  22400. /** Used to match words composed of alphanumeric characters. */
  22401. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  22402. /** Used to match backslashes in property paths. */
  22403. var reEscapeChar = /\\(\\)?/g;
  22404. /**
  22405. * Used to match
  22406. * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
  22407. */
  22408. var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
  22409. /** Used to match `RegExp` flags from their coerced string values. */
  22410. var reFlags = /\w*$/;
  22411. /** Used to detect bad signed hexadecimal string values. */
  22412. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  22413. /** Used to detect binary string values. */
  22414. var reIsBinary = /^0b[01]+$/i;
  22415. /** Used to detect host constructors (Safari). */
  22416. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  22417. /** Used to detect octal string values. */
  22418. var reIsOctal = /^0o[0-7]+$/i;
  22419. /** Used to detect unsigned integer values. */
  22420. var reIsUint = /^(?:0|[1-9]\d*)$/;
  22421. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  22422. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  22423. /** Used to ensure capturing order of template delimiters. */
  22424. var reNoMatch = /($^)/;
  22425. /** Used to match unescaped characters in compiled string literals. */
  22426. var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
  22427. /** Used to compose unicode character classes. */
  22428. var rsAstralRange = '\\ud800-\\udfff',
  22429. rsComboMarksRange = '\\u0300-\\u036f',
  22430. reComboHalfMarksRange = '\\ufe20-\\ufe2f',
  22431. rsComboSymbolsRange = '\\u20d0-\\u20ff',
  22432. rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
  22433. rsDingbatRange = '\\u2700-\\u27bf',
  22434. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  22435. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  22436. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  22437. rsPunctuationRange = '\\u2000-\\u206f',
  22438. rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
  22439. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  22440. rsVarRange = '\\ufe0e\\ufe0f',
  22441. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  22442. /** Used to compose unicode capture groups. */
  22443. var rsApos = "['\u2019]",
  22444. rsAstral = '[' + rsAstralRange + ']',
  22445. rsBreak = '[' + rsBreakRange + ']',
  22446. rsCombo = '[' + rsComboRange + ']',
  22447. rsDigits = '\\d+',
  22448. rsDingbat = '[' + rsDingbatRange + ']',
  22449. rsLower = '[' + rsLowerRange + ']',
  22450. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  22451. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  22452. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  22453. rsNonAstral = '[^' + rsAstralRange + ']',
  22454. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  22455. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  22456. rsUpper = '[' + rsUpperRange + ']',
  22457. rsZWJ = '\\u200d';
  22458. /** Used to compose unicode regexes. */
  22459. var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
  22460. rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
  22461. rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  22462. rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  22463. reOptMod = rsModifier + '?',
  22464. rsOptVar = '[' + rsVarRange + ']?',
  22465. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  22466. rsOrdLower = '\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)',
  22467. rsOrdUpper = '\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)',
  22468. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  22469. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  22470. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  22471. /** Used to match apostrophes. */
  22472. var reApos = RegExp(rsApos, 'g');
  22473. /**
  22474. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  22475. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  22476. */
  22477. var reComboMark = RegExp(rsCombo, 'g');
  22478. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  22479. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  22480. /** Used to match complex or compound words. */
  22481. var reUnicodeWord = RegExp([
  22482. rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  22483. rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
  22484. rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
  22485. rsUpper + '+' + rsOptContrUpper,
  22486. rsOrdUpper,
  22487. rsOrdLower,
  22488. rsDigits,
  22489. rsEmoji
  22490. ].join('|'), 'g');
  22491. /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
  22492. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
  22493. /** Used to detect strings that need a more robust regexp to match words. */
  22494. var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
  22495. /** Used to assign default `context` object properties. */
  22496. var contextProps = [
  22497. 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
  22498. 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
  22499. 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
  22500. 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
  22501. '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
  22502. ];
  22503. /** Used to make template sourceURLs easier to identify. */
  22504. var templateCounter = -1;
  22505. /** Used to identify `toStringTag` values of typed arrays. */
  22506. var typedArrayTags = {};
  22507. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  22508. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  22509. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  22510. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  22511. typedArrayTags[uint32Tag] = true;
  22512. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  22513. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  22514. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  22515. typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  22516. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  22517. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  22518. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  22519. typedArrayTags[weakMapTag] = false;
  22520. /** Used to identify `toStringTag` values supported by `_.clone`. */
  22521. var cloneableTags = {};
  22522. cloneableTags[argsTag] = cloneableTags[arrayTag] =
  22523. cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
  22524. cloneableTags[boolTag] = cloneableTags[dateTag] =
  22525. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  22526. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  22527. cloneableTags[int32Tag] = cloneableTags[mapTag] =
  22528. cloneableTags[numberTag] = cloneableTags[objectTag] =
  22529. cloneableTags[regexpTag] = cloneableTags[setTag] =
  22530. cloneableTags[stringTag] = cloneableTags[symbolTag] =
  22531. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  22532. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  22533. cloneableTags[errorTag] = cloneableTags[funcTag] =
  22534. cloneableTags[weakMapTag] = false;
  22535. /** Used to map Latin Unicode letters to basic Latin letters. */
  22536. var deburredLetters = {
  22537. // Latin-1 Supplement block.
  22538. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  22539. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  22540. '\xc7': 'C', '\xe7': 'c',
  22541. '\xd0': 'D', '\xf0': 'd',
  22542. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  22543. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  22544. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  22545. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  22546. '\xd1': 'N', '\xf1': 'n',
  22547. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  22548. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  22549. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  22550. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  22551. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  22552. '\xc6': 'Ae', '\xe6': 'ae',
  22553. '\xde': 'Th', '\xfe': 'th',
  22554. '\xdf': 'ss',
  22555. // Latin Extended-A block.
  22556. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  22557. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  22558. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  22559. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  22560. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  22561. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  22562. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  22563. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  22564. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  22565. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  22566. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  22567. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  22568. '\u0134': 'J', '\u0135': 'j',
  22569. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  22570. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  22571. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  22572. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  22573. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  22574. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  22575. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  22576. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  22577. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  22578. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  22579. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  22580. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  22581. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  22582. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  22583. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  22584. '\u0174': 'W', '\u0175': 'w',
  22585. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  22586. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  22587. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  22588. '\u0132': 'IJ', '\u0133': 'ij',
  22589. '\u0152': 'Oe', '\u0153': 'oe',
  22590. '\u0149': "'n", '\u017f': 's'
  22591. };
  22592. /** Used to map characters to HTML entities. */
  22593. var htmlEscapes = {
  22594. '&': '&amp;',
  22595. '<': '&lt;',
  22596. '>': '&gt;',
  22597. '"': '&quot;',
  22598. "'": '&#39;'
  22599. };
  22600. /** Used to map HTML entities to characters. */
  22601. var htmlUnescapes = {
  22602. '&amp;': '&',
  22603. '&lt;': '<',
  22604. '&gt;': '>',
  22605. '&quot;': '"',
  22606. '&#39;': "'"
  22607. };
  22608. /** Used to escape characters for inclusion in compiled string literals. */
  22609. var stringEscapes = {
  22610. '\\': '\\',
  22611. "'": "'",
  22612. '\n': 'n',
  22613. '\r': 'r',
  22614. '\u2028': 'u2028',
  22615. '\u2029': 'u2029'
  22616. };
  22617. /** Built-in method references without a dependency on `root`. */
  22618. var freeParseFloat = parseFloat,
  22619. freeParseInt = parseInt;
  22620. /** Detect free variable `global` from Node.js. */
  22621. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  22622. /** Detect free variable `self`. */
  22623. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  22624. /** Used as a reference to the global object. */
  22625. var root = freeGlobal || freeSelf || Function('return this')();
  22626. /** Detect free variable `exports`. */
  22627. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  22628. /** Detect free variable `module`. */
  22629. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  22630. /** Detect the popular CommonJS extension `module.exports`. */
  22631. var moduleExports = freeModule && freeModule.exports === freeExports;
  22632. /** Detect free variable `process` from Node.js. */
  22633. var freeProcess = moduleExports && freeGlobal.process;
  22634. /** Used to access faster Node.js helpers. */
  22635. var nodeUtil = (function() {
  22636. try {
  22637. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  22638. } catch (e) {}
  22639. }());
  22640. /* Node.js helper references. */
  22641. var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
  22642. nodeIsDate = nodeUtil && nodeUtil.isDate,
  22643. nodeIsMap = nodeUtil && nodeUtil.isMap,
  22644. nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
  22645. nodeIsSet = nodeUtil && nodeUtil.isSet,
  22646. nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  22647. /*--------------------------------------------------------------------------*/
  22648. /**
  22649. * Adds the key-value `pair` to `map`.
  22650. *
  22651. * @private
  22652. * @param {Object} map The map to modify.
  22653. * @param {Array} pair The key-value pair to add.
  22654. * @returns {Object} Returns `map`.
  22655. */
  22656. function addMapEntry(map, pair) {
  22657. // Don't return `map.set` because it's not chainable in IE 11.
  22658. map.set(pair[0], pair[1]);
  22659. return map;
  22660. }
  22661. /**
  22662. * Adds `value` to `set`.
  22663. *
  22664. * @private
  22665. * @param {Object} set The set to modify.
  22666. * @param {*} value The value to add.
  22667. * @returns {Object} Returns `set`.
  22668. */
  22669. function addSetEntry(set, value) {
  22670. // Don't return `set.add` because it's not chainable in IE 11.
  22671. set.add(value);
  22672. return set;
  22673. }
  22674. /**
  22675. * A faster alternative to `Function#apply`, this function invokes `func`
  22676. * with the `this` binding of `thisArg` and the arguments of `args`.
  22677. *
  22678. * @private
  22679. * @param {Function} func The function to invoke.
  22680. * @param {*} thisArg The `this` binding of `func`.
  22681. * @param {Array} args The arguments to invoke `func` with.
  22682. * @returns {*} Returns the result of `func`.
  22683. */
  22684. function apply(func, thisArg, args) {
  22685. switch (args.length) {
  22686. case 0: return func.call(thisArg);
  22687. case 1: return func.call(thisArg, args[0]);
  22688. case 2: return func.call(thisArg, args[0], args[1]);
  22689. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  22690. }
  22691. return func.apply(thisArg, args);
  22692. }
  22693. /**
  22694. * A specialized version of `baseAggregator` for arrays.
  22695. *
  22696. * @private
  22697. * @param {Array} [array] The array to iterate over.
  22698. * @param {Function} setter The function to set `accumulator` values.
  22699. * @param {Function} iteratee The iteratee to transform keys.
  22700. * @param {Object} accumulator The initial aggregated object.
  22701. * @returns {Function} Returns `accumulator`.
  22702. */
  22703. function arrayAggregator(array, setter, iteratee, accumulator) {
  22704. var index = -1,
  22705. length = array == null ? 0 : array.length;
  22706. while (++index < length) {
  22707. var value = array[index];
  22708. setter(accumulator, value, iteratee(value), array);
  22709. }
  22710. return accumulator;
  22711. }
  22712. /**
  22713. * A specialized version of `_.forEach` for arrays without support for
  22714. * iteratee shorthands.
  22715. *
  22716. * @private
  22717. * @param {Array} [array] The array to iterate over.
  22718. * @param {Function} iteratee The function invoked per iteration.
  22719. * @returns {Array} Returns `array`.
  22720. */
  22721. function arrayEach(array, iteratee) {
  22722. var index = -1,
  22723. length = array == null ? 0 : array.length;
  22724. while (++index < length) {
  22725. if (iteratee(array[index], index, array) === false) {
  22726. break;
  22727. }
  22728. }
  22729. return array;
  22730. }
  22731. /**
  22732. * A specialized version of `_.forEachRight` for arrays without support for
  22733. * iteratee shorthands.
  22734. *
  22735. * @private
  22736. * @param {Array} [array] The array to iterate over.
  22737. * @param {Function} iteratee The function invoked per iteration.
  22738. * @returns {Array} Returns `array`.
  22739. */
  22740. function arrayEachRight(array, iteratee) {
  22741. var length = array == null ? 0 : array.length;
  22742. while (length--) {
  22743. if (iteratee(array[length], length, array) === false) {
  22744. break;
  22745. }
  22746. }
  22747. return array;
  22748. }
  22749. /**
  22750. * A specialized version of `_.every` for arrays without support for
  22751. * iteratee shorthands.
  22752. *
  22753. * @private
  22754. * @param {Array} [array] The array to iterate over.
  22755. * @param {Function} predicate The function invoked per iteration.
  22756. * @returns {boolean} Returns `true` if all elements pass the predicate check,
  22757. * else `false`.
  22758. */
  22759. function arrayEvery(array, predicate) {
  22760. var index = -1,
  22761. length = array == null ? 0 : array.length;
  22762. while (++index < length) {
  22763. if (!predicate(array[index], index, array)) {
  22764. return false;
  22765. }
  22766. }
  22767. return true;
  22768. }
  22769. /**
  22770. * A specialized version of `_.filter` for arrays without support for
  22771. * iteratee shorthands.
  22772. *
  22773. * @private
  22774. * @param {Array} [array] The array to iterate over.
  22775. * @param {Function} predicate The function invoked per iteration.
  22776. * @returns {Array} Returns the new filtered array.
  22777. */
  22778. function arrayFilter(array, predicate) {
  22779. var index = -1,
  22780. length = array == null ? 0 : array.length,
  22781. resIndex = 0,
  22782. result = [];
  22783. while (++index < length) {
  22784. var value = array[index];
  22785. if (predicate(value, index, array)) {
  22786. result[resIndex++] = value;
  22787. }
  22788. }
  22789. return result;
  22790. }
  22791. /**
  22792. * A specialized version of `_.includes` for arrays without support for
  22793. * specifying an index to search from.
  22794. *
  22795. * @private
  22796. * @param {Array} [array] The array to inspect.
  22797. * @param {*} target The value to search for.
  22798. * @returns {boolean} Returns `true` if `target` is found, else `false`.
  22799. */
  22800. function arrayIncludes(array, value) {
  22801. var length = array == null ? 0 : array.length;
  22802. return !!length && baseIndexOf(array, value, 0) > -1;
  22803. }
  22804. /**
  22805. * This function is like `arrayIncludes` except that it accepts a comparator.
  22806. *
  22807. * @private
  22808. * @param {Array} [array] The array to inspect.
  22809. * @param {*} target The value to search for.
  22810. * @param {Function} comparator The comparator invoked per element.
  22811. * @returns {boolean} Returns `true` if `target` is found, else `false`.
  22812. */
  22813. function arrayIncludesWith(array, value, comparator) {
  22814. var index = -1,
  22815. length = array == null ? 0 : array.length;
  22816. while (++index < length) {
  22817. if (comparator(value, array[index])) {
  22818. return true;
  22819. }
  22820. }
  22821. return false;
  22822. }
  22823. /**
  22824. * A specialized version of `_.map` for arrays without support for iteratee
  22825. * shorthands.
  22826. *
  22827. * @private
  22828. * @param {Array} [array] The array to iterate over.
  22829. * @param {Function} iteratee The function invoked per iteration.
  22830. * @returns {Array} Returns the new mapped array.
  22831. */
  22832. function arrayMap(array, iteratee) {
  22833. var index = -1,
  22834. length = array == null ? 0 : array.length,
  22835. result = Array(length);
  22836. while (++index < length) {
  22837. result[index] = iteratee(array[index], index, array);
  22838. }
  22839. return result;
  22840. }
  22841. /**
  22842. * Appends the elements of `values` to `array`.
  22843. *
  22844. * @private
  22845. * @param {Array} array The array to modify.
  22846. * @param {Array} values The values to append.
  22847. * @returns {Array} Returns `array`.
  22848. */
  22849. function arrayPush(array, values) {
  22850. var index = -1,
  22851. length = values.length,
  22852. offset = array.length;
  22853. while (++index < length) {
  22854. array[offset + index] = values[index];
  22855. }
  22856. return array;
  22857. }
  22858. /**
  22859. * A specialized version of `_.reduce` for arrays without support for
  22860. * iteratee shorthands.
  22861. *
  22862. * @private
  22863. * @param {Array} [array] The array to iterate over.
  22864. * @param {Function} iteratee The function invoked per iteration.
  22865. * @param {*} [accumulator] The initial value.
  22866. * @param {boolean} [initAccum] Specify using the first element of `array` as
  22867. * the initial value.
  22868. * @returns {*} Returns the accumulated value.
  22869. */
  22870. function arrayReduce(array, iteratee, accumulator, initAccum) {
  22871. var index = -1,
  22872. length = array == null ? 0 : array.length;
  22873. if (initAccum && length) {
  22874. accumulator = array[++index];
  22875. }
  22876. while (++index < length) {
  22877. accumulator = iteratee(accumulator, array[index], index, array);
  22878. }
  22879. return accumulator;
  22880. }
  22881. /**
  22882. * A specialized version of `_.reduceRight` for arrays without support for
  22883. * iteratee shorthands.
  22884. *
  22885. * @private
  22886. * @param {Array} [array] The array to iterate over.
  22887. * @param {Function} iteratee The function invoked per iteration.
  22888. * @param {*} [accumulator] The initial value.
  22889. * @param {boolean} [initAccum] Specify using the last element of `array` as
  22890. * the initial value.
  22891. * @returns {*} Returns the accumulated value.
  22892. */
  22893. function arrayReduceRight(array, iteratee, accumulator, initAccum) {
  22894. var length = array == null ? 0 : array.length;
  22895. if (initAccum && length) {
  22896. accumulator = array[--length];
  22897. }
  22898. while (length--) {
  22899. accumulator = iteratee(accumulator, array[length], length, array);
  22900. }
  22901. return accumulator;
  22902. }
  22903. /**
  22904. * A specialized version of `_.some` for arrays without support for iteratee
  22905. * shorthands.
  22906. *
  22907. * @private
  22908. * @param {Array} [array] The array to iterate over.
  22909. * @param {Function} predicate The function invoked per iteration.
  22910. * @returns {boolean} Returns `true` if any element passes the predicate check,
  22911. * else `false`.
  22912. */
  22913. function arraySome(array, predicate) {
  22914. var index = -1,
  22915. length = array == null ? 0 : array.length;
  22916. while (++index < length) {
  22917. if (predicate(array[index], index, array)) {
  22918. return true;
  22919. }
  22920. }
  22921. return false;
  22922. }
  22923. /**
  22924. * Gets the size of an ASCII `string`.
  22925. *
  22926. * @private
  22927. * @param {string} string The string inspect.
  22928. * @returns {number} Returns the string size.
  22929. */
  22930. var asciiSize = baseProperty('length');
  22931. /**
  22932. * Converts an ASCII `string` to an array.
  22933. *
  22934. * @private
  22935. * @param {string} string The string to convert.
  22936. * @returns {Array} Returns the converted array.
  22937. */
  22938. function asciiToArray(string) {
  22939. return string.split('');
  22940. }
  22941. /**
  22942. * Splits an ASCII `string` into an array of its words.
  22943. *
  22944. * @private
  22945. * @param {string} The string to inspect.
  22946. * @returns {Array} Returns the words of `string`.
  22947. */
  22948. function asciiWords(string) {
  22949. return string.match(reAsciiWord) || [];
  22950. }
  22951. /**
  22952. * The base implementation of methods like `_.findKey` and `_.findLastKey`,
  22953. * without support for iteratee shorthands, which iterates over `collection`
  22954. * using `eachFunc`.
  22955. *
  22956. * @private
  22957. * @param {Array|Object} collection The collection to inspect.
  22958. * @param {Function} predicate The function invoked per iteration.
  22959. * @param {Function} eachFunc The function to iterate over `collection`.
  22960. * @returns {*} Returns the found element or its key, else `undefined`.
  22961. */
  22962. function baseFindKey(collection, predicate, eachFunc) {
  22963. var result;
  22964. eachFunc(collection, function(value, key, collection) {
  22965. if (predicate(value, key, collection)) {
  22966. result = key;
  22967. return false;
  22968. }
  22969. });
  22970. return result;
  22971. }
  22972. /**
  22973. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  22974. * support for iteratee shorthands.
  22975. *
  22976. * @private
  22977. * @param {Array} array The array to inspect.
  22978. * @param {Function} predicate The function invoked per iteration.
  22979. * @param {number} fromIndex The index to search from.
  22980. * @param {boolean} [fromRight] Specify iterating from right to left.
  22981. * @returns {number} Returns the index of the matched value, else `-1`.
  22982. */
  22983. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  22984. var length = array.length,
  22985. index = fromIndex + (fromRight ? 1 : -1);
  22986. while ((fromRight ? index-- : ++index < length)) {
  22987. if (predicate(array[index], index, array)) {
  22988. return index;
  22989. }
  22990. }
  22991. return -1;
  22992. }
  22993. /**
  22994. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  22995. *
  22996. * @private
  22997. * @param {Array} array The array to inspect.
  22998. * @param {*} value The value to search for.
  22999. * @param {number} fromIndex The index to search from.
  23000. * @returns {number} Returns the index of the matched value, else `-1`.
  23001. */
  23002. function baseIndexOf(array, value, fromIndex) {
  23003. return value === value
  23004. ? strictIndexOf(array, value, fromIndex)
  23005. : baseFindIndex(array, baseIsNaN, fromIndex);
  23006. }
  23007. /**
  23008. * This function is like `baseIndexOf` except that it accepts a comparator.
  23009. *
  23010. * @private
  23011. * @param {Array} array The array to inspect.
  23012. * @param {*} value The value to search for.
  23013. * @param {number} fromIndex The index to search from.
  23014. * @param {Function} comparator The comparator invoked per element.
  23015. * @returns {number} Returns the index of the matched value, else `-1`.
  23016. */
  23017. function baseIndexOfWith(array, value, fromIndex, comparator) {
  23018. var index = fromIndex - 1,
  23019. length = array.length;
  23020. while (++index < length) {
  23021. if (comparator(array[index], value)) {
  23022. return index;
  23023. }
  23024. }
  23025. return -1;
  23026. }
  23027. /**
  23028. * The base implementation of `_.isNaN` without support for number objects.
  23029. *
  23030. * @private
  23031. * @param {*} value The value to check.
  23032. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  23033. */
  23034. function baseIsNaN(value) {
  23035. return value !== value;
  23036. }
  23037. /**
  23038. * The base implementation of `_.mean` and `_.meanBy` without support for
  23039. * iteratee shorthands.
  23040. *
  23041. * @private
  23042. * @param {Array} array The array to iterate over.
  23043. * @param {Function} iteratee The function invoked per iteration.
  23044. * @returns {number} Returns the mean.
  23045. */
  23046. function baseMean(array, iteratee) {
  23047. var length = array == null ? 0 : array.length;
  23048. return length ? (baseSum(array, iteratee) / length) : NAN;
  23049. }
  23050. /**
  23051. * The base implementation of `_.property` without support for deep paths.
  23052. *
  23053. * @private
  23054. * @param {string} key The key of the property to get.
  23055. * @returns {Function} Returns the new accessor function.
  23056. */
  23057. function baseProperty(key) {
  23058. return function(object) {
  23059. return object == null ? undefined : object[key];
  23060. };
  23061. }
  23062. /**
  23063. * The base implementation of `_.propertyOf` without support for deep paths.
  23064. *
  23065. * @private
  23066. * @param {Object} object The object to query.
  23067. * @returns {Function} Returns the new accessor function.
  23068. */
  23069. function basePropertyOf(object) {
  23070. return function(key) {
  23071. return object == null ? undefined : object[key];
  23072. };
  23073. }
  23074. /**
  23075. * The base implementation of `_.reduce` and `_.reduceRight`, without support
  23076. * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
  23077. *
  23078. * @private
  23079. * @param {Array|Object} collection The collection to iterate over.
  23080. * @param {Function} iteratee The function invoked per iteration.
  23081. * @param {*} accumulator The initial value.
  23082. * @param {boolean} initAccum Specify using the first or last element of
  23083. * `collection` as the initial value.
  23084. * @param {Function} eachFunc The function to iterate over `collection`.
  23085. * @returns {*} Returns the accumulated value.
  23086. */
  23087. function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
  23088. eachFunc(collection, function(value, index, collection) {
  23089. accumulator = initAccum
  23090. ? (initAccum = false, value)
  23091. : iteratee(accumulator, value, index, collection);
  23092. });
  23093. return accumulator;
  23094. }
  23095. /**
  23096. * The base implementation of `_.sortBy` which uses `comparer` to define the
  23097. * sort order of `array` and replaces criteria objects with their corresponding
  23098. * values.
  23099. *
  23100. * @private
  23101. * @param {Array} array The array to sort.
  23102. * @param {Function} comparer The function to define sort order.
  23103. * @returns {Array} Returns `array`.
  23104. */
  23105. function baseSortBy(array, comparer) {
  23106. var length = array.length;
  23107. array.sort(comparer);
  23108. while (length--) {
  23109. array[length] = array[length].value;
  23110. }
  23111. return array;
  23112. }
  23113. /**
  23114. * The base implementation of `_.sum` and `_.sumBy` without support for
  23115. * iteratee shorthands.
  23116. *
  23117. * @private
  23118. * @param {Array} array The array to iterate over.
  23119. * @param {Function} iteratee The function invoked per iteration.
  23120. * @returns {number} Returns the sum.
  23121. */
  23122. function baseSum(array, iteratee) {
  23123. var result,
  23124. index = -1,
  23125. length = array.length;
  23126. while (++index < length) {
  23127. var current = iteratee(array[index]);
  23128. if (current !== undefined) {
  23129. result = result === undefined ? current : (result + current);
  23130. }
  23131. }
  23132. return result;
  23133. }
  23134. /**
  23135. * The base implementation of `_.times` without support for iteratee shorthands
  23136. * or max array length checks.
  23137. *
  23138. * @private
  23139. * @param {number} n The number of times to invoke `iteratee`.
  23140. * @param {Function} iteratee The function invoked per iteration.
  23141. * @returns {Array} Returns the array of results.
  23142. */
  23143. function baseTimes(n, iteratee) {
  23144. var index = -1,
  23145. result = Array(n);
  23146. while (++index < n) {
  23147. result[index] = iteratee(index);
  23148. }
  23149. return result;
  23150. }
  23151. /**
  23152. * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
  23153. * of key-value pairs for `object` corresponding to the property names of `props`.
  23154. *
  23155. * @private
  23156. * @param {Object} object The object to query.
  23157. * @param {Array} props The property names to get values for.
  23158. * @returns {Object} Returns the key-value pairs.
  23159. */
  23160. function baseToPairs(object, props) {
  23161. return arrayMap(props, function(key) {
  23162. return [key, object[key]];
  23163. });
  23164. }
  23165. /**
  23166. * The base implementation of `_.unary` without support for storing metadata.
  23167. *
  23168. * @private
  23169. * @param {Function} func The function to cap arguments for.
  23170. * @returns {Function} Returns the new capped function.
  23171. */
  23172. function baseUnary(func) {
  23173. return function(value) {
  23174. return func(value);
  23175. };
  23176. }
  23177. /**
  23178. * The base implementation of `_.values` and `_.valuesIn` which creates an
  23179. * array of `object` property values corresponding to the property names
  23180. * of `props`.
  23181. *
  23182. * @private
  23183. * @param {Object} object The object to query.
  23184. * @param {Array} props The property names to get values for.
  23185. * @returns {Object} Returns the array of property values.
  23186. */
  23187. function baseValues(object, props) {
  23188. return arrayMap(props, function(key) {
  23189. return object[key];
  23190. });
  23191. }
  23192. /**
  23193. * Checks if a `cache` value for `key` exists.
  23194. *
  23195. * @private
  23196. * @param {Object} cache The cache to query.
  23197. * @param {string} key The key of the entry to check.
  23198. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  23199. */
  23200. function cacheHas(cache, key) {
  23201. return cache.has(key);
  23202. }
  23203. /**
  23204. * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
  23205. * that is not found in the character symbols.
  23206. *
  23207. * @private
  23208. * @param {Array} strSymbols The string symbols to inspect.
  23209. * @param {Array} chrSymbols The character symbols to find.
  23210. * @returns {number} Returns the index of the first unmatched string symbol.
  23211. */
  23212. function charsStartIndex(strSymbols, chrSymbols) {
  23213. var index = -1,
  23214. length = strSymbols.length;
  23215. while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  23216. return index;
  23217. }
  23218. /**
  23219. * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
  23220. * that is not found in the character symbols.
  23221. *
  23222. * @private
  23223. * @param {Array} strSymbols The string symbols to inspect.
  23224. * @param {Array} chrSymbols The character symbols to find.
  23225. * @returns {number} Returns the index of the last unmatched string symbol.
  23226. */
  23227. function charsEndIndex(strSymbols, chrSymbols) {
  23228. var index = strSymbols.length;
  23229. while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  23230. return index;
  23231. }
  23232. /**
  23233. * Gets the number of `placeholder` occurrences in `array`.
  23234. *
  23235. * @private
  23236. * @param {Array} array The array to inspect.
  23237. * @param {*} placeholder The placeholder to search for.
  23238. * @returns {number} Returns the placeholder count.
  23239. */
  23240. function countHolders(array, placeholder) {
  23241. var length = array.length,
  23242. result = 0;
  23243. while (length--) {
  23244. if (array[length] === placeholder) {
  23245. ++result;
  23246. }
  23247. }
  23248. return result;
  23249. }
  23250. /**
  23251. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  23252. * letters to basic Latin letters.
  23253. *
  23254. * @private
  23255. * @param {string} letter The matched letter to deburr.
  23256. * @returns {string} Returns the deburred letter.
  23257. */
  23258. var deburrLetter = basePropertyOf(deburredLetters);
  23259. /**
  23260. * Used by `_.escape` to convert characters to HTML entities.
  23261. *
  23262. * @private
  23263. * @param {string} chr The matched character to escape.
  23264. * @returns {string} Returns the escaped character.
  23265. */
  23266. var escapeHtmlChar = basePropertyOf(htmlEscapes);
  23267. /**
  23268. * Used by `_.template` to escape characters for inclusion in compiled string literals.
  23269. *
  23270. * @private
  23271. * @param {string} chr The matched character to escape.
  23272. * @returns {string} Returns the escaped character.
  23273. */
  23274. function escapeStringChar(chr) {
  23275. return '\\' + stringEscapes[chr];
  23276. }
  23277. /**
  23278. * Gets the value at `key` of `object`.
  23279. *
  23280. * @private
  23281. * @param {Object} [object] The object to query.
  23282. * @param {string} key The key of the property to get.
  23283. * @returns {*} Returns the property value.
  23284. */
  23285. function getValue(object, key) {
  23286. return object == null ? undefined : object[key];
  23287. }
  23288. /**
  23289. * Checks if `string` contains Unicode symbols.
  23290. *
  23291. * @private
  23292. * @param {string} string The string to inspect.
  23293. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  23294. */
  23295. function hasUnicode(string) {
  23296. return reHasUnicode.test(string);
  23297. }
  23298. /**
  23299. * Checks if `string` contains a word composed of Unicode symbols.
  23300. *
  23301. * @private
  23302. * @param {string} string The string to inspect.
  23303. * @returns {boolean} Returns `true` if a word is found, else `false`.
  23304. */
  23305. function hasUnicodeWord(string) {
  23306. return reHasUnicodeWord.test(string);
  23307. }
  23308. /**
  23309. * Converts `iterator` to an array.
  23310. *
  23311. * @private
  23312. * @param {Object} iterator The iterator to convert.
  23313. * @returns {Array} Returns the converted array.
  23314. */
  23315. function iteratorToArray(iterator) {
  23316. var data,
  23317. result = [];
  23318. while (!(data = iterator.next()).done) {
  23319. result.push(data.value);
  23320. }
  23321. return result;
  23322. }
  23323. /**
  23324. * Converts `map` to its key-value pairs.
  23325. *
  23326. * @private
  23327. * @param {Object} map The map to convert.
  23328. * @returns {Array} Returns the key-value pairs.
  23329. */
  23330. function mapToArray(map) {
  23331. var index = -1,
  23332. result = Array(map.size);
  23333. map.forEach(function(value, key) {
  23334. result[++index] = [key, value];
  23335. });
  23336. return result;
  23337. }
  23338. /**
  23339. * Creates a unary function that invokes `func` with its argument transformed.
  23340. *
  23341. * @private
  23342. * @param {Function} func The function to wrap.
  23343. * @param {Function} transform The argument transform.
  23344. * @returns {Function} Returns the new function.
  23345. */
  23346. function overArg(func, transform) {
  23347. return function(arg) {
  23348. return func(transform(arg));
  23349. };
  23350. }
  23351. /**
  23352. * Replaces all `placeholder` elements in `array` with an internal placeholder
  23353. * and returns an array of their indexes.
  23354. *
  23355. * @private
  23356. * @param {Array} array The array to modify.
  23357. * @param {*} placeholder The placeholder to replace.
  23358. * @returns {Array} Returns the new array of placeholder indexes.
  23359. */
  23360. function replaceHolders(array, placeholder) {
  23361. var index = -1,
  23362. length = array.length,
  23363. resIndex = 0,
  23364. result = [];
  23365. while (++index < length) {
  23366. var value = array[index];
  23367. if (value === placeholder || value === PLACEHOLDER) {
  23368. array[index] = PLACEHOLDER;
  23369. result[resIndex++] = index;
  23370. }
  23371. }
  23372. return result;
  23373. }
  23374. /**
  23375. * Converts `set` to an array of its values.
  23376. *
  23377. * @private
  23378. * @param {Object} set The set to convert.
  23379. * @returns {Array} Returns the values.
  23380. */
  23381. function setToArray(set) {
  23382. var index = -1,
  23383. result = Array(set.size);
  23384. set.forEach(function(value) {
  23385. result[++index] = value;
  23386. });
  23387. return result;
  23388. }
  23389. /**
  23390. * Converts `set` to its value-value pairs.
  23391. *
  23392. * @private
  23393. * @param {Object} set The set to convert.
  23394. * @returns {Array} Returns the value-value pairs.
  23395. */
  23396. function setToPairs(set) {
  23397. var index = -1,
  23398. result = Array(set.size);
  23399. set.forEach(function(value) {
  23400. result[++index] = [value, value];
  23401. });
  23402. return result;
  23403. }
  23404. /**
  23405. * A specialized version of `_.indexOf` which performs strict equality
  23406. * comparisons of values, i.e. `===`.
  23407. *
  23408. * @private
  23409. * @param {Array} array The array to inspect.
  23410. * @param {*} value The value to search for.
  23411. * @param {number} fromIndex The index to search from.
  23412. * @returns {number} Returns the index of the matched value, else `-1`.
  23413. */
  23414. function strictIndexOf(array, value, fromIndex) {
  23415. var index = fromIndex - 1,
  23416. length = array.length;
  23417. while (++index < length) {
  23418. if (array[index] === value) {
  23419. return index;
  23420. }
  23421. }
  23422. return -1;
  23423. }
  23424. /**
  23425. * A specialized version of `_.lastIndexOf` which performs strict equality
  23426. * comparisons of values, i.e. `===`.
  23427. *
  23428. * @private
  23429. * @param {Array} array The array to inspect.
  23430. * @param {*} value The value to search for.
  23431. * @param {number} fromIndex The index to search from.
  23432. * @returns {number} Returns the index of the matched value, else `-1`.
  23433. */
  23434. function strictLastIndexOf(array, value, fromIndex) {
  23435. var index = fromIndex + 1;
  23436. while (index--) {
  23437. if (array[index] === value) {
  23438. return index;
  23439. }
  23440. }
  23441. return index;
  23442. }
  23443. /**
  23444. * Gets the number of symbols in `string`.
  23445. *
  23446. * @private
  23447. * @param {string} string The string to inspect.
  23448. * @returns {number} Returns the string size.
  23449. */
  23450. function stringSize(string) {
  23451. return hasUnicode(string)
  23452. ? unicodeSize(string)
  23453. : asciiSize(string);
  23454. }
  23455. /**
  23456. * Converts `string` to an array.
  23457. *
  23458. * @private
  23459. * @param {string} string The string to convert.
  23460. * @returns {Array} Returns the converted array.
  23461. */
  23462. function stringToArray(string) {
  23463. return hasUnicode(string)
  23464. ? unicodeToArray(string)
  23465. : asciiToArray(string);
  23466. }
  23467. /**
  23468. * Used by `_.unescape` to convert HTML entities to characters.
  23469. *
  23470. * @private
  23471. * @param {string} chr The matched character to unescape.
  23472. * @returns {string} Returns the unescaped character.
  23473. */
  23474. var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
  23475. /**
  23476. * Gets the size of a Unicode `string`.
  23477. *
  23478. * @private
  23479. * @param {string} string The string inspect.
  23480. * @returns {number} Returns the string size.
  23481. */
  23482. function unicodeSize(string) {
  23483. var result = reUnicode.lastIndex = 0;
  23484. while (reUnicode.test(string)) {
  23485. ++result;
  23486. }
  23487. return result;
  23488. }
  23489. /**
  23490. * Converts a Unicode `string` to an array.
  23491. *
  23492. * @private
  23493. * @param {string} string The string to convert.
  23494. * @returns {Array} Returns the converted array.
  23495. */
  23496. function unicodeToArray(string) {
  23497. return string.match(reUnicode) || [];
  23498. }
  23499. /**
  23500. * Splits a Unicode `string` into an array of its words.
  23501. *
  23502. * @private
  23503. * @param {string} The string to inspect.
  23504. * @returns {Array} Returns the words of `string`.
  23505. */
  23506. function unicodeWords(string) {
  23507. return string.match(reUnicodeWord) || [];
  23508. }
  23509. /*--------------------------------------------------------------------------*/
  23510. /**
  23511. * Create a new pristine `lodash` function using the `context` object.
  23512. *
  23513. * @static
  23514. * @memberOf _
  23515. * @since 1.1.0
  23516. * @category Util
  23517. * @param {Object} [context=root] The context object.
  23518. * @returns {Function} Returns a new `lodash` function.
  23519. * @example
  23520. *
  23521. * _.mixin({ 'foo': _.constant('foo') });
  23522. *
  23523. * var lodash = _.runInContext();
  23524. * lodash.mixin({ 'bar': lodash.constant('bar') });
  23525. *
  23526. * _.isFunction(_.foo);
  23527. * // => true
  23528. * _.isFunction(_.bar);
  23529. * // => false
  23530. *
  23531. * lodash.isFunction(lodash.foo);
  23532. * // => false
  23533. * lodash.isFunction(lodash.bar);
  23534. * // => true
  23535. *
  23536. * // Create a suped-up `defer` in Node.js.
  23537. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
  23538. */
  23539. var runInContext = (function runInContext(context) {
  23540. context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));
  23541. /** Built-in constructor references. */
  23542. var Array = context.Array,
  23543. Date = context.Date,
  23544. Error = context.Error,
  23545. Function = context.Function,
  23546. Math = context.Math,
  23547. Object = context.Object,
  23548. RegExp = context.RegExp,
  23549. String = context.String,
  23550. TypeError = context.TypeError;
  23551. /** Used for built-in method references. */
  23552. var arrayProto = Array.prototype,
  23553. funcProto = Function.prototype,
  23554. objectProto = Object.prototype;
  23555. /** Used to detect overreaching core-js shims. */
  23556. var coreJsData = context['__core-js_shared__'];
  23557. /** Used to resolve the decompiled source of functions. */
  23558. var funcToString = funcProto.toString;
  23559. /** Used to check objects for own properties. */
  23560. var hasOwnProperty = objectProto.hasOwnProperty;
  23561. /** Used to generate unique IDs. */
  23562. var idCounter = 0;
  23563. /** Used to detect methods masquerading as native. */
  23564. var maskSrcKey = (function() {
  23565. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  23566. return uid ? ('Symbol(src)_1.' + uid) : '';
  23567. }());
  23568. /**
  23569. * Used to resolve the
  23570. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  23571. * of values.
  23572. */
  23573. var nativeObjectToString = objectProto.toString;
  23574. /** Used to infer the `Object` constructor. */
  23575. var objectCtorString = funcToString.call(Object);
  23576. /** Used to restore the original `_` reference in `_.noConflict`. */
  23577. var oldDash = root._;
  23578. /** Used to detect if a method is native. */
  23579. var reIsNative = RegExp('^' +
  23580. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  23581. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  23582. );
  23583. /** Built-in value references. */
  23584. var Buffer = moduleExports ? context.Buffer : undefined,
  23585. Symbol = context.Symbol,
  23586. Uint8Array = context.Uint8Array,
  23587. allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
  23588. getPrototype = overArg(Object.getPrototypeOf, Object),
  23589. objectCreate = Object.create,
  23590. propertyIsEnumerable = objectProto.propertyIsEnumerable,
  23591. splice = arrayProto.splice,
  23592. spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,
  23593. symIterator = Symbol ? Symbol.iterator : undefined,
  23594. symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  23595. var defineProperty = (function() {
  23596. try {
  23597. var func = getNative(Object, 'defineProperty');
  23598. func({}, '', {});
  23599. return func;
  23600. } catch (e) {}
  23601. }());
  23602. /** Mocked built-ins. */
  23603. var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
  23604. ctxNow = Date && Date.now !== root.Date.now && Date.now,
  23605. ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
  23606. /* Built-in method references for those with the same name as other `lodash` methods. */
  23607. var nativeCeil = Math.ceil,
  23608. nativeFloor = Math.floor,
  23609. nativeGetSymbols = Object.getOwnPropertySymbols,
  23610. nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
  23611. nativeIsFinite = context.isFinite,
  23612. nativeJoin = arrayProto.join,
  23613. nativeKeys = overArg(Object.keys, Object),
  23614. nativeMax = Math.max,
  23615. nativeMin = Math.min,
  23616. nativeNow = Date.now,
  23617. nativeParseInt = context.parseInt,
  23618. nativeRandom = Math.random,
  23619. nativeReverse = arrayProto.reverse;
  23620. /* Built-in method references that are verified to be native. */
  23621. var DataView = getNative(context, 'DataView'),
  23622. Map = getNative(context, 'Map'),
  23623. Promise = getNative(context, 'Promise'),
  23624. Set = getNative(context, 'Set'),
  23625. WeakMap = getNative(context, 'WeakMap'),
  23626. nativeCreate = getNative(Object, 'create');
  23627. /** Used to store function metadata. */
  23628. var metaMap = WeakMap && new WeakMap;
  23629. /** Used to lookup unminified function names. */
  23630. var realNames = {};
  23631. /** Used to detect maps, sets, and weakmaps. */
  23632. var dataViewCtorString = toSource(DataView),
  23633. mapCtorString = toSource(Map),
  23634. promiseCtorString = toSource(Promise),
  23635. setCtorString = toSource(Set),
  23636. weakMapCtorString = toSource(WeakMap);
  23637. /** Used to convert symbols to primitives and strings. */
  23638. var symbolProto = Symbol ? Symbol.prototype : undefined,
  23639. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
  23640. symbolToString = symbolProto ? symbolProto.toString : undefined;
  23641. /*------------------------------------------------------------------------*/
  23642. /**
  23643. * Creates a `lodash` object which wraps `value` to enable implicit method
  23644. * chain sequences. Methods that operate on and return arrays, collections,
  23645. * and functions can be chained together. Methods that retrieve a single value
  23646. * or may return a primitive value will automatically end the chain sequence
  23647. * and return the unwrapped value. Otherwise, the value must be unwrapped
  23648. * with `_#value`.
  23649. *
  23650. * Explicit chain sequences, which must be unwrapped with `_#value`, may be
  23651. * enabled using `_.chain`.
  23652. *
  23653. * The execution of chained methods is lazy, that is, it's deferred until
  23654. * `_#value` is implicitly or explicitly called.
  23655. *
  23656. * Lazy evaluation allows several methods to support shortcut fusion.
  23657. * Shortcut fusion is an optimization to merge iteratee calls; this avoids
  23658. * the creation of intermediate arrays and can greatly reduce the number of
  23659. * iteratee executions. Sections of a chain sequence qualify for shortcut
  23660. * fusion if the section is applied to an array and iteratees accept only
  23661. * one argument. The heuristic for whether a section qualifies for shortcut
  23662. * fusion is subject to change.
  23663. *
  23664. * Chaining is supported in custom builds as long as the `_#value` method is
  23665. * directly or indirectly included in the build.
  23666. *
  23667. * In addition to lodash methods, wrappers have `Array` and `String` methods.
  23668. *
  23669. * The wrapper `Array` methods are:
  23670. * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
  23671. *
  23672. * The wrapper `String` methods are:
  23673. * `replace` and `split`
  23674. *
  23675. * The wrapper methods that support shortcut fusion are:
  23676. * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
  23677. * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
  23678. * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
  23679. *
  23680. * The chainable wrapper methods are:
  23681. * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
  23682. * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
  23683. * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
  23684. * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
  23685. * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
  23686. * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
  23687. * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
  23688. * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
  23689. * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
  23690. * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
  23691. * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
  23692. * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
  23693. * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
  23694. * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
  23695. * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
  23696. * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
  23697. * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
  23698. * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
  23699. * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
  23700. * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
  23701. * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
  23702. * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
  23703. * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
  23704. * `zipObject`, `zipObjectDeep`, and `zipWith`
  23705. *
  23706. * The wrapper methods that are **not** chainable by default are:
  23707. * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
  23708. * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
  23709. * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
  23710. * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
  23711. * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
  23712. * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
  23713. * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
  23714. * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
  23715. * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
  23716. * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
  23717. * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
  23718. * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
  23719. * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
  23720. * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
  23721. * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
  23722. * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
  23723. * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
  23724. * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
  23725. * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
  23726. * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
  23727. * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
  23728. * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
  23729. * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
  23730. * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
  23731. * `upperFirst`, `value`, and `words`
  23732. *
  23733. * @name _
  23734. * @constructor
  23735. * @category Seq
  23736. * @param {*} value The value to wrap in a `lodash` instance.
  23737. * @returns {Object} Returns the new `lodash` wrapper instance.
  23738. * @example
  23739. *
  23740. * function square(n) {
  23741. * return n * n;
  23742. * }
  23743. *
  23744. * var wrapped = _([1, 2, 3]);
  23745. *
  23746. * // Returns an unwrapped value.
  23747. * wrapped.reduce(_.add);
  23748. * // => 6
  23749. *
  23750. * // Returns a wrapped value.
  23751. * var squares = wrapped.map(square);
  23752. *
  23753. * _.isArray(squares);
  23754. * // => false
  23755. *
  23756. * _.isArray(squares.value());
  23757. * // => true
  23758. */
  23759. function lodash(value) {
  23760. if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
  23761. if (value instanceof LodashWrapper) {
  23762. return value;
  23763. }
  23764. if (hasOwnProperty.call(value, '__wrapped__')) {
  23765. return wrapperClone(value);
  23766. }
  23767. }
  23768. return new LodashWrapper(value);
  23769. }
  23770. /**
  23771. * The base implementation of `_.create` without support for assigning
  23772. * properties to the created object.
  23773. *
  23774. * @private
  23775. * @param {Object} proto The object to inherit from.
  23776. * @returns {Object} Returns the new object.
  23777. */
  23778. var baseCreate = (function() {
  23779. function object() {}
  23780. return function(proto) {
  23781. if (!isObject(proto)) {
  23782. return {};
  23783. }
  23784. if (objectCreate) {
  23785. return objectCreate(proto);
  23786. }
  23787. object.prototype = proto;
  23788. var result = new object;
  23789. object.prototype = undefined;
  23790. return result;
  23791. };
  23792. }());
  23793. /**
  23794. * The function whose prototype chain sequence wrappers inherit from.
  23795. *
  23796. * @private
  23797. */
  23798. function baseLodash() {
  23799. // No operation performed.
  23800. }
  23801. /**
  23802. * The base constructor for creating `lodash` wrapper objects.
  23803. *
  23804. * @private
  23805. * @param {*} value The value to wrap.
  23806. * @param {boolean} [chainAll] Enable explicit method chain sequences.
  23807. */
  23808. function LodashWrapper(value, chainAll) {
  23809. this.__wrapped__ = value;
  23810. this.__actions__ = [];
  23811. this.__chain__ = !!chainAll;
  23812. this.__index__ = 0;
  23813. this.__values__ = undefined;
  23814. }
  23815. /**
  23816. * By default, the template delimiters used by lodash are like those in
  23817. * embedded Ruby (ERB) as well as ES2015 template strings. Change the
  23818. * following template settings to use alternative delimiters.
  23819. *
  23820. * @static
  23821. * @memberOf _
  23822. * @type {Object}
  23823. */
  23824. lodash.templateSettings = {
  23825. /**
  23826. * Used to detect `data` property values to be HTML-escaped.
  23827. *
  23828. * @memberOf _.templateSettings
  23829. * @type {RegExp}
  23830. */
  23831. 'escape': reEscape,
  23832. /**
  23833. * Used to detect code to be evaluated.
  23834. *
  23835. * @memberOf _.templateSettings
  23836. * @type {RegExp}
  23837. */
  23838. 'evaluate': reEvaluate,
  23839. /**
  23840. * Used to detect `data` property values to inject.
  23841. *
  23842. * @memberOf _.templateSettings
  23843. * @type {RegExp}
  23844. */
  23845. 'interpolate': reInterpolate,
  23846. /**
  23847. * Used to reference the data object in the template text.
  23848. *
  23849. * @memberOf _.templateSettings
  23850. * @type {string}
  23851. */
  23852. 'variable': '',
  23853. /**
  23854. * Used to import variables into the compiled template.
  23855. *
  23856. * @memberOf _.templateSettings
  23857. * @type {Object}
  23858. */
  23859. 'imports': {
  23860. /**
  23861. * A reference to the `lodash` function.
  23862. *
  23863. * @memberOf _.templateSettings.imports
  23864. * @type {Function}
  23865. */
  23866. '_': lodash
  23867. }
  23868. };
  23869. // Ensure wrappers are instances of `baseLodash`.
  23870. lodash.prototype = baseLodash.prototype;
  23871. lodash.prototype.constructor = lodash;
  23872. LodashWrapper.prototype = baseCreate(baseLodash.prototype);
  23873. LodashWrapper.prototype.constructor = LodashWrapper;
  23874. /*------------------------------------------------------------------------*/
  23875. /**
  23876. * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
  23877. *
  23878. * @private
  23879. * @constructor
  23880. * @param {*} value The value to wrap.
  23881. */
  23882. function LazyWrapper(value) {
  23883. this.__wrapped__ = value;
  23884. this.__actions__ = [];
  23885. this.__dir__ = 1;
  23886. this.__filtered__ = false;
  23887. this.__iteratees__ = [];
  23888. this.__takeCount__ = MAX_ARRAY_LENGTH;
  23889. this.__views__ = [];
  23890. }
  23891. /**
  23892. * Creates a clone of the lazy wrapper object.
  23893. *
  23894. * @private
  23895. * @name clone
  23896. * @memberOf LazyWrapper
  23897. * @returns {Object} Returns the cloned `LazyWrapper` object.
  23898. */
  23899. function lazyClone() {
  23900. var result = new LazyWrapper(this.__wrapped__);
  23901. result.__actions__ = copyArray(this.__actions__);
  23902. result.__dir__ = this.__dir__;
  23903. result.__filtered__ = this.__filtered__;
  23904. result.__iteratees__ = copyArray(this.__iteratees__);
  23905. result.__takeCount__ = this.__takeCount__;
  23906. result.__views__ = copyArray(this.__views__);
  23907. return result;
  23908. }
  23909. /**
  23910. * Reverses the direction of lazy iteration.
  23911. *
  23912. * @private
  23913. * @name reverse
  23914. * @memberOf LazyWrapper
  23915. * @returns {Object} Returns the new reversed `LazyWrapper` object.
  23916. */
  23917. function lazyReverse() {
  23918. if (this.__filtered__) {
  23919. var result = new LazyWrapper(this);
  23920. result.__dir__ = -1;
  23921. result.__filtered__ = true;
  23922. } else {
  23923. result = this.clone();
  23924. result.__dir__ *= -1;
  23925. }
  23926. return result;
  23927. }
  23928. /**
  23929. * Extracts the unwrapped value from its lazy wrapper.
  23930. *
  23931. * @private
  23932. * @name value
  23933. * @memberOf LazyWrapper
  23934. * @returns {*} Returns the unwrapped value.
  23935. */
  23936. function lazyValue() {
  23937. var array = this.__wrapped__.value(),
  23938. dir = this.__dir__,
  23939. isArr = isArray(array),
  23940. isRight = dir < 0,
  23941. arrLength = isArr ? array.length : 0,
  23942. view = getView(0, arrLength, this.__views__),
  23943. start = view.start,
  23944. end = view.end,
  23945. length = end - start,
  23946. index = isRight ? end : (start - 1),
  23947. iteratees = this.__iteratees__,
  23948. iterLength = iteratees.length,
  23949. resIndex = 0,
  23950. takeCount = nativeMin(length, this.__takeCount__);
  23951. if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
  23952. return baseWrapperValue(array, this.__actions__);
  23953. }
  23954. var result = [];
  23955. outer:
  23956. while (length-- && resIndex < takeCount) {
  23957. index += dir;
  23958. var iterIndex = -1,
  23959. value = array[index];
  23960. while (++iterIndex < iterLength) {
  23961. var data = iteratees[iterIndex],
  23962. iteratee = data.iteratee,
  23963. type = data.type,
  23964. computed = iteratee(value);
  23965. if (type == LAZY_MAP_FLAG) {
  23966. value = computed;
  23967. } else if (!computed) {
  23968. if (type == LAZY_FILTER_FLAG) {
  23969. continue outer;
  23970. } else {
  23971. break outer;
  23972. }
  23973. }
  23974. }
  23975. result[resIndex++] = value;
  23976. }
  23977. return result;
  23978. }
  23979. // Ensure `LazyWrapper` is an instance of `baseLodash`.
  23980. LazyWrapper.prototype = baseCreate(baseLodash.prototype);
  23981. LazyWrapper.prototype.constructor = LazyWrapper;
  23982. /*------------------------------------------------------------------------*/
  23983. /**
  23984. * Creates a hash object.
  23985. *
  23986. * @private
  23987. * @constructor
  23988. * @param {Array} [entries] The key-value pairs to cache.
  23989. */
  23990. function Hash(entries) {
  23991. var index = -1,
  23992. length = entries == null ? 0 : entries.length;
  23993. this.clear();
  23994. while (++index < length) {
  23995. var entry = entries[index];
  23996. this.set(entry[0], entry[1]);
  23997. }
  23998. }
  23999. /**
  24000. * Removes all key-value entries from the hash.
  24001. *
  24002. * @private
  24003. * @name clear
  24004. * @memberOf Hash
  24005. */
  24006. function hashClear() {
  24007. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  24008. this.size = 0;
  24009. }
  24010. /**
  24011. * Removes `key` and its value from the hash.
  24012. *
  24013. * @private
  24014. * @name delete
  24015. * @memberOf Hash
  24016. * @param {Object} hash The hash to modify.
  24017. * @param {string} key The key of the value to remove.
  24018. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  24019. */
  24020. function hashDelete(key) {
  24021. var result = this.has(key) && delete this.__data__[key];
  24022. this.size -= result ? 1 : 0;
  24023. return result;
  24024. }
  24025. /**
  24026. * Gets the hash value for `key`.
  24027. *
  24028. * @private
  24029. * @name get
  24030. * @memberOf Hash
  24031. * @param {string} key The key of the value to get.
  24032. * @returns {*} Returns the entry value.
  24033. */
  24034. function hashGet(key) {
  24035. var data = this.__data__;
  24036. if (nativeCreate) {
  24037. var result = data[key];
  24038. return result === HASH_UNDEFINED ? undefined : result;
  24039. }
  24040. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  24041. }
  24042. /**
  24043. * Checks if a hash value for `key` exists.
  24044. *
  24045. * @private
  24046. * @name has
  24047. * @memberOf Hash
  24048. * @param {string} key The key of the entry to check.
  24049. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  24050. */
  24051. function hashHas(key) {
  24052. var data = this.__data__;
  24053. return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
  24054. }
  24055. /**
  24056. * Sets the hash `key` to `value`.
  24057. *
  24058. * @private
  24059. * @name set
  24060. * @memberOf Hash
  24061. * @param {string} key The key of the value to set.
  24062. * @param {*} value The value to set.
  24063. * @returns {Object} Returns the hash instance.
  24064. */
  24065. function hashSet(key, value) {
  24066. var data = this.__data__;
  24067. this.size += this.has(key) ? 0 : 1;
  24068. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  24069. return this;
  24070. }
  24071. // Add methods to `Hash`.
  24072. Hash.prototype.clear = hashClear;
  24073. Hash.prototype['delete'] = hashDelete;
  24074. Hash.prototype.get = hashGet;
  24075. Hash.prototype.has = hashHas;
  24076. Hash.prototype.set = hashSet;
  24077. /*------------------------------------------------------------------------*/
  24078. /**
  24079. * Creates an list cache object.
  24080. *
  24081. * @private
  24082. * @constructor
  24083. * @param {Array} [entries] The key-value pairs to cache.
  24084. */
  24085. function ListCache(entries) {
  24086. var index = -1,
  24087. length = entries == null ? 0 : entries.length;
  24088. this.clear();
  24089. while (++index < length) {
  24090. var entry = entries[index];
  24091. this.set(entry[0], entry[1]);
  24092. }
  24093. }
  24094. /**
  24095. * Removes all key-value entries from the list cache.
  24096. *
  24097. * @private
  24098. * @name clear
  24099. * @memberOf ListCache
  24100. */
  24101. function listCacheClear() {
  24102. this.__data__ = [];
  24103. this.size = 0;
  24104. }
  24105. /**
  24106. * Removes `key` and its value from the list cache.
  24107. *
  24108. * @private
  24109. * @name delete
  24110. * @memberOf ListCache
  24111. * @param {string} key The key of the value to remove.
  24112. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  24113. */
  24114. function listCacheDelete(key) {
  24115. var data = this.__data__,
  24116. index = assocIndexOf(data, key);
  24117. if (index < 0) {
  24118. return false;
  24119. }
  24120. var lastIndex = data.length - 1;
  24121. if (index == lastIndex) {
  24122. data.pop();
  24123. } else {
  24124. splice.call(data, index, 1);
  24125. }
  24126. --this.size;
  24127. return true;
  24128. }
  24129. /**
  24130. * Gets the list cache value for `key`.
  24131. *
  24132. * @private
  24133. * @name get
  24134. * @memberOf ListCache
  24135. * @param {string} key The key of the value to get.
  24136. * @returns {*} Returns the entry value.
  24137. */
  24138. function listCacheGet(key) {
  24139. var data = this.__data__,
  24140. index = assocIndexOf(data, key);
  24141. return index < 0 ? undefined : data[index][1];
  24142. }
  24143. /**
  24144. * Checks if a list cache value for `key` exists.
  24145. *
  24146. * @private
  24147. * @name has
  24148. * @memberOf ListCache
  24149. * @param {string} key The key of the entry to check.
  24150. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  24151. */
  24152. function listCacheHas(key) {
  24153. return assocIndexOf(this.__data__, key) > -1;
  24154. }
  24155. /**
  24156. * Sets the list cache `key` to `value`.
  24157. *
  24158. * @private
  24159. * @name set
  24160. * @memberOf ListCache
  24161. * @param {string} key The key of the value to set.
  24162. * @param {*} value The value to set.
  24163. * @returns {Object} Returns the list cache instance.
  24164. */
  24165. function listCacheSet(key, value) {
  24166. var data = this.__data__,
  24167. index = assocIndexOf(data, key);
  24168. if (index < 0) {
  24169. ++this.size;
  24170. data.push([key, value]);
  24171. } else {
  24172. data[index][1] = value;
  24173. }
  24174. return this;
  24175. }
  24176. // Add methods to `ListCache`.
  24177. ListCache.prototype.clear = listCacheClear;
  24178. ListCache.prototype['delete'] = listCacheDelete;
  24179. ListCache.prototype.get = listCacheGet;
  24180. ListCache.prototype.has = listCacheHas;
  24181. ListCache.prototype.set = listCacheSet;
  24182. /*------------------------------------------------------------------------*/
  24183. /**
  24184. * Creates a map cache object to store key-value pairs.
  24185. *
  24186. * @private
  24187. * @constructor
  24188. * @param {Array} [entries] The key-value pairs to cache.
  24189. */
  24190. function MapCache(entries) {
  24191. var index = -1,
  24192. length = entries == null ? 0 : entries.length;
  24193. this.clear();
  24194. while (++index < length) {
  24195. var entry = entries[index];
  24196. this.set(entry[0], entry[1]);
  24197. }
  24198. }
  24199. /**
  24200. * Removes all key-value entries from the map.
  24201. *
  24202. * @private
  24203. * @name clear
  24204. * @memberOf MapCache
  24205. */
  24206. function mapCacheClear() {
  24207. this.size = 0;
  24208. this.__data__ = {
  24209. 'hash': new Hash,
  24210. 'map': new (Map || ListCache),
  24211. 'string': new Hash
  24212. };
  24213. }
  24214. /**
  24215. * Removes `key` and its value from the map.
  24216. *
  24217. * @private
  24218. * @name delete
  24219. * @memberOf MapCache
  24220. * @param {string} key The key of the value to remove.
  24221. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  24222. */
  24223. function mapCacheDelete(key) {
  24224. var result = getMapData(this, key)['delete'](key);
  24225. this.size -= result ? 1 : 0;
  24226. return result;
  24227. }
  24228. /**
  24229. * Gets the map value for `key`.
  24230. *
  24231. * @private
  24232. * @name get
  24233. * @memberOf MapCache
  24234. * @param {string} key The key of the value to get.
  24235. * @returns {*} Returns the entry value.
  24236. */
  24237. function mapCacheGet(key) {
  24238. return getMapData(this, key).get(key);
  24239. }
  24240. /**
  24241. * Checks if a map value for `key` exists.
  24242. *
  24243. * @private
  24244. * @name has
  24245. * @memberOf MapCache
  24246. * @param {string} key The key of the entry to check.
  24247. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  24248. */
  24249. function mapCacheHas(key) {
  24250. return getMapData(this, key).has(key);
  24251. }
  24252. /**
  24253. * Sets the map `key` to `value`.
  24254. *
  24255. * @private
  24256. * @name set
  24257. * @memberOf MapCache
  24258. * @param {string} key The key of the value to set.
  24259. * @param {*} value The value to set.
  24260. * @returns {Object} Returns the map cache instance.
  24261. */
  24262. function mapCacheSet(key, value) {
  24263. var data = getMapData(this, key),
  24264. size = data.size;
  24265. data.set(key, value);
  24266. this.size += data.size == size ? 0 : 1;
  24267. return this;
  24268. }
  24269. // Add methods to `MapCache`.
  24270. MapCache.prototype.clear = mapCacheClear;
  24271. MapCache.prototype['delete'] = mapCacheDelete;
  24272. MapCache.prototype.get = mapCacheGet;
  24273. MapCache.prototype.has = mapCacheHas;
  24274. MapCache.prototype.set = mapCacheSet;
  24275. /*------------------------------------------------------------------------*/
  24276. /**
  24277. *
  24278. * Creates an array cache object to store unique values.
  24279. *
  24280. * @private
  24281. * @constructor
  24282. * @param {Array} [values] The values to cache.
  24283. */
  24284. function SetCache(values) {
  24285. var index = -1,
  24286. length = values == null ? 0 : values.length;
  24287. this.__data__ = new MapCache;
  24288. while (++index < length) {
  24289. this.add(values[index]);
  24290. }
  24291. }
  24292. /**
  24293. * Adds `value` to the array cache.
  24294. *
  24295. * @private
  24296. * @name add
  24297. * @memberOf SetCache
  24298. * @alias push
  24299. * @param {*} value The value to cache.
  24300. * @returns {Object} Returns the cache instance.
  24301. */
  24302. function setCacheAdd(value) {
  24303. this.__data__.set(value, HASH_UNDEFINED);
  24304. return this;
  24305. }
  24306. /**
  24307. * Checks if `value` is in the array cache.
  24308. *
  24309. * @private
  24310. * @name has
  24311. * @memberOf SetCache
  24312. * @param {*} value The value to search for.
  24313. * @returns {number} Returns `true` if `value` is found, else `false`.
  24314. */
  24315. function setCacheHas(value) {
  24316. return this.__data__.has(value);
  24317. }
  24318. // Add methods to `SetCache`.
  24319. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
  24320. SetCache.prototype.has = setCacheHas;
  24321. /*------------------------------------------------------------------------*/
  24322. /**
  24323. * Creates a stack cache object to store key-value pairs.
  24324. *
  24325. * @private
  24326. * @constructor
  24327. * @param {Array} [entries] The key-value pairs to cache.
  24328. */
  24329. function Stack(entries) {
  24330. var data = this.__data__ = new ListCache(entries);
  24331. this.size = data.size;
  24332. }
  24333. /**
  24334. * Removes all key-value entries from the stack.
  24335. *
  24336. * @private
  24337. * @name clear
  24338. * @memberOf Stack
  24339. */
  24340. function stackClear() {
  24341. this.__data__ = new ListCache;
  24342. this.size = 0;
  24343. }
  24344. /**
  24345. * Removes `key` and its value from the stack.
  24346. *
  24347. * @private
  24348. * @name delete
  24349. * @memberOf Stack
  24350. * @param {string} key The key of the value to remove.
  24351. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  24352. */
  24353. function stackDelete(key) {
  24354. var data = this.__data__,
  24355. result = data['delete'](key);
  24356. this.size = data.size;
  24357. return result;
  24358. }
  24359. /**
  24360. * Gets the stack value for `key`.
  24361. *
  24362. * @private
  24363. * @name get
  24364. * @memberOf Stack
  24365. * @param {string} key The key of the value to get.
  24366. * @returns {*} Returns the entry value.
  24367. */
  24368. function stackGet(key) {
  24369. return this.__data__.get(key);
  24370. }
  24371. /**
  24372. * Checks if a stack value for `key` exists.
  24373. *
  24374. * @private
  24375. * @name has
  24376. * @memberOf Stack
  24377. * @param {string} key The key of the entry to check.
  24378. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  24379. */
  24380. function stackHas(key) {
  24381. return this.__data__.has(key);
  24382. }
  24383. /**
  24384. * Sets the stack `key` to `value`.
  24385. *
  24386. * @private
  24387. * @name set
  24388. * @memberOf Stack
  24389. * @param {string} key The key of the value to set.
  24390. * @param {*} value The value to set.
  24391. * @returns {Object} Returns the stack cache instance.
  24392. */
  24393. function stackSet(key, value) {
  24394. var data = this.__data__;
  24395. if (data instanceof ListCache) {
  24396. var pairs = data.__data__;
  24397. if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  24398. pairs.push([key, value]);
  24399. this.size = ++data.size;
  24400. return this;
  24401. }
  24402. data = this.__data__ = new MapCache(pairs);
  24403. }
  24404. data.set(key, value);
  24405. this.size = data.size;
  24406. return this;
  24407. }
  24408. // Add methods to `Stack`.
  24409. Stack.prototype.clear = stackClear;
  24410. Stack.prototype['delete'] = stackDelete;
  24411. Stack.prototype.get = stackGet;
  24412. Stack.prototype.has = stackHas;
  24413. Stack.prototype.set = stackSet;
  24414. /*------------------------------------------------------------------------*/
  24415. /**
  24416. * Creates an array of the enumerable property names of the array-like `value`.
  24417. *
  24418. * @private
  24419. * @param {*} value The value to query.
  24420. * @param {boolean} inherited Specify returning inherited property names.
  24421. * @returns {Array} Returns the array of property names.
  24422. */
  24423. function arrayLikeKeys(value, inherited) {
  24424. var isArr = isArray(value),
  24425. isArg = !isArr && isArguments(value),
  24426. isBuff = !isArr && !isArg && isBuffer(value),
  24427. isType = !isArr && !isArg && !isBuff && isTypedArray(value),
  24428. skipIndexes = isArr || isArg || isBuff || isType,
  24429. result = skipIndexes ? baseTimes(value.length, String) : [],
  24430. length = result.length;
  24431. for (var key in value) {
  24432. if ((inherited || hasOwnProperty.call(value, key)) &&
  24433. !(skipIndexes && (
  24434. // Safari 9 has enumerable `arguments.length` in strict mode.
  24435. key == 'length' ||
  24436. // Node.js 0.10 has enumerable non-index properties on buffers.
  24437. (isBuff && (key == 'offset' || key == 'parent')) ||
  24438. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  24439. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  24440. // Skip index properties.
  24441. isIndex(key, length)
  24442. ))) {
  24443. result.push(key);
  24444. }
  24445. }
  24446. return result;
  24447. }
  24448. /**
  24449. * A specialized version of `_.sample` for arrays.
  24450. *
  24451. * @private
  24452. * @param {Array} array The array to sample.
  24453. * @returns {*} Returns the random element.
  24454. */
  24455. function arraySample(array) {
  24456. var length = array.length;
  24457. return length ? array[baseRandom(0, length - 1)] : undefined;
  24458. }
  24459. /**
  24460. * A specialized version of `_.sampleSize` for arrays.
  24461. *
  24462. * @private
  24463. * @param {Array} array The array to sample.
  24464. * @param {number} n The number of elements to sample.
  24465. * @returns {Array} Returns the random elements.
  24466. */
  24467. function arraySampleSize(array, n) {
  24468. return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
  24469. }
  24470. /**
  24471. * A specialized version of `_.shuffle` for arrays.
  24472. *
  24473. * @private
  24474. * @param {Array} array The array to shuffle.
  24475. * @returns {Array} Returns the new shuffled array.
  24476. */
  24477. function arrayShuffle(array) {
  24478. return shuffleSelf(copyArray(array));
  24479. }
  24480. /**
  24481. * This function is like `assignValue` except that it doesn't assign
  24482. * `undefined` values.
  24483. *
  24484. * @private
  24485. * @param {Object} object The object to modify.
  24486. * @param {string} key The key of the property to assign.
  24487. * @param {*} value The value to assign.
  24488. */
  24489. function assignMergeValue(object, key, value) {
  24490. if ((value !== undefined && !eq(object[key], value)) ||
  24491. (value === undefined && !(key in object))) {
  24492. baseAssignValue(object, key, value);
  24493. }
  24494. }
  24495. /**
  24496. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  24497. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  24498. * for equality comparisons.
  24499. *
  24500. * @private
  24501. * @param {Object} object The object to modify.
  24502. * @param {string} key The key of the property to assign.
  24503. * @param {*} value The value to assign.
  24504. */
  24505. function assignValue(object, key, value) {
  24506. var objValue = object[key];
  24507. if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
  24508. (value === undefined && !(key in object))) {
  24509. baseAssignValue(object, key, value);
  24510. }
  24511. }
  24512. /**
  24513. * Gets the index at which the `key` is found in `array` of key-value pairs.
  24514. *
  24515. * @private
  24516. * @param {Array} array The array to inspect.
  24517. * @param {*} key The key to search for.
  24518. * @returns {number} Returns the index of the matched value, else `-1`.
  24519. */
  24520. function assocIndexOf(array, key) {
  24521. var length = array.length;
  24522. while (length--) {
  24523. if (eq(array[length][0], key)) {
  24524. return length;
  24525. }
  24526. }
  24527. return -1;
  24528. }
  24529. /**
  24530. * Aggregates elements of `collection` on `accumulator` with keys transformed
  24531. * by `iteratee` and values set by `setter`.
  24532. *
  24533. * @private
  24534. * @param {Array|Object} collection The collection to iterate over.
  24535. * @param {Function} setter The function to set `accumulator` values.
  24536. * @param {Function} iteratee The iteratee to transform keys.
  24537. * @param {Object} accumulator The initial aggregated object.
  24538. * @returns {Function} Returns `accumulator`.
  24539. */
  24540. function baseAggregator(collection, setter, iteratee, accumulator) {
  24541. baseEach(collection, function(value, key, collection) {
  24542. setter(accumulator, value, iteratee(value), collection);
  24543. });
  24544. return accumulator;
  24545. }
  24546. /**
  24547. * The base implementation of `_.assign` without support for multiple sources
  24548. * or `customizer` functions.
  24549. *
  24550. * @private
  24551. * @param {Object} object The destination object.
  24552. * @param {Object} source The source object.
  24553. * @returns {Object} Returns `object`.
  24554. */
  24555. function baseAssign(object, source) {
  24556. return object && copyObject(source, keys(source), object);
  24557. }
  24558. /**
  24559. * The base implementation of `_.assignIn` without support for multiple sources
  24560. * or `customizer` functions.
  24561. *
  24562. * @private
  24563. * @param {Object} object The destination object.
  24564. * @param {Object} source The source object.
  24565. * @returns {Object} Returns `object`.
  24566. */
  24567. function baseAssignIn(object, source) {
  24568. return object && copyObject(source, keysIn(source), object);
  24569. }
  24570. /**
  24571. * The base implementation of `assignValue` and `assignMergeValue` without
  24572. * value checks.
  24573. *
  24574. * @private
  24575. * @param {Object} object The object to modify.
  24576. * @param {string} key The key of the property to assign.
  24577. * @param {*} value The value to assign.
  24578. */
  24579. function baseAssignValue(object, key, value) {
  24580. if (key == '__proto__' && defineProperty) {
  24581. defineProperty(object, key, {
  24582. 'configurable': true,
  24583. 'enumerable': true,
  24584. 'value': value,
  24585. 'writable': true
  24586. });
  24587. } else {
  24588. object[key] = value;
  24589. }
  24590. }
  24591. /**
  24592. * The base implementation of `_.at` without support for individual paths.
  24593. *
  24594. * @private
  24595. * @param {Object} object The object to iterate over.
  24596. * @param {string[]} paths The property paths to pick.
  24597. * @returns {Array} Returns the picked elements.
  24598. */
  24599. function baseAt(object, paths) {
  24600. var index = -1,
  24601. length = paths.length,
  24602. result = Array(length),
  24603. skip = object == null;
  24604. while (++index < length) {
  24605. result[index] = skip ? undefined : get(object, paths[index]);
  24606. }
  24607. return result;
  24608. }
  24609. /**
  24610. * The base implementation of `_.clamp` which doesn't coerce arguments.
  24611. *
  24612. * @private
  24613. * @param {number} number The number to clamp.
  24614. * @param {number} [lower] The lower bound.
  24615. * @param {number} upper The upper bound.
  24616. * @returns {number} Returns the clamped number.
  24617. */
  24618. function baseClamp(number, lower, upper) {
  24619. if (number === number) {
  24620. if (upper !== undefined) {
  24621. number = number <= upper ? number : upper;
  24622. }
  24623. if (lower !== undefined) {
  24624. number = number >= lower ? number : lower;
  24625. }
  24626. }
  24627. return number;
  24628. }
  24629. /**
  24630. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  24631. * traversed objects.
  24632. *
  24633. * @private
  24634. * @param {*} value The value to clone.
  24635. * @param {boolean} bitmask The bitmask flags.
  24636. * 1 - Deep clone
  24637. * 2 - Flatten inherited properties
  24638. * 4 - Clone symbols
  24639. * @param {Function} [customizer] The function to customize cloning.
  24640. * @param {string} [key] The key of `value`.
  24641. * @param {Object} [object] The parent object of `value`.
  24642. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  24643. * @returns {*} Returns the cloned value.
  24644. */
  24645. function baseClone(value, bitmask, customizer, key, object, stack) {
  24646. var result,
  24647. isDeep = bitmask & CLONE_DEEP_FLAG,
  24648. isFlat = bitmask & CLONE_FLAT_FLAG,
  24649. isFull = bitmask & CLONE_SYMBOLS_FLAG;
  24650. if (customizer) {
  24651. result = object ? customizer(value, key, object, stack) : customizer(value);
  24652. }
  24653. if (result !== undefined) {
  24654. return result;
  24655. }
  24656. if (!isObject(value)) {
  24657. return value;
  24658. }
  24659. var isArr = isArray(value);
  24660. if (isArr) {
  24661. result = initCloneArray(value);
  24662. if (!isDeep) {
  24663. return copyArray(value, result);
  24664. }
  24665. } else {
  24666. var tag = getTag(value),
  24667. isFunc = tag == funcTag || tag == genTag;
  24668. if (isBuffer(value)) {
  24669. return cloneBuffer(value, isDeep);
  24670. }
  24671. if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
  24672. result = (isFlat || isFunc) ? {} : initCloneObject(value);
  24673. if (!isDeep) {
  24674. return isFlat
  24675. ? copySymbolsIn(value, baseAssignIn(result, value))
  24676. : copySymbols(value, baseAssign(result, value));
  24677. }
  24678. } else {
  24679. if (!cloneableTags[tag]) {
  24680. return object ? value : {};
  24681. }
  24682. result = initCloneByTag(value, tag, baseClone, isDeep);
  24683. }
  24684. }
  24685. // Check for circular references and return its corresponding clone.
  24686. stack || (stack = new Stack);
  24687. var stacked = stack.get(value);
  24688. if (stacked) {
  24689. return stacked;
  24690. }
  24691. stack.set(value, result);
  24692. var keysFunc = isFull
  24693. ? (isFlat ? getAllKeysIn : getAllKeys)
  24694. : (isFlat ? keysIn : keys);
  24695. var props = isArr ? undefined : keysFunc(value);
  24696. arrayEach(props || value, function(subValue, key) {
  24697. if (props) {
  24698. key = subValue;
  24699. subValue = value[key];
  24700. }
  24701. // Recursively populate clone (susceptible to call stack limits).
  24702. assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  24703. });
  24704. return result;
  24705. }
  24706. /**
  24707. * The base implementation of `_.conforms` which doesn't clone `source`.
  24708. *
  24709. * @private
  24710. * @param {Object} source The object of property predicates to conform to.
  24711. * @returns {Function} Returns the new spec function.
  24712. */
  24713. function baseConforms(source) {
  24714. var props = keys(source);
  24715. return function(object) {
  24716. return baseConformsTo(object, source, props);
  24717. };
  24718. }
  24719. /**
  24720. * The base implementation of `_.conformsTo` which accepts `props` to check.
  24721. *
  24722. * @private
  24723. * @param {Object} object The object to inspect.
  24724. * @param {Object} source The object of property predicates to conform to.
  24725. * @returns {boolean} Returns `true` if `object` conforms, else `false`.
  24726. */
  24727. function baseConformsTo(object, source, props) {
  24728. var length = props.length;
  24729. if (object == null) {
  24730. return !length;
  24731. }
  24732. object = Object(object);
  24733. while (length--) {
  24734. var key = props[length],
  24735. predicate = source[key],
  24736. value = object[key];
  24737. if ((value === undefined && !(key in object)) || !predicate(value)) {
  24738. return false;
  24739. }
  24740. }
  24741. return true;
  24742. }
  24743. /**
  24744. * The base implementation of `_.delay` and `_.defer` which accepts `args`
  24745. * to provide to `func`.
  24746. *
  24747. * @private
  24748. * @param {Function} func The function to delay.
  24749. * @param {number} wait The number of milliseconds to delay invocation.
  24750. * @param {Array} args The arguments to provide to `func`.
  24751. * @returns {number|Object} Returns the timer id or timeout object.
  24752. */
  24753. function baseDelay(func, wait, args) {
  24754. if (typeof func != 'function') {
  24755. throw new TypeError(FUNC_ERROR_TEXT);
  24756. }
  24757. return setTimeout(function() { func.apply(undefined, args); }, wait);
  24758. }
  24759. /**
  24760. * The base implementation of methods like `_.difference` without support
  24761. * for excluding multiple arrays or iteratee shorthands.
  24762. *
  24763. * @private
  24764. * @param {Array} array The array to inspect.
  24765. * @param {Array} values The values to exclude.
  24766. * @param {Function} [iteratee] The iteratee invoked per element.
  24767. * @param {Function} [comparator] The comparator invoked per element.
  24768. * @returns {Array} Returns the new array of filtered values.
  24769. */
  24770. function baseDifference(array, values, iteratee, comparator) {
  24771. var index = -1,
  24772. includes = arrayIncludes,
  24773. isCommon = true,
  24774. length = array.length,
  24775. result = [],
  24776. valuesLength = values.length;
  24777. if (!length) {
  24778. return result;
  24779. }
  24780. if (iteratee) {
  24781. values = arrayMap(values, baseUnary(iteratee));
  24782. }
  24783. if (comparator) {
  24784. includes = arrayIncludesWith;
  24785. isCommon = false;
  24786. }
  24787. else if (values.length >= LARGE_ARRAY_SIZE) {
  24788. includes = cacheHas;
  24789. isCommon = false;
  24790. values = new SetCache(values);
  24791. }
  24792. outer:
  24793. while (++index < length) {
  24794. var value = array[index],
  24795. computed = iteratee == null ? value : iteratee(value);
  24796. value = (comparator || value !== 0) ? value : 0;
  24797. if (isCommon && computed === computed) {
  24798. var valuesIndex = valuesLength;
  24799. while (valuesIndex--) {
  24800. if (values[valuesIndex] === computed) {
  24801. continue outer;
  24802. }
  24803. }
  24804. result.push(value);
  24805. }
  24806. else if (!includes(values, computed, comparator)) {
  24807. result.push(value);
  24808. }
  24809. }
  24810. return result;
  24811. }
  24812. /**
  24813. * The base implementation of `_.forEach` without support for iteratee shorthands.
  24814. *
  24815. * @private
  24816. * @param {Array|Object} collection The collection to iterate over.
  24817. * @param {Function} iteratee The function invoked per iteration.
  24818. * @returns {Array|Object} Returns `collection`.
  24819. */
  24820. var baseEach = createBaseEach(baseForOwn);
  24821. /**
  24822. * The base implementation of `_.forEachRight` without support for iteratee shorthands.
  24823. *
  24824. * @private
  24825. * @param {Array|Object} collection The collection to iterate over.
  24826. * @param {Function} iteratee The function invoked per iteration.
  24827. * @returns {Array|Object} Returns `collection`.
  24828. */
  24829. var baseEachRight = createBaseEach(baseForOwnRight, true);
  24830. /**
  24831. * The base implementation of `_.every` without support for iteratee shorthands.
  24832. *
  24833. * @private
  24834. * @param {Array|Object} collection The collection to iterate over.
  24835. * @param {Function} predicate The function invoked per iteration.
  24836. * @returns {boolean} Returns `true` if all elements pass the predicate check,
  24837. * else `false`
  24838. */
  24839. function baseEvery(collection, predicate) {
  24840. var result = true;
  24841. baseEach(collection, function(value, index, collection) {
  24842. result = !!predicate(value, index, collection);
  24843. return result;
  24844. });
  24845. return result;
  24846. }
  24847. /**
  24848. * The base implementation of methods like `_.max` and `_.min` which accepts a
  24849. * `comparator` to determine the extremum value.
  24850. *
  24851. * @private
  24852. * @param {Array} array The array to iterate over.
  24853. * @param {Function} iteratee The iteratee invoked per iteration.
  24854. * @param {Function} comparator The comparator used to compare values.
  24855. * @returns {*} Returns the extremum value.
  24856. */
  24857. function baseExtremum(array, iteratee, comparator) {
  24858. var index = -1,
  24859. length = array.length;
  24860. while (++index < length) {
  24861. var value = array[index],
  24862. current = iteratee(value);
  24863. if (current != null && (computed === undefined
  24864. ? (current === current && !isSymbol(current))
  24865. : comparator(current, computed)
  24866. )) {
  24867. var computed = current,
  24868. result = value;
  24869. }
  24870. }
  24871. return result;
  24872. }
  24873. /**
  24874. * The base implementation of `_.fill` without an iteratee call guard.
  24875. *
  24876. * @private
  24877. * @param {Array} array The array to fill.
  24878. * @param {*} value The value to fill `array` with.
  24879. * @param {number} [start=0] The start position.
  24880. * @param {number} [end=array.length] The end position.
  24881. * @returns {Array} Returns `array`.
  24882. */
  24883. function baseFill(array, value, start, end) {
  24884. var length = array.length;
  24885. start = toInteger(start);
  24886. if (start < 0) {
  24887. start = -start > length ? 0 : (length + start);
  24888. }
  24889. end = (end === undefined || end > length) ? length : toInteger(end);
  24890. if (end < 0) {
  24891. end += length;
  24892. }
  24893. end = start > end ? 0 : toLength(end);
  24894. while (start < end) {
  24895. array[start++] = value;
  24896. }
  24897. return array;
  24898. }
  24899. /**
  24900. * The base implementation of `_.filter` without support for iteratee shorthands.
  24901. *
  24902. * @private
  24903. * @param {Array|Object} collection The collection to iterate over.
  24904. * @param {Function} predicate The function invoked per iteration.
  24905. * @returns {Array} Returns the new filtered array.
  24906. */
  24907. function baseFilter(collection, predicate) {
  24908. var result = [];
  24909. baseEach(collection, function(value, index, collection) {
  24910. if (predicate(value, index, collection)) {
  24911. result.push(value);
  24912. }
  24913. });
  24914. return result;
  24915. }
  24916. /**
  24917. * The base implementation of `_.flatten` with support for restricting flattening.
  24918. *
  24919. * @private
  24920. * @param {Array} array The array to flatten.
  24921. * @param {number} depth The maximum recursion depth.
  24922. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
  24923. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
  24924. * @param {Array} [result=[]] The initial result value.
  24925. * @returns {Array} Returns the new flattened array.
  24926. */
  24927. function baseFlatten(array, depth, predicate, isStrict, result) {
  24928. var index = -1,
  24929. length = array.length;
  24930. predicate || (predicate = isFlattenable);
  24931. result || (result = []);
  24932. while (++index < length) {
  24933. var value = array[index];
  24934. if (depth > 0 && predicate(value)) {
  24935. if (depth > 1) {
  24936. // Recursively flatten arrays (susceptible to call stack limits).
  24937. baseFlatten(value, depth - 1, predicate, isStrict, result);
  24938. } else {
  24939. arrayPush(result, value);
  24940. }
  24941. } else if (!isStrict) {
  24942. result[result.length] = value;
  24943. }
  24944. }
  24945. return result;
  24946. }
  24947. /**
  24948. * The base implementation of `baseForOwn` which iterates over `object`
  24949. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  24950. * Iteratee functions may exit iteration early by explicitly returning `false`.
  24951. *
  24952. * @private
  24953. * @param {Object} object The object to iterate over.
  24954. * @param {Function} iteratee The function invoked per iteration.
  24955. * @param {Function} keysFunc The function to get the keys of `object`.
  24956. * @returns {Object} Returns `object`.
  24957. */
  24958. var baseFor = createBaseFor();
  24959. /**
  24960. * This function is like `baseFor` except that it iterates over properties
  24961. * in the opposite order.
  24962. *
  24963. * @private
  24964. * @param {Object} object The object to iterate over.
  24965. * @param {Function} iteratee The function invoked per iteration.
  24966. * @param {Function} keysFunc The function to get the keys of `object`.
  24967. * @returns {Object} Returns `object`.
  24968. */
  24969. var baseForRight = createBaseFor(true);
  24970. /**
  24971. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  24972. *
  24973. * @private
  24974. * @param {Object} object The object to iterate over.
  24975. * @param {Function} iteratee The function invoked per iteration.
  24976. * @returns {Object} Returns `object`.
  24977. */
  24978. function baseForOwn(object, iteratee) {
  24979. return object && baseFor(object, iteratee, keys);
  24980. }
  24981. /**
  24982. * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
  24983. *
  24984. * @private
  24985. * @param {Object} object The object to iterate over.
  24986. * @param {Function} iteratee The function invoked per iteration.
  24987. * @returns {Object} Returns `object`.
  24988. */
  24989. function baseForOwnRight(object, iteratee) {
  24990. return object && baseForRight(object, iteratee, keys);
  24991. }
  24992. /**
  24993. * The base implementation of `_.functions` which creates an array of
  24994. * `object` function property names filtered from `props`.
  24995. *
  24996. * @private
  24997. * @param {Object} object The object to inspect.
  24998. * @param {Array} props The property names to filter.
  24999. * @returns {Array} Returns the function names.
  25000. */
  25001. function baseFunctions(object, props) {
  25002. return arrayFilter(props, function(key) {
  25003. return isFunction(object[key]);
  25004. });
  25005. }
  25006. /**
  25007. * The base implementation of `_.get` without support for default values.
  25008. *
  25009. * @private
  25010. * @param {Object} object The object to query.
  25011. * @param {Array|string} path The path of the property to get.
  25012. * @returns {*} Returns the resolved value.
  25013. */
  25014. function baseGet(object, path) {
  25015. path = castPath(path, object);
  25016. var index = 0,
  25017. length = path.length;
  25018. while (object != null && index < length) {
  25019. object = object[toKey(path[index++])];
  25020. }
  25021. return (index && index == length) ? object : undefined;
  25022. }
  25023. /**
  25024. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  25025. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  25026. * symbols of `object`.
  25027. *
  25028. * @private
  25029. * @param {Object} object The object to query.
  25030. * @param {Function} keysFunc The function to get the keys of `object`.
  25031. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  25032. * @returns {Array} Returns the array of property names and symbols.
  25033. */
  25034. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  25035. var result = keysFunc(object);
  25036. return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
  25037. }
  25038. /**
  25039. * The base implementation of `getTag` without fallbacks for buggy environments.
  25040. *
  25041. * @private
  25042. * @param {*} value The value to query.
  25043. * @returns {string} Returns the `toStringTag`.
  25044. */
  25045. function baseGetTag(value) {
  25046. if (value == null) {
  25047. return value === undefined ? undefinedTag : nullTag;
  25048. }
  25049. return (symToStringTag && symToStringTag in Object(value))
  25050. ? getRawTag(value)
  25051. : objectToString(value);
  25052. }
  25053. /**
  25054. * The base implementation of `_.gt` which doesn't coerce arguments.
  25055. *
  25056. * @private
  25057. * @param {*} value The value to compare.
  25058. * @param {*} other The other value to compare.
  25059. * @returns {boolean} Returns `true` if `value` is greater than `other`,
  25060. * else `false`.
  25061. */
  25062. function baseGt(value, other) {
  25063. return value > other;
  25064. }
  25065. /**
  25066. * The base implementation of `_.has` without support for deep paths.
  25067. *
  25068. * @private
  25069. * @param {Object} [object] The object to query.
  25070. * @param {Array|string} key The key to check.
  25071. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  25072. */
  25073. function baseHas(object, key) {
  25074. return object != null && hasOwnProperty.call(object, key);
  25075. }
  25076. /**
  25077. * The base implementation of `_.hasIn` without support for deep paths.
  25078. *
  25079. * @private
  25080. * @param {Object} [object] The object to query.
  25081. * @param {Array|string} key The key to check.
  25082. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  25083. */
  25084. function baseHasIn(object, key) {
  25085. return object != null && key in Object(object);
  25086. }
  25087. /**
  25088. * The base implementation of `_.inRange` which doesn't coerce arguments.
  25089. *
  25090. * @private
  25091. * @param {number} number The number to check.
  25092. * @param {number} start The start of the range.
  25093. * @param {number} end The end of the range.
  25094. * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
  25095. */
  25096. function baseInRange(number, start, end) {
  25097. return number >= nativeMin(start, end) && number < nativeMax(start, end);
  25098. }
  25099. /**
  25100. * The base implementation of methods like `_.intersection`, without support
  25101. * for iteratee shorthands, that accepts an array of arrays to inspect.
  25102. *
  25103. * @private
  25104. * @param {Array} arrays The arrays to inspect.
  25105. * @param {Function} [iteratee] The iteratee invoked per element.
  25106. * @param {Function} [comparator] The comparator invoked per element.
  25107. * @returns {Array} Returns the new array of shared values.
  25108. */
  25109. function baseIntersection(arrays, iteratee, comparator) {
  25110. var includes = comparator ? arrayIncludesWith : arrayIncludes,
  25111. length = arrays[0].length,
  25112. othLength = arrays.length,
  25113. othIndex = othLength,
  25114. caches = Array(othLength),
  25115. maxLength = Infinity,
  25116. result = [];
  25117. while (othIndex--) {
  25118. var array = arrays[othIndex];
  25119. if (othIndex && iteratee) {
  25120. array = arrayMap(array, baseUnary(iteratee));
  25121. }
  25122. maxLength = nativeMin(array.length, maxLength);
  25123. caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
  25124. ? new SetCache(othIndex && array)
  25125. : undefined;
  25126. }
  25127. array = arrays[0];
  25128. var index = -1,
  25129. seen = caches[0];
  25130. outer:
  25131. while (++index < length && result.length < maxLength) {
  25132. var value = array[index],
  25133. computed = iteratee ? iteratee(value) : value;
  25134. value = (comparator || value !== 0) ? value : 0;
  25135. if (!(seen
  25136. ? cacheHas(seen, computed)
  25137. : includes(result, computed, comparator)
  25138. )) {
  25139. othIndex = othLength;
  25140. while (--othIndex) {
  25141. var cache = caches[othIndex];
  25142. if (!(cache
  25143. ? cacheHas(cache, computed)
  25144. : includes(arrays[othIndex], computed, comparator))
  25145. ) {
  25146. continue outer;
  25147. }
  25148. }
  25149. if (seen) {
  25150. seen.push(computed);
  25151. }
  25152. result.push(value);
  25153. }
  25154. }
  25155. return result;
  25156. }
  25157. /**
  25158. * The base implementation of `_.invert` and `_.invertBy` which inverts
  25159. * `object` with values transformed by `iteratee` and set by `setter`.
  25160. *
  25161. * @private
  25162. * @param {Object} object The object to iterate over.
  25163. * @param {Function} setter The function to set `accumulator` values.
  25164. * @param {Function} iteratee The iteratee to transform values.
  25165. * @param {Object} accumulator The initial inverted object.
  25166. * @returns {Function} Returns `accumulator`.
  25167. */
  25168. function baseInverter(object, setter, iteratee, accumulator) {
  25169. baseForOwn(object, function(value, key, object) {
  25170. setter(accumulator, iteratee(value), key, object);
  25171. });
  25172. return accumulator;
  25173. }
  25174. /**
  25175. * The base implementation of `_.invoke` without support for individual
  25176. * method arguments.
  25177. *
  25178. * @private
  25179. * @param {Object} object The object to query.
  25180. * @param {Array|string} path The path of the method to invoke.
  25181. * @param {Array} args The arguments to invoke the method with.
  25182. * @returns {*} Returns the result of the invoked method.
  25183. */
  25184. function baseInvoke(object, path, args) {
  25185. path = castPath(path, object);
  25186. object = parent(object, path);
  25187. var func = object == null ? object : object[toKey(last(path))];
  25188. return func == null ? undefined : apply(func, object, args);
  25189. }
  25190. /**
  25191. * The base implementation of `_.isArguments`.
  25192. *
  25193. * @private
  25194. * @param {*} value The value to check.
  25195. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  25196. */
  25197. function baseIsArguments(value) {
  25198. return isObjectLike(value) && baseGetTag(value) == argsTag;
  25199. }
  25200. /**
  25201. * The base implementation of `_.isArrayBuffer` without Node.js optimizations.
  25202. *
  25203. * @private
  25204. * @param {*} value The value to check.
  25205. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
  25206. */
  25207. function baseIsArrayBuffer(value) {
  25208. return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
  25209. }
  25210. /**
  25211. * The base implementation of `_.isDate` without Node.js optimizations.
  25212. *
  25213. * @private
  25214. * @param {*} value The value to check.
  25215. * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
  25216. */
  25217. function baseIsDate(value) {
  25218. return isObjectLike(value) && baseGetTag(value) == dateTag;
  25219. }
  25220. /**
  25221. * The base implementation of `_.isEqual` which supports partial comparisons
  25222. * and tracks traversed objects.
  25223. *
  25224. * @private
  25225. * @param {*} value The value to compare.
  25226. * @param {*} other The other value to compare.
  25227. * @param {boolean} bitmask The bitmask flags.
  25228. * 1 - Unordered comparison
  25229. * 2 - Partial comparison
  25230. * @param {Function} [customizer] The function to customize comparisons.
  25231. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  25232. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  25233. */
  25234. function baseIsEqual(value, other, bitmask, customizer, stack) {
  25235. if (value === other) {
  25236. return true;
  25237. }
  25238. if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
  25239. return value !== value && other !== other;
  25240. }
  25241. return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  25242. }
  25243. /**
  25244. * A specialized version of `baseIsEqual` for arrays and objects which performs
  25245. * deep comparisons and tracks traversed objects enabling objects with circular
  25246. * references to be compared.
  25247. *
  25248. * @private
  25249. * @param {Object} object The object to compare.
  25250. * @param {Object} other The other object to compare.
  25251. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  25252. * @param {Function} customizer The function to customize comparisons.
  25253. * @param {Function} equalFunc The function to determine equivalents of values.
  25254. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  25255. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  25256. */
  25257. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  25258. var objIsArr = isArray(object),
  25259. othIsArr = isArray(other),
  25260. objTag = objIsArr ? arrayTag : getTag(object),
  25261. othTag = othIsArr ? arrayTag : getTag(other);
  25262. objTag = objTag == argsTag ? objectTag : objTag;
  25263. othTag = othTag == argsTag ? objectTag : othTag;
  25264. var objIsObj = objTag == objectTag,
  25265. othIsObj = othTag == objectTag,
  25266. isSameTag = objTag == othTag;
  25267. if (isSameTag && isBuffer(object)) {
  25268. if (!isBuffer(other)) {
  25269. return false;
  25270. }
  25271. objIsArr = true;
  25272. objIsObj = false;
  25273. }
  25274. if (isSameTag && !objIsObj) {
  25275. stack || (stack = new Stack);
  25276. return (objIsArr || isTypedArray(object))
  25277. ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
  25278. : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  25279. }
  25280. if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
  25281. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  25282. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  25283. if (objIsWrapped || othIsWrapped) {
  25284. var objUnwrapped = objIsWrapped ? object.value() : object,
  25285. othUnwrapped = othIsWrapped ? other.value() : other;
  25286. stack || (stack = new Stack);
  25287. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  25288. }
  25289. }
  25290. if (!isSameTag) {
  25291. return false;
  25292. }
  25293. stack || (stack = new Stack);
  25294. return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  25295. }
  25296. /**
  25297. * The base implementation of `_.isMap` without Node.js optimizations.
  25298. *
  25299. * @private
  25300. * @param {*} value The value to check.
  25301. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  25302. */
  25303. function baseIsMap(value) {
  25304. return isObjectLike(value) && getTag(value) == mapTag;
  25305. }
  25306. /**
  25307. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  25308. *
  25309. * @private
  25310. * @param {Object} object The object to inspect.
  25311. * @param {Object} source The object of property values to match.
  25312. * @param {Array} matchData The property names, values, and compare flags to match.
  25313. * @param {Function} [customizer] The function to customize comparisons.
  25314. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  25315. */
  25316. function baseIsMatch(object, source, matchData, customizer) {
  25317. var index = matchData.length,
  25318. length = index,
  25319. noCustomizer = !customizer;
  25320. if (object == null) {
  25321. return !length;
  25322. }
  25323. object = Object(object);
  25324. while (index--) {
  25325. var data = matchData[index];
  25326. if ((noCustomizer && data[2])
  25327. ? data[1] !== object[data[0]]
  25328. : !(data[0] in object)
  25329. ) {
  25330. return false;
  25331. }
  25332. }
  25333. while (++index < length) {
  25334. data = matchData[index];
  25335. var key = data[0],
  25336. objValue = object[key],
  25337. srcValue = data[1];
  25338. if (noCustomizer && data[2]) {
  25339. if (objValue === undefined && !(key in object)) {
  25340. return false;
  25341. }
  25342. } else {
  25343. var stack = new Stack;
  25344. if (customizer) {
  25345. var result = customizer(objValue, srcValue, key, object, source, stack);
  25346. }
  25347. if (!(result === undefined
  25348. ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
  25349. : result
  25350. )) {
  25351. return false;
  25352. }
  25353. }
  25354. }
  25355. return true;
  25356. }
  25357. /**
  25358. * The base implementation of `_.isNative` without bad shim checks.
  25359. *
  25360. * @private
  25361. * @param {*} value The value to check.
  25362. * @returns {boolean} Returns `true` if `value` is a native function,
  25363. * else `false`.
  25364. */
  25365. function baseIsNative(value) {
  25366. if (!isObject(value) || isMasked(value)) {
  25367. return false;
  25368. }
  25369. var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  25370. return pattern.test(toSource(value));
  25371. }
  25372. /**
  25373. * The base implementation of `_.isRegExp` without Node.js optimizations.
  25374. *
  25375. * @private
  25376. * @param {*} value The value to check.
  25377. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
  25378. */
  25379. function baseIsRegExp(value) {
  25380. return isObjectLike(value) && baseGetTag(value) == regexpTag;
  25381. }
  25382. /**
  25383. * The base implementation of `_.isSet` without Node.js optimizations.
  25384. *
  25385. * @private
  25386. * @param {*} value The value to check.
  25387. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  25388. */
  25389. function baseIsSet(value) {
  25390. return isObjectLike(value) && getTag(value) == setTag;
  25391. }
  25392. /**
  25393. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  25394. *
  25395. * @private
  25396. * @param {*} value The value to check.
  25397. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  25398. */
  25399. function baseIsTypedArray(value) {
  25400. return isObjectLike(value) &&
  25401. isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
  25402. }
  25403. /**
  25404. * The base implementation of `_.iteratee`.
  25405. *
  25406. * @private
  25407. * @param {*} [value=_.identity] The value to convert to an iteratee.
  25408. * @returns {Function} Returns the iteratee.
  25409. */
  25410. function baseIteratee(value) {
  25411. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  25412. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  25413. if (typeof value == 'function') {
  25414. return value;
  25415. }
  25416. if (value == null) {
  25417. return identity;
  25418. }
  25419. if (typeof value == 'object') {
  25420. return isArray(value)
  25421. ? baseMatchesProperty(value[0], value[1])
  25422. : baseMatches(value);
  25423. }
  25424. return property(value);
  25425. }
  25426. /**
  25427. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  25428. *
  25429. * @private
  25430. * @param {Object} object The object to query.
  25431. * @returns {Array} Returns the array of property names.
  25432. */
  25433. function baseKeys(object) {
  25434. if (!isPrototype(object)) {
  25435. return nativeKeys(object);
  25436. }
  25437. var result = [];
  25438. for (var key in Object(object)) {
  25439. if (hasOwnProperty.call(object, key) && key != 'constructor') {
  25440. result.push(key);
  25441. }
  25442. }
  25443. return result;
  25444. }
  25445. /**
  25446. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  25447. *
  25448. * @private
  25449. * @param {Object} object The object to query.
  25450. * @returns {Array} Returns the array of property names.
  25451. */
  25452. function baseKeysIn(object) {
  25453. if (!isObject(object)) {
  25454. return nativeKeysIn(object);
  25455. }
  25456. var isProto = isPrototype(object),
  25457. result = [];
  25458. for (var key in object) {
  25459. if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
  25460. result.push(key);
  25461. }
  25462. }
  25463. return result;
  25464. }
  25465. /**
  25466. * The base implementation of `_.lt` which doesn't coerce arguments.
  25467. *
  25468. * @private
  25469. * @param {*} value The value to compare.
  25470. * @param {*} other The other value to compare.
  25471. * @returns {boolean} Returns `true` if `value` is less than `other`,
  25472. * else `false`.
  25473. */
  25474. function baseLt(value, other) {
  25475. return value < other;
  25476. }
  25477. /**
  25478. * The base implementation of `_.map` without support for iteratee shorthands.
  25479. *
  25480. * @private
  25481. * @param {Array|Object} collection The collection to iterate over.
  25482. * @param {Function} iteratee The function invoked per iteration.
  25483. * @returns {Array} Returns the new mapped array.
  25484. */
  25485. function baseMap(collection, iteratee) {
  25486. var index = -1,
  25487. result = isArrayLike(collection) ? Array(collection.length) : [];
  25488. baseEach(collection, function(value, key, collection) {
  25489. result[++index] = iteratee(value, key, collection);
  25490. });
  25491. return result;
  25492. }
  25493. /**
  25494. * The base implementation of `_.matches` which doesn't clone `source`.
  25495. *
  25496. * @private
  25497. * @param {Object} source The object of property values to match.
  25498. * @returns {Function} Returns the new spec function.
  25499. */
  25500. function baseMatches(source) {
  25501. var matchData = getMatchData(source);
  25502. if (matchData.length == 1 && matchData[0][2]) {
  25503. return matchesStrictComparable(matchData[0][0], matchData[0][1]);
  25504. }
  25505. return function(object) {
  25506. return object === source || baseIsMatch(object, source, matchData);
  25507. };
  25508. }
  25509. /**
  25510. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  25511. *
  25512. * @private
  25513. * @param {string} path The path of the property to get.
  25514. * @param {*} srcValue The value to match.
  25515. * @returns {Function} Returns the new spec function.
  25516. */
  25517. function baseMatchesProperty(path, srcValue) {
  25518. if (isKey(path) && isStrictComparable(srcValue)) {
  25519. return matchesStrictComparable(toKey(path), srcValue);
  25520. }
  25521. return function(object) {
  25522. var objValue = get(object, path);
  25523. return (objValue === undefined && objValue === srcValue)
  25524. ? hasIn(object, path)
  25525. : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  25526. };
  25527. }
  25528. /**
  25529. * The base implementation of `_.merge` without support for multiple sources.
  25530. *
  25531. * @private
  25532. * @param {Object} object The destination object.
  25533. * @param {Object} source The source object.
  25534. * @param {number} srcIndex The index of `source`.
  25535. * @param {Function} [customizer] The function to customize merged values.
  25536. * @param {Object} [stack] Tracks traversed source values and their merged
  25537. * counterparts.
  25538. */
  25539. function baseMerge(object, source, srcIndex, customizer, stack) {
  25540. if (object === source) {
  25541. return;
  25542. }
  25543. baseFor(source, function(srcValue, key) {
  25544. if (isObject(srcValue)) {
  25545. stack || (stack = new Stack);
  25546. baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
  25547. }
  25548. else {
  25549. var newValue = customizer
  25550. ? customizer(object[key], srcValue, (key + ''), object, source, stack)
  25551. : undefined;
  25552. if (newValue === undefined) {
  25553. newValue = srcValue;
  25554. }
  25555. assignMergeValue(object, key, newValue);
  25556. }
  25557. }, keysIn);
  25558. }
  25559. /**
  25560. * A specialized version of `baseMerge` for arrays and objects which performs
  25561. * deep merges and tracks traversed objects enabling objects with circular
  25562. * references to be merged.
  25563. *
  25564. * @private
  25565. * @param {Object} object The destination object.
  25566. * @param {Object} source The source object.
  25567. * @param {string} key The key of the value to merge.
  25568. * @param {number} srcIndex The index of `source`.
  25569. * @param {Function} mergeFunc The function to merge values.
  25570. * @param {Function} [customizer] The function to customize assigned values.
  25571. * @param {Object} [stack] Tracks traversed source values and their merged
  25572. * counterparts.
  25573. */
  25574. function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
  25575. var objValue = object[key],
  25576. srcValue = source[key],
  25577. stacked = stack.get(srcValue);
  25578. if (stacked) {
  25579. assignMergeValue(object, key, stacked);
  25580. return;
  25581. }
  25582. var newValue = customizer
  25583. ? customizer(objValue, srcValue, (key + ''), object, source, stack)
  25584. : undefined;
  25585. var isCommon = newValue === undefined;
  25586. if (isCommon) {
  25587. var isArr = isArray(srcValue),
  25588. isBuff = !isArr && isBuffer(srcValue),
  25589. isTyped = !isArr && !isBuff && isTypedArray(srcValue);
  25590. newValue = srcValue;
  25591. if (isArr || isBuff || isTyped) {
  25592. if (isArray(objValue)) {
  25593. newValue = objValue;
  25594. }
  25595. else if (isArrayLikeObject(objValue)) {
  25596. newValue = copyArray(objValue);
  25597. }
  25598. else if (isBuff) {
  25599. isCommon = false;
  25600. newValue = cloneBuffer(srcValue, true);
  25601. }
  25602. else if (isTyped) {
  25603. isCommon = false;
  25604. newValue = cloneTypedArray(srcValue, true);
  25605. }
  25606. else {
  25607. newValue = [];
  25608. }
  25609. }
  25610. else if (isPlainObject(srcValue) || isArguments(srcValue)) {
  25611. newValue = objValue;
  25612. if (isArguments(objValue)) {
  25613. newValue = toPlainObject(objValue);
  25614. }
  25615. else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
  25616. newValue = initCloneObject(srcValue);
  25617. }
  25618. }
  25619. else {
  25620. isCommon = false;
  25621. }
  25622. }
  25623. if (isCommon) {
  25624. // Recursively merge objects and arrays (susceptible to call stack limits).
  25625. stack.set(srcValue, newValue);
  25626. mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
  25627. stack['delete'](srcValue);
  25628. }
  25629. assignMergeValue(object, key, newValue);
  25630. }
  25631. /**
  25632. * The base implementation of `_.nth` which doesn't coerce arguments.
  25633. *
  25634. * @private
  25635. * @param {Array} array The array to query.
  25636. * @param {number} n The index of the element to return.
  25637. * @returns {*} Returns the nth element of `array`.
  25638. */
  25639. function baseNth(array, n) {
  25640. var length = array.length;
  25641. if (!length) {
  25642. return;
  25643. }
  25644. n += n < 0 ? length : 0;
  25645. return isIndex(n, length) ? array[n] : undefined;
  25646. }
  25647. /**
  25648. * The base implementation of `_.orderBy` without param guards.
  25649. *
  25650. * @private
  25651. * @param {Array|Object} collection The collection to iterate over.
  25652. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
  25653. * @param {string[]} orders The sort orders of `iteratees`.
  25654. * @returns {Array} Returns the new sorted array.
  25655. */
  25656. function baseOrderBy(collection, iteratees, orders) {
  25657. var index = -1;
  25658. iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee()));
  25659. var result = baseMap(collection, function(value, key, collection) {
  25660. var criteria = arrayMap(iteratees, function(iteratee) {
  25661. return iteratee(value);
  25662. });
  25663. return { 'criteria': criteria, 'index': ++index, 'value': value };
  25664. });
  25665. return baseSortBy(result, function(object, other) {
  25666. return compareMultiple(object, other, orders);
  25667. });
  25668. }
  25669. /**
  25670. * The base implementation of `_.pick` without support for individual
  25671. * property identifiers.
  25672. *
  25673. * @private
  25674. * @param {Object} object The source object.
  25675. * @param {string[]} paths The property paths to pick.
  25676. * @returns {Object} Returns the new object.
  25677. */
  25678. function basePick(object, paths) {
  25679. return basePickBy(object, paths, function(value, path) {
  25680. return hasIn(object, path);
  25681. });
  25682. }
  25683. /**
  25684. * The base implementation of `_.pickBy` without support for iteratee shorthands.
  25685. *
  25686. * @private
  25687. * @param {Object} object The source object.
  25688. * @param {string[]} paths The property paths to pick.
  25689. * @param {Function} predicate The function invoked per property.
  25690. * @returns {Object} Returns the new object.
  25691. */
  25692. function basePickBy(object, paths, predicate) {
  25693. var index = -1,
  25694. length = paths.length,
  25695. result = {};
  25696. while (++index < length) {
  25697. var path = paths[index],
  25698. value = baseGet(object, path);
  25699. if (predicate(value, path)) {
  25700. baseSet(result, castPath(path, object), value);
  25701. }
  25702. }
  25703. return result;
  25704. }
  25705. /**
  25706. * A specialized version of `baseProperty` which supports deep paths.
  25707. *
  25708. * @private
  25709. * @param {Array|string} path The path of the property to get.
  25710. * @returns {Function} Returns the new accessor function.
  25711. */
  25712. function basePropertyDeep(path) {
  25713. return function(object) {
  25714. return baseGet(object, path);
  25715. };
  25716. }
  25717. /**
  25718. * The base implementation of `_.pullAllBy` without support for iteratee
  25719. * shorthands.
  25720. *
  25721. * @private
  25722. * @param {Array} array The array to modify.
  25723. * @param {Array} values The values to remove.
  25724. * @param {Function} [iteratee] The iteratee invoked per element.
  25725. * @param {Function} [comparator] The comparator invoked per element.
  25726. * @returns {Array} Returns `array`.
  25727. */
  25728. function basePullAll(array, values, iteratee, comparator) {
  25729. var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
  25730. index = -1,
  25731. length = values.length,
  25732. seen = array;
  25733. if (array === values) {
  25734. values = copyArray(values);
  25735. }
  25736. if (iteratee) {
  25737. seen = arrayMap(array, baseUnary(iteratee));
  25738. }
  25739. while (++index < length) {
  25740. var fromIndex = 0,
  25741. value = values[index],
  25742. computed = iteratee ? iteratee(value) : value;
  25743. while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
  25744. if (seen !== array) {
  25745. splice.call(seen, fromIndex, 1);
  25746. }
  25747. splice.call(array, fromIndex, 1);
  25748. }
  25749. }
  25750. return array;
  25751. }
  25752. /**
  25753. * The base implementation of `_.pullAt` without support for individual
  25754. * indexes or capturing the removed elements.
  25755. *
  25756. * @private
  25757. * @param {Array} array The array to modify.
  25758. * @param {number[]} indexes The indexes of elements to remove.
  25759. * @returns {Array} Returns `array`.
  25760. */
  25761. function basePullAt(array, indexes) {
  25762. var length = array ? indexes.length : 0,
  25763. lastIndex = length - 1;
  25764. while (length--) {
  25765. var index = indexes[length];
  25766. if (length == lastIndex || index !== previous) {
  25767. var previous = index;
  25768. if (isIndex(index)) {
  25769. splice.call(array, index, 1);
  25770. } else {
  25771. baseUnset(array, index);
  25772. }
  25773. }
  25774. }
  25775. return array;
  25776. }
  25777. /**
  25778. * The base implementation of `_.random` without support for returning
  25779. * floating-point numbers.
  25780. *
  25781. * @private
  25782. * @param {number} lower The lower bound.
  25783. * @param {number} upper The upper bound.
  25784. * @returns {number} Returns the random number.
  25785. */
  25786. function baseRandom(lower, upper) {
  25787. return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
  25788. }
  25789. /**
  25790. * The base implementation of `_.range` and `_.rangeRight` which doesn't
  25791. * coerce arguments.
  25792. *
  25793. * @private
  25794. * @param {number} start The start of the range.
  25795. * @param {number} end The end of the range.
  25796. * @param {number} step The value to increment or decrement by.
  25797. * @param {boolean} [fromRight] Specify iterating from right to left.
  25798. * @returns {Array} Returns the range of numbers.
  25799. */
  25800. function baseRange(start, end, step, fromRight) {
  25801. var index = -1,
  25802. length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
  25803. result = Array(length);
  25804. while (length--) {
  25805. result[fromRight ? length : ++index] = start;
  25806. start += step;
  25807. }
  25808. return result;
  25809. }
  25810. /**
  25811. * The base implementation of `_.repeat` which doesn't coerce arguments.
  25812. *
  25813. * @private
  25814. * @param {string} string The string to repeat.
  25815. * @param {number} n The number of times to repeat the string.
  25816. * @returns {string} Returns the repeated string.
  25817. */
  25818. function baseRepeat(string, n) {
  25819. var result = '';
  25820. if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
  25821. return result;
  25822. }
  25823. // Leverage the exponentiation by squaring algorithm for a faster repeat.
  25824. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
  25825. do {
  25826. if (n % 2) {
  25827. result += string;
  25828. }
  25829. n = nativeFloor(n / 2);
  25830. if (n) {
  25831. string += string;
  25832. }
  25833. } while (n);
  25834. return result;
  25835. }
  25836. /**
  25837. * The base implementation of `_.rest` which doesn't validate or coerce arguments.
  25838. *
  25839. * @private
  25840. * @param {Function} func The function to apply a rest parameter to.
  25841. * @param {number} [start=func.length-1] The start position of the rest parameter.
  25842. * @returns {Function} Returns the new function.
  25843. */
  25844. function baseRest(func, start) {
  25845. return setToString(overRest(func, start, identity), func + '');
  25846. }
  25847. /**
  25848. * The base implementation of `_.sample`.
  25849. *
  25850. * @private
  25851. * @param {Array|Object} collection The collection to sample.
  25852. * @returns {*} Returns the random element.
  25853. */
  25854. function baseSample(collection) {
  25855. return arraySample(values(collection));
  25856. }
  25857. /**
  25858. * The base implementation of `_.sampleSize` without param guards.
  25859. *
  25860. * @private
  25861. * @param {Array|Object} collection The collection to sample.
  25862. * @param {number} n The number of elements to sample.
  25863. * @returns {Array} Returns the random elements.
  25864. */
  25865. function baseSampleSize(collection, n) {
  25866. var array = values(collection);
  25867. return shuffleSelf(array, baseClamp(n, 0, array.length));
  25868. }
  25869. /**
  25870. * The base implementation of `_.set`.
  25871. *
  25872. * @private
  25873. * @param {Object} object The object to modify.
  25874. * @param {Array|string} path The path of the property to set.
  25875. * @param {*} value The value to set.
  25876. * @param {Function} [customizer] The function to customize path creation.
  25877. * @returns {Object} Returns `object`.
  25878. */
  25879. function baseSet(object, path, value, customizer) {
  25880. if (!isObject(object)) {
  25881. return object;
  25882. }
  25883. path = castPath(path, object);
  25884. var index = -1,
  25885. length = path.length,
  25886. lastIndex = length - 1,
  25887. nested = object;
  25888. while (nested != null && ++index < length) {
  25889. var key = toKey(path[index]),
  25890. newValue = value;
  25891. if (index != lastIndex) {
  25892. var objValue = nested[key];
  25893. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  25894. if (newValue === undefined) {
  25895. newValue = isObject(objValue)
  25896. ? objValue
  25897. : (isIndex(path[index + 1]) ? [] : {});
  25898. }
  25899. }
  25900. assignValue(nested, key, newValue);
  25901. nested = nested[key];
  25902. }
  25903. return object;
  25904. }
  25905. /**
  25906. * The base implementation of `setData` without support for hot loop shorting.
  25907. *
  25908. * @private
  25909. * @param {Function} func The function to associate metadata with.
  25910. * @param {*} data The metadata.
  25911. * @returns {Function} Returns `func`.
  25912. */
  25913. var baseSetData = !metaMap ? identity : function(func, data) {
  25914. metaMap.set(func, data);
  25915. return func;
  25916. };
  25917. /**
  25918. * The base implementation of `setToString` without support for hot loop shorting.
  25919. *
  25920. * @private
  25921. * @param {Function} func The function to modify.
  25922. * @param {Function} string The `toString` result.
  25923. * @returns {Function} Returns `func`.
  25924. */
  25925. var baseSetToString = !defineProperty ? identity : function(func, string) {
  25926. return defineProperty(func, 'toString', {
  25927. 'configurable': true,
  25928. 'enumerable': false,
  25929. 'value': constant(string),
  25930. 'writable': true
  25931. });
  25932. };
  25933. /**
  25934. * The base implementation of `_.shuffle`.
  25935. *
  25936. * @private
  25937. * @param {Array|Object} collection The collection to shuffle.
  25938. * @returns {Array} Returns the new shuffled array.
  25939. */
  25940. function baseShuffle(collection) {
  25941. return shuffleSelf(values(collection));
  25942. }
  25943. /**
  25944. * The base implementation of `_.slice` without an iteratee call guard.
  25945. *
  25946. * @private
  25947. * @param {Array} array The array to slice.
  25948. * @param {number} [start=0] The start position.
  25949. * @param {number} [end=array.length] The end position.
  25950. * @returns {Array} Returns the slice of `array`.
  25951. */
  25952. function baseSlice(array, start, end) {
  25953. var index = -1,
  25954. length = array.length;
  25955. if (start < 0) {
  25956. start = -start > length ? 0 : (length + start);
  25957. }
  25958. end = end > length ? length : end;
  25959. if (end < 0) {
  25960. end += length;
  25961. }
  25962. length = start > end ? 0 : ((end - start) >>> 0);
  25963. start >>>= 0;
  25964. var result = Array(length);
  25965. while (++index < length) {
  25966. result[index] = array[index + start];
  25967. }
  25968. return result;
  25969. }
  25970. /**
  25971. * The base implementation of `_.some` without support for iteratee shorthands.
  25972. *
  25973. * @private
  25974. * @param {Array|Object} collection The collection to iterate over.
  25975. * @param {Function} predicate The function invoked per iteration.
  25976. * @returns {boolean} Returns `true` if any element passes the predicate check,
  25977. * else `false`.
  25978. */
  25979. function baseSome(collection, predicate) {
  25980. var result;
  25981. baseEach(collection, function(value, index, collection) {
  25982. result = predicate(value, index, collection);
  25983. return !result;
  25984. });
  25985. return !!result;
  25986. }
  25987. /**
  25988. * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
  25989. * performs a binary search of `array` to determine the index at which `value`
  25990. * should be inserted into `array` in order to maintain its sort order.
  25991. *
  25992. * @private
  25993. * @param {Array} array The sorted array to inspect.
  25994. * @param {*} value The value to evaluate.
  25995. * @param {boolean} [retHighest] Specify returning the highest qualified index.
  25996. * @returns {number} Returns the index at which `value` should be inserted
  25997. * into `array`.
  25998. */
  25999. function baseSortedIndex(array, value, retHighest) {
  26000. var low = 0,
  26001. high = array == null ? low : array.length;
  26002. if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
  26003. while (low < high) {
  26004. var mid = (low + high) >>> 1,
  26005. computed = array[mid];
  26006. if (computed !== null && !isSymbol(computed) &&
  26007. (retHighest ? (computed <= value) : (computed < value))) {
  26008. low = mid + 1;
  26009. } else {
  26010. high = mid;
  26011. }
  26012. }
  26013. return high;
  26014. }
  26015. return baseSortedIndexBy(array, value, identity, retHighest);
  26016. }
  26017. /**
  26018. * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
  26019. * which invokes `iteratee` for `value` and each element of `array` to compute
  26020. * their sort ranking. The iteratee is invoked with one argument; (value).
  26021. *
  26022. * @private
  26023. * @param {Array} array The sorted array to inspect.
  26024. * @param {*} value The value to evaluate.
  26025. * @param {Function} iteratee The iteratee invoked per element.
  26026. * @param {boolean} [retHighest] Specify returning the highest qualified index.
  26027. * @returns {number} Returns the index at which `value` should be inserted
  26028. * into `array`.
  26029. */
  26030. function baseSortedIndexBy(array, value, iteratee, retHighest) {
  26031. value = iteratee(value);
  26032. var low = 0,
  26033. high = array == null ? 0 : array.length,
  26034. valIsNaN = value !== value,
  26035. valIsNull = value === null,
  26036. valIsSymbol = isSymbol(value),
  26037. valIsUndefined = value === undefined;
  26038. while (low < high) {
  26039. var mid = nativeFloor((low + high) / 2),
  26040. computed = iteratee(array[mid]),
  26041. othIsDefined = computed !== undefined,
  26042. othIsNull = computed === null,
  26043. othIsReflexive = computed === computed,
  26044. othIsSymbol = isSymbol(computed);
  26045. if (valIsNaN) {
  26046. var setLow = retHighest || othIsReflexive;
  26047. } else if (valIsUndefined) {
  26048. setLow = othIsReflexive && (retHighest || othIsDefined);
  26049. } else if (valIsNull) {
  26050. setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
  26051. } else if (valIsSymbol) {
  26052. setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
  26053. } else if (othIsNull || othIsSymbol) {
  26054. setLow = false;
  26055. } else {
  26056. setLow = retHighest ? (computed <= value) : (computed < value);
  26057. }
  26058. if (setLow) {
  26059. low = mid + 1;
  26060. } else {
  26061. high = mid;
  26062. }
  26063. }
  26064. return nativeMin(high, MAX_ARRAY_INDEX);
  26065. }
  26066. /**
  26067. * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
  26068. * support for iteratee shorthands.
  26069. *
  26070. * @private
  26071. * @param {Array} array The array to inspect.
  26072. * @param {Function} [iteratee] The iteratee invoked per element.
  26073. * @returns {Array} Returns the new duplicate free array.
  26074. */
  26075. function baseSortedUniq(array, iteratee) {
  26076. var index = -1,
  26077. length = array.length,
  26078. resIndex = 0,
  26079. result = [];
  26080. while (++index < length) {
  26081. var value = array[index],
  26082. computed = iteratee ? iteratee(value) : value;
  26083. if (!index || !eq(computed, seen)) {
  26084. var seen = computed;
  26085. result[resIndex++] = value === 0 ? 0 : value;
  26086. }
  26087. }
  26088. return result;
  26089. }
  26090. /**
  26091. * The base implementation of `_.toNumber` which doesn't ensure correct
  26092. * conversions of binary, hexadecimal, or octal string values.
  26093. *
  26094. * @private
  26095. * @param {*} value The value to process.
  26096. * @returns {number} Returns the number.
  26097. */
  26098. function baseToNumber(value) {
  26099. if (typeof value == 'number') {
  26100. return value;
  26101. }
  26102. if (isSymbol(value)) {
  26103. return NAN;
  26104. }
  26105. return +value;
  26106. }
  26107. /**
  26108. * The base implementation of `_.toString` which doesn't convert nullish
  26109. * values to empty strings.
  26110. *
  26111. * @private
  26112. * @param {*} value The value to process.
  26113. * @returns {string} Returns the string.
  26114. */
  26115. function baseToString(value) {
  26116. // Exit early for strings to avoid a performance hit in some environments.
  26117. if (typeof value == 'string') {
  26118. return value;
  26119. }
  26120. if (isArray(value)) {
  26121. // Recursively convert values (susceptible to call stack limits).
  26122. return arrayMap(value, baseToString) + '';
  26123. }
  26124. if (isSymbol(value)) {
  26125. return symbolToString ? symbolToString.call(value) : '';
  26126. }
  26127. var result = (value + '');
  26128. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  26129. }
  26130. /**
  26131. * The base implementation of `_.uniqBy` without support for iteratee shorthands.
  26132. *
  26133. * @private
  26134. * @param {Array} array The array to inspect.
  26135. * @param {Function} [iteratee] The iteratee invoked per element.
  26136. * @param {Function} [comparator] The comparator invoked per element.
  26137. * @returns {Array} Returns the new duplicate free array.
  26138. */
  26139. function baseUniq(array, iteratee, comparator) {
  26140. var index = -1,
  26141. includes = arrayIncludes,
  26142. length = array.length,
  26143. isCommon = true,
  26144. result = [],
  26145. seen = result;
  26146. if (comparator) {
  26147. isCommon = false;
  26148. includes = arrayIncludesWith;
  26149. }
  26150. else if (length >= LARGE_ARRAY_SIZE) {
  26151. var set = iteratee ? null : createSet(array);
  26152. if (set) {
  26153. return setToArray(set);
  26154. }
  26155. isCommon = false;
  26156. includes = cacheHas;
  26157. seen = new SetCache;
  26158. }
  26159. else {
  26160. seen = iteratee ? [] : result;
  26161. }
  26162. outer:
  26163. while (++index < length) {
  26164. var value = array[index],
  26165. computed = iteratee ? iteratee(value) : value;
  26166. value = (comparator || value !== 0) ? value : 0;
  26167. if (isCommon && computed === computed) {
  26168. var seenIndex = seen.length;
  26169. while (seenIndex--) {
  26170. if (seen[seenIndex] === computed) {
  26171. continue outer;
  26172. }
  26173. }
  26174. if (iteratee) {
  26175. seen.push(computed);
  26176. }
  26177. result.push(value);
  26178. }
  26179. else if (!includes(seen, computed, comparator)) {
  26180. if (seen !== result) {
  26181. seen.push(computed);
  26182. }
  26183. result.push(value);
  26184. }
  26185. }
  26186. return result;
  26187. }
  26188. /**
  26189. * The base implementation of `_.unset`.
  26190. *
  26191. * @private
  26192. * @param {Object} object The object to modify.
  26193. * @param {Array|string} path The property path to unset.
  26194. * @returns {boolean} Returns `true` if the property is deleted, else `false`.
  26195. */
  26196. function baseUnset(object, path) {
  26197. path = castPath(path, object);
  26198. object = parent(object, path);
  26199. return object == null || delete object[toKey(last(path))];
  26200. }
  26201. /**
  26202. * The base implementation of `_.update`.
  26203. *
  26204. * @private
  26205. * @param {Object} object The object to modify.
  26206. * @param {Array|string} path The path of the property to update.
  26207. * @param {Function} updater The function to produce the updated value.
  26208. * @param {Function} [customizer] The function to customize path creation.
  26209. * @returns {Object} Returns `object`.
  26210. */
  26211. function baseUpdate(object, path, updater, customizer) {
  26212. return baseSet(object, path, updater(baseGet(object, path)), customizer);
  26213. }
  26214. /**
  26215. * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
  26216. * without support for iteratee shorthands.
  26217. *
  26218. * @private
  26219. * @param {Array} array The array to query.
  26220. * @param {Function} predicate The function invoked per iteration.
  26221. * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
  26222. * @param {boolean} [fromRight] Specify iterating from right to left.
  26223. * @returns {Array} Returns the slice of `array`.
  26224. */
  26225. function baseWhile(array, predicate, isDrop, fromRight) {
  26226. var length = array.length,
  26227. index = fromRight ? length : -1;
  26228. while ((fromRight ? index-- : ++index < length) &&
  26229. predicate(array[index], index, array)) {}
  26230. return isDrop
  26231. ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
  26232. : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
  26233. }
  26234. /**
  26235. * The base implementation of `wrapperValue` which returns the result of
  26236. * performing a sequence of actions on the unwrapped `value`, where each
  26237. * successive action is supplied the return value of the previous.
  26238. *
  26239. * @private
  26240. * @param {*} value The unwrapped value.
  26241. * @param {Array} actions Actions to perform to resolve the unwrapped value.
  26242. * @returns {*} Returns the resolved value.
  26243. */
  26244. function baseWrapperValue(value, actions) {
  26245. var result = value;
  26246. if (result instanceof LazyWrapper) {
  26247. result = result.value();
  26248. }
  26249. return arrayReduce(actions, function(result, action) {
  26250. return action.func.apply(action.thisArg, arrayPush([result], action.args));
  26251. }, result);
  26252. }
  26253. /**
  26254. * The base implementation of methods like `_.xor`, without support for
  26255. * iteratee shorthands, that accepts an array of arrays to inspect.
  26256. *
  26257. * @private
  26258. * @param {Array} arrays The arrays to inspect.
  26259. * @param {Function} [iteratee] The iteratee invoked per element.
  26260. * @param {Function} [comparator] The comparator invoked per element.
  26261. * @returns {Array} Returns the new array of values.
  26262. */
  26263. function baseXor(arrays, iteratee, comparator) {
  26264. var length = arrays.length;
  26265. if (length < 2) {
  26266. return length ? baseUniq(arrays[0]) : [];
  26267. }
  26268. var index = -1,
  26269. result = Array(length);
  26270. while (++index < length) {
  26271. var array = arrays[index],
  26272. othIndex = -1;
  26273. while (++othIndex < length) {
  26274. if (othIndex != index) {
  26275. result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
  26276. }
  26277. }
  26278. }
  26279. return baseUniq(baseFlatten(result, 1), iteratee, comparator);
  26280. }
  26281. /**
  26282. * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
  26283. *
  26284. * @private
  26285. * @param {Array} props The property identifiers.
  26286. * @param {Array} values The property values.
  26287. * @param {Function} assignFunc The function to assign values.
  26288. * @returns {Object} Returns the new object.
  26289. */
  26290. function baseZipObject(props, values, assignFunc) {
  26291. var index = -1,
  26292. length = props.length,
  26293. valsLength = values.length,
  26294. result = {};
  26295. while (++index < length) {
  26296. var value = index < valsLength ? values[index] : undefined;
  26297. assignFunc(result, props[index], value);
  26298. }
  26299. return result;
  26300. }
  26301. /**
  26302. * Casts `value` to an empty array if it's not an array like object.
  26303. *
  26304. * @private
  26305. * @param {*} value The value to inspect.
  26306. * @returns {Array|Object} Returns the cast array-like object.
  26307. */
  26308. function castArrayLikeObject(value) {
  26309. return isArrayLikeObject(value) ? value : [];
  26310. }
  26311. /**
  26312. * Casts `value` to `identity` if it's not a function.
  26313. *
  26314. * @private
  26315. * @param {*} value The value to inspect.
  26316. * @returns {Function} Returns cast function.
  26317. */
  26318. function castFunction(value) {
  26319. return typeof value == 'function' ? value : identity;
  26320. }
  26321. /**
  26322. * Casts `value` to a path array if it's not one.
  26323. *
  26324. * @private
  26325. * @param {*} value The value to inspect.
  26326. * @param {Object} [object] The object to query keys on.
  26327. * @returns {Array} Returns the cast property path array.
  26328. */
  26329. function castPath(value, object) {
  26330. if (isArray(value)) {
  26331. return value;
  26332. }
  26333. return isKey(value, object) ? [value] : stringToPath(toString(value));
  26334. }
  26335. /**
  26336. * A `baseRest` alias which can be replaced with `identity` by module
  26337. * replacement plugins.
  26338. *
  26339. * @private
  26340. * @type {Function}
  26341. * @param {Function} func The function to apply a rest parameter to.
  26342. * @returns {Function} Returns the new function.
  26343. */
  26344. var castRest = baseRest;
  26345. /**
  26346. * Casts `array` to a slice if it's needed.
  26347. *
  26348. * @private
  26349. * @param {Array} array The array to inspect.
  26350. * @param {number} start The start position.
  26351. * @param {number} [end=array.length] The end position.
  26352. * @returns {Array} Returns the cast slice.
  26353. */
  26354. function castSlice(array, start, end) {
  26355. var length = array.length;
  26356. end = end === undefined ? length : end;
  26357. return (!start && end >= length) ? array : baseSlice(array, start, end);
  26358. }
  26359. /**
  26360. * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
  26361. *
  26362. * @private
  26363. * @param {number|Object} id The timer id or timeout object of the timer to clear.
  26364. */
  26365. var clearTimeout = ctxClearTimeout || function(id) {
  26366. return root.clearTimeout(id);
  26367. };
  26368. /**
  26369. * Creates a clone of `buffer`.
  26370. *
  26371. * @private
  26372. * @param {Buffer} buffer The buffer to clone.
  26373. * @param {boolean} [isDeep] Specify a deep clone.
  26374. * @returns {Buffer} Returns the cloned buffer.
  26375. */
  26376. function cloneBuffer(buffer, isDeep) {
  26377. if (isDeep) {
  26378. return buffer.slice();
  26379. }
  26380. var length = buffer.length,
  26381. result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  26382. buffer.copy(result);
  26383. return result;
  26384. }
  26385. /**
  26386. * Creates a clone of `arrayBuffer`.
  26387. *
  26388. * @private
  26389. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  26390. * @returns {ArrayBuffer} Returns the cloned array buffer.
  26391. */
  26392. function cloneArrayBuffer(arrayBuffer) {
  26393. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  26394. new Uint8Array(result).set(new Uint8Array(arrayBuffer));
  26395. return result;
  26396. }
  26397. /**
  26398. * Creates a clone of `dataView`.
  26399. *
  26400. * @private
  26401. * @param {Object} dataView The data view to clone.
  26402. * @param {boolean} [isDeep] Specify a deep clone.
  26403. * @returns {Object} Returns the cloned data view.
  26404. */
  26405. function cloneDataView(dataView, isDeep) {
  26406. var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  26407. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  26408. }
  26409. /**
  26410. * Creates a clone of `map`.
  26411. *
  26412. * @private
  26413. * @param {Object} map The map to clone.
  26414. * @param {Function} cloneFunc The function to clone values.
  26415. * @param {boolean} [isDeep] Specify a deep clone.
  26416. * @returns {Object} Returns the cloned map.
  26417. */
  26418. function cloneMap(map, isDeep, cloneFunc) {
  26419. var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map);
  26420. return arrayReduce(array, addMapEntry, new map.constructor);
  26421. }
  26422. /**
  26423. * Creates a clone of `regexp`.
  26424. *
  26425. * @private
  26426. * @param {Object} regexp The regexp to clone.
  26427. * @returns {Object} Returns the cloned regexp.
  26428. */
  26429. function cloneRegExp(regexp) {
  26430. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  26431. result.lastIndex = regexp.lastIndex;
  26432. return result;
  26433. }
  26434. /**
  26435. * Creates a clone of `set`.
  26436. *
  26437. * @private
  26438. * @param {Object} set The set to clone.
  26439. * @param {Function} cloneFunc The function to clone values.
  26440. * @param {boolean} [isDeep] Specify a deep clone.
  26441. * @returns {Object} Returns the cloned set.
  26442. */
  26443. function cloneSet(set, isDeep, cloneFunc) {
  26444. var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set);
  26445. return arrayReduce(array, addSetEntry, new set.constructor);
  26446. }
  26447. /**
  26448. * Creates a clone of the `symbol` object.
  26449. *
  26450. * @private
  26451. * @param {Object} symbol The symbol object to clone.
  26452. * @returns {Object} Returns the cloned symbol object.
  26453. */
  26454. function cloneSymbol(symbol) {
  26455. return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
  26456. }
  26457. /**
  26458. * Creates a clone of `typedArray`.
  26459. *
  26460. * @private
  26461. * @param {Object} typedArray The typed array to clone.
  26462. * @param {boolean} [isDeep] Specify a deep clone.
  26463. * @returns {Object} Returns the cloned typed array.
  26464. */
  26465. function cloneTypedArray(typedArray, isDeep) {
  26466. var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  26467. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  26468. }
  26469. /**
  26470. * Compares values to sort them in ascending order.
  26471. *
  26472. * @private
  26473. * @param {*} value The value to compare.
  26474. * @param {*} other The other value to compare.
  26475. * @returns {number} Returns the sort order indicator for `value`.
  26476. */
  26477. function compareAscending(value, other) {
  26478. if (value !== other) {
  26479. var valIsDefined = value !== undefined,
  26480. valIsNull = value === null,
  26481. valIsReflexive = value === value,
  26482. valIsSymbol = isSymbol(value);
  26483. var othIsDefined = other !== undefined,
  26484. othIsNull = other === null,
  26485. othIsReflexive = other === other,
  26486. othIsSymbol = isSymbol(other);
  26487. if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
  26488. (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
  26489. (valIsNull && othIsDefined && othIsReflexive) ||
  26490. (!valIsDefined && othIsReflexive) ||
  26491. !valIsReflexive) {
  26492. return 1;
  26493. }
  26494. if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
  26495. (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
  26496. (othIsNull && valIsDefined && valIsReflexive) ||
  26497. (!othIsDefined && valIsReflexive) ||
  26498. !othIsReflexive) {
  26499. return -1;
  26500. }
  26501. }
  26502. return 0;
  26503. }
  26504. /**
  26505. * Used by `_.orderBy` to compare multiple properties of a value to another
  26506. * and stable sort them.
  26507. *
  26508. * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
  26509. * specify an order of "desc" for descending or "asc" for ascending sort order
  26510. * of corresponding values.
  26511. *
  26512. * @private
  26513. * @param {Object} object The object to compare.
  26514. * @param {Object} other The other object to compare.
  26515. * @param {boolean[]|string[]} orders The order to sort by for each property.
  26516. * @returns {number} Returns the sort order indicator for `object`.
  26517. */
  26518. function compareMultiple(object, other, orders) {
  26519. var index = -1,
  26520. objCriteria = object.criteria,
  26521. othCriteria = other.criteria,
  26522. length = objCriteria.length,
  26523. ordersLength = orders.length;
  26524. while (++index < length) {
  26525. var result = compareAscending(objCriteria[index], othCriteria[index]);
  26526. if (result) {
  26527. if (index >= ordersLength) {
  26528. return result;
  26529. }
  26530. var order = orders[index];
  26531. return result * (order == 'desc' ? -1 : 1);
  26532. }
  26533. }
  26534. // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
  26535. // that causes it, under certain circumstances, to provide the same value for
  26536. // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
  26537. // for more details.
  26538. //
  26539. // This also ensures a stable sort in V8 and other engines.
  26540. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
  26541. return object.index - other.index;
  26542. }
  26543. /**
  26544. * Creates an array that is the composition of partially applied arguments,
  26545. * placeholders, and provided arguments into a single array of arguments.
  26546. *
  26547. * @private
  26548. * @param {Array} args The provided arguments.
  26549. * @param {Array} partials The arguments to prepend to those provided.
  26550. * @param {Array} holders The `partials` placeholder indexes.
  26551. * @params {boolean} [isCurried] Specify composing for a curried function.
  26552. * @returns {Array} Returns the new array of composed arguments.
  26553. */
  26554. function composeArgs(args, partials, holders, isCurried) {
  26555. var argsIndex = -1,
  26556. argsLength = args.length,
  26557. holdersLength = holders.length,
  26558. leftIndex = -1,
  26559. leftLength = partials.length,
  26560. rangeLength = nativeMax(argsLength - holdersLength, 0),
  26561. result = Array(leftLength + rangeLength),
  26562. isUncurried = !isCurried;
  26563. while (++leftIndex < leftLength) {
  26564. result[leftIndex] = partials[leftIndex];
  26565. }
  26566. while (++argsIndex < holdersLength) {
  26567. if (isUncurried || argsIndex < argsLength) {
  26568. result[holders[argsIndex]] = args[argsIndex];
  26569. }
  26570. }
  26571. while (rangeLength--) {
  26572. result[leftIndex++] = args[argsIndex++];
  26573. }
  26574. return result;
  26575. }
  26576. /**
  26577. * This function is like `composeArgs` except that the arguments composition
  26578. * is tailored for `_.partialRight`.
  26579. *
  26580. * @private
  26581. * @param {Array} args The provided arguments.
  26582. * @param {Array} partials The arguments to append to those provided.
  26583. * @param {Array} holders The `partials` placeholder indexes.
  26584. * @params {boolean} [isCurried] Specify composing for a curried function.
  26585. * @returns {Array} Returns the new array of composed arguments.
  26586. */
  26587. function composeArgsRight(args, partials, holders, isCurried) {
  26588. var argsIndex = -1,
  26589. argsLength = args.length,
  26590. holdersIndex = -1,
  26591. holdersLength = holders.length,
  26592. rightIndex = -1,
  26593. rightLength = partials.length,
  26594. rangeLength = nativeMax(argsLength - holdersLength, 0),
  26595. result = Array(rangeLength + rightLength),
  26596. isUncurried = !isCurried;
  26597. while (++argsIndex < rangeLength) {
  26598. result[argsIndex] = args[argsIndex];
  26599. }
  26600. var offset = argsIndex;
  26601. while (++rightIndex < rightLength) {
  26602. result[offset + rightIndex] = partials[rightIndex];
  26603. }
  26604. while (++holdersIndex < holdersLength) {
  26605. if (isUncurried || argsIndex < argsLength) {
  26606. result[offset + holders[holdersIndex]] = args[argsIndex++];
  26607. }
  26608. }
  26609. return result;
  26610. }
  26611. /**
  26612. * Copies the values of `source` to `array`.
  26613. *
  26614. * @private
  26615. * @param {Array} source The array to copy values from.
  26616. * @param {Array} [array=[]] The array to copy values to.
  26617. * @returns {Array} Returns `array`.
  26618. */
  26619. function copyArray(source, array) {
  26620. var index = -1,
  26621. length = source.length;
  26622. array || (array = Array(length));
  26623. while (++index < length) {
  26624. array[index] = source[index];
  26625. }
  26626. return array;
  26627. }
  26628. /**
  26629. * Copies properties of `source` to `object`.
  26630. *
  26631. * @private
  26632. * @param {Object} source The object to copy properties from.
  26633. * @param {Array} props The property identifiers to copy.
  26634. * @param {Object} [object={}] The object to copy properties to.
  26635. * @param {Function} [customizer] The function to customize copied values.
  26636. * @returns {Object} Returns `object`.
  26637. */
  26638. function copyObject(source, props, object, customizer) {
  26639. var isNew = !object;
  26640. object || (object = {});
  26641. var index = -1,
  26642. length = props.length;
  26643. while (++index < length) {
  26644. var key = props[index];
  26645. var newValue = customizer
  26646. ? customizer(object[key], source[key], key, object, source)
  26647. : undefined;
  26648. if (newValue === undefined) {
  26649. newValue = source[key];
  26650. }
  26651. if (isNew) {
  26652. baseAssignValue(object, key, newValue);
  26653. } else {
  26654. assignValue(object, key, newValue);
  26655. }
  26656. }
  26657. return object;
  26658. }
  26659. /**
  26660. * Copies own symbols of `source` to `object`.
  26661. *
  26662. * @private
  26663. * @param {Object} source The object to copy symbols from.
  26664. * @param {Object} [object={}] The object to copy symbols to.
  26665. * @returns {Object} Returns `object`.
  26666. */
  26667. function copySymbols(source, object) {
  26668. return copyObject(source, getSymbols(source), object);
  26669. }
  26670. /**
  26671. * Copies own and inherited symbols of `source` to `object`.
  26672. *
  26673. * @private
  26674. * @param {Object} source The object to copy symbols from.
  26675. * @param {Object} [object={}] The object to copy symbols to.
  26676. * @returns {Object} Returns `object`.
  26677. */
  26678. function copySymbolsIn(source, object) {
  26679. return copyObject(source, getSymbolsIn(source), object);
  26680. }
  26681. /**
  26682. * Creates a function like `_.groupBy`.
  26683. *
  26684. * @private
  26685. * @param {Function} setter The function to set accumulator values.
  26686. * @param {Function} [initializer] The accumulator object initializer.
  26687. * @returns {Function} Returns the new aggregator function.
  26688. */
  26689. function createAggregator(setter, initializer) {
  26690. return function(collection, iteratee) {
  26691. var func = isArray(collection) ? arrayAggregator : baseAggregator,
  26692. accumulator = initializer ? initializer() : {};
  26693. return func(collection, setter, getIteratee(iteratee, 2), accumulator);
  26694. };
  26695. }
  26696. /**
  26697. * Creates a function like `_.assign`.
  26698. *
  26699. * @private
  26700. * @param {Function} assigner The function to assign values.
  26701. * @returns {Function} Returns the new assigner function.
  26702. */
  26703. function createAssigner(assigner) {
  26704. return baseRest(function(object, sources) {
  26705. var index = -1,
  26706. length = sources.length,
  26707. customizer = length > 1 ? sources[length - 1] : undefined,
  26708. guard = length > 2 ? sources[2] : undefined;
  26709. customizer = (assigner.length > 3 && typeof customizer == 'function')
  26710. ? (length--, customizer)
  26711. : undefined;
  26712. if (guard && isIterateeCall(sources[0], sources[1], guard)) {
  26713. customizer = length < 3 ? undefined : customizer;
  26714. length = 1;
  26715. }
  26716. object = Object(object);
  26717. while (++index < length) {
  26718. var source = sources[index];
  26719. if (source) {
  26720. assigner(object, source, index, customizer);
  26721. }
  26722. }
  26723. return object;
  26724. });
  26725. }
  26726. /**
  26727. * Creates a `baseEach` or `baseEachRight` function.
  26728. *
  26729. * @private
  26730. * @param {Function} eachFunc The function to iterate over a collection.
  26731. * @param {boolean} [fromRight] Specify iterating from right to left.
  26732. * @returns {Function} Returns the new base function.
  26733. */
  26734. function createBaseEach(eachFunc, fromRight) {
  26735. return function(collection, iteratee) {
  26736. if (collection == null) {
  26737. return collection;
  26738. }
  26739. if (!isArrayLike(collection)) {
  26740. return eachFunc(collection, iteratee);
  26741. }
  26742. var length = collection.length,
  26743. index = fromRight ? length : -1,
  26744. iterable = Object(collection);
  26745. while ((fromRight ? index-- : ++index < length)) {
  26746. if (iteratee(iterable[index], index, iterable) === false) {
  26747. break;
  26748. }
  26749. }
  26750. return collection;
  26751. };
  26752. }
  26753. /**
  26754. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  26755. *
  26756. * @private
  26757. * @param {boolean} [fromRight] Specify iterating from right to left.
  26758. * @returns {Function} Returns the new base function.
  26759. */
  26760. function createBaseFor(fromRight) {
  26761. return function(object, iteratee, keysFunc) {
  26762. var index = -1,
  26763. iterable = Object(object),
  26764. props = keysFunc(object),
  26765. length = props.length;
  26766. while (length--) {
  26767. var key = props[fromRight ? length : ++index];
  26768. if (iteratee(iterable[key], key, iterable) === false) {
  26769. break;
  26770. }
  26771. }
  26772. return object;
  26773. };
  26774. }
  26775. /**
  26776. * Creates a function that wraps `func` to invoke it with the optional `this`
  26777. * binding of `thisArg`.
  26778. *
  26779. * @private
  26780. * @param {Function} func The function to wrap.
  26781. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  26782. * @param {*} [thisArg] The `this` binding of `func`.
  26783. * @returns {Function} Returns the new wrapped function.
  26784. */
  26785. function createBind(func, bitmask, thisArg) {
  26786. var isBind = bitmask & WRAP_BIND_FLAG,
  26787. Ctor = createCtor(func);
  26788. function wrapper() {
  26789. var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
  26790. return fn.apply(isBind ? thisArg : this, arguments);
  26791. }
  26792. return wrapper;
  26793. }
  26794. /**
  26795. * Creates a function like `_.lowerFirst`.
  26796. *
  26797. * @private
  26798. * @param {string} methodName The name of the `String` case method to use.
  26799. * @returns {Function} Returns the new case function.
  26800. */
  26801. function createCaseFirst(methodName) {
  26802. return function(string) {
  26803. string = toString(string);
  26804. var strSymbols = hasUnicode(string)
  26805. ? stringToArray(string)
  26806. : undefined;
  26807. var chr = strSymbols
  26808. ? strSymbols[0]
  26809. : string.charAt(0);
  26810. var trailing = strSymbols
  26811. ? castSlice(strSymbols, 1).join('')
  26812. : string.slice(1);
  26813. return chr[methodName]() + trailing;
  26814. };
  26815. }
  26816. /**
  26817. * Creates a function like `_.camelCase`.
  26818. *
  26819. * @private
  26820. * @param {Function} callback The function to combine each word.
  26821. * @returns {Function} Returns the new compounder function.
  26822. */
  26823. function createCompounder(callback) {
  26824. return function(string) {
  26825. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  26826. };
  26827. }
  26828. /**
  26829. * Creates a function that produces an instance of `Ctor` regardless of
  26830. * whether it was invoked as part of a `new` expression or by `call` or `apply`.
  26831. *
  26832. * @private
  26833. * @param {Function} Ctor The constructor to wrap.
  26834. * @returns {Function} Returns the new wrapped function.
  26835. */
  26836. function createCtor(Ctor) {
  26837. return function() {
  26838. // Use a `switch` statement to work with class constructors. See
  26839. // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  26840. // for more details.
  26841. var args = arguments;
  26842. switch (args.length) {
  26843. case 0: return new Ctor;
  26844. case 1: return new Ctor(args[0]);
  26845. case 2: return new Ctor(args[0], args[1]);
  26846. case 3: return new Ctor(args[0], args[1], args[2]);
  26847. case 4: return new Ctor(args[0], args[1], args[2], args[3]);
  26848. case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
  26849. case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
  26850. case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
  26851. }
  26852. var thisBinding = baseCreate(Ctor.prototype),
  26853. result = Ctor.apply(thisBinding, args);
  26854. // Mimic the constructor's `return` behavior.
  26855. // See https://es5.github.io/#x13.2.2 for more details.
  26856. return isObject(result) ? result : thisBinding;
  26857. };
  26858. }
  26859. /**
  26860. * Creates a function that wraps `func` to enable currying.
  26861. *
  26862. * @private
  26863. * @param {Function} func The function to wrap.
  26864. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  26865. * @param {number} arity The arity of `func`.
  26866. * @returns {Function} Returns the new wrapped function.
  26867. */
  26868. function createCurry(func, bitmask, arity) {
  26869. var Ctor = createCtor(func);
  26870. function wrapper() {
  26871. var length = arguments.length,
  26872. args = Array(length),
  26873. index = length,
  26874. placeholder = getHolder(wrapper);
  26875. while (index--) {
  26876. args[index] = arguments[index];
  26877. }
  26878. var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
  26879. ? []
  26880. : replaceHolders(args, placeholder);
  26881. length -= holders.length;
  26882. if (length < arity) {
  26883. return createRecurry(
  26884. func, bitmask, createHybrid, wrapper.placeholder, undefined,
  26885. args, holders, undefined, undefined, arity - length);
  26886. }
  26887. var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
  26888. return apply(fn, this, args);
  26889. }
  26890. return wrapper;
  26891. }
  26892. /**
  26893. * Creates a `_.find` or `_.findLast` function.
  26894. *
  26895. * @private
  26896. * @param {Function} findIndexFunc The function to find the collection index.
  26897. * @returns {Function} Returns the new find function.
  26898. */
  26899. function createFind(findIndexFunc) {
  26900. return function(collection, predicate, fromIndex) {
  26901. var iterable = Object(collection);
  26902. if (!isArrayLike(collection)) {
  26903. var iteratee = getIteratee(predicate, 3);
  26904. collection = keys(collection);
  26905. predicate = function(key) { return iteratee(iterable[key], key, iterable); };
  26906. }
  26907. var index = findIndexFunc(collection, predicate, fromIndex);
  26908. return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
  26909. };
  26910. }
  26911. /**
  26912. * Creates a `_.flow` or `_.flowRight` function.
  26913. *
  26914. * @private
  26915. * @param {boolean} [fromRight] Specify iterating from right to left.
  26916. * @returns {Function} Returns the new flow function.
  26917. */
  26918. function createFlow(fromRight) {
  26919. return flatRest(function(funcs) {
  26920. var length = funcs.length,
  26921. index = length,
  26922. prereq = LodashWrapper.prototype.thru;
  26923. if (fromRight) {
  26924. funcs.reverse();
  26925. }
  26926. while (index--) {
  26927. var func = funcs[index];
  26928. if (typeof func != 'function') {
  26929. throw new TypeError(FUNC_ERROR_TEXT);
  26930. }
  26931. if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
  26932. var wrapper = new LodashWrapper([], true);
  26933. }
  26934. }
  26935. index = wrapper ? index : length;
  26936. while (++index < length) {
  26937. func = funcs[index];
  26938. var funcName = getFuncName(func),
  26939. data = funcName == 'wrapper' ? getData(func) : undefined;
  26940. if (data && isLaziable(data[0]) &&
  26941. data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
  26942. !data[4].length && data[9] == 1
  26943. ) {
  26944. wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
  26945. } else {
  26946. wrapper = (func.length == 1 && isLaziable(func))
  26947. ? wrapper[funcName]()
  26948. : wrapper.thru(func);
  26949. }
  26950. }
  26951. return function() {
  26952. var args = arguments,
  26953. value = args[0];
  26954. if (wrapper && args.length == 1 && isArray(value)) {
  26955. return wrapper.plant(value).value();
  26956. }
  26957. var index = 0,
  26958. result = length ? funcs[index].apply(this, args) : value;
  26959. while (++index < length) {
  26960. result = funcs[index].call(this, result);
  26961. }
  26962. return result;
  26963. };
  26964. });
  26965. }
  26966. /**
  26967. * Creates a function that wraps `func` to invoke it with optional `this`
  26968. * binding of `thisArg`, partial application, and currying.
  26969. *
  26970. * @private
  26971. * @param {Function|string} func The function or method name to wrap.
  26972. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  26973. * @param {*} [thisArg] The `this` binding of `func`.
  26974. * @param {Array} [partials] The arguments to prepend to those provided to
  26975. * the new function.
  26976. * @param {Array} [holders] The `partials` placeholder indexes.
  26977. * @param {Array} [partialsRight] The arguments to append to those provided
  26978. * to the new function.
  26979. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
  26980. * @param {Array} [argPos] The argument positions of the new function.
  26981. * @param {number} [ary] The arity cap of `func`.
  26982. * @param {number} [arity] The arity of `func`.
  26983. * @returns {Function} Returns the new wrapped function.
  26984. */
  26985. function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  26986. var isAry = bitmask & WRAP_ARY_FLAG,
  26987. isBind = bitmask & WRAP_BIND_FLAG,
  26988. isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
  26989. isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
  26990. isFlip = bitmask & WRAP_FLIP_FLAG,
  26991. Ctor = isBindKey ? undefined : createCtor(func);
  26992. function wrapper() {
  26993. var length = arguments.length,
  26994. args = Array(length),
  26995. index = length;
  26996. while (index--) {
  26997. args[index] = arguments[index];
  26998. }
  26999. if (isCurried) {
  27000. var placeholder = getHolder(wrapper),
  27001. holdersCount = countHolders(args, placeholder);
  27002. }
  27003. if (partials) {
  27004. args = composeArgs(args, partials, holders, isCurried);
  27005. }
  27006. if (partialsRight) {
  27007. args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
  27008. }
  27009. length -= holdersCount;
  27010. if (isCurried && length < arity) {
  27011. var newHolders = replaceHolders(args, placeholder);
  27012. return createRecurry(
  27013. func, bitmask, createHybrid, wrapper.placeholder, thisArg,
  27014. args, newHolders, argPos, ary, arity - length
  27015. );
  27016. }
  27017. var thisBinding = isBind ? thisArg : this,
  27018. fn = isBindKey ? thisBinding[func] : func;
  27019. length = args.length;
  27020. if (argPos) {
  27021. args = reorder(args, argPos);
  27022. } else if (isFlip && length > 1) {
  27023. args.reverse();
  27024. }
  27025. if (isAry && ary < length) {
  27026. args.length = ary;
  27027. }
  27028. if (this && this !== root && this instanceof wrapper) {
  27029. fn = Ctor || createCtor(fn);
  27030. }
  27031. return fn.apply(thisBinding, args);
  27032. }
  27033. return wrapper;
  27034. }
  27035. /**
  27036. * Creates a function like `_.invertBy`.
  27037. *
  27038. * @private
  27039. * @param {Function} setter The function to set accumulator values.
  27040. * @param {Function} toIteratee The function to resolve iteratees.
  27041. * @returns {Function} Returns the new inverter function.
  27042. */
  27043. function createInverter(setter, toIteratee) {
  27044. return function(object, iteratee) {
  27045. return baseInverter(object, setter, toIteratee(iteratee), {});
  27046. };
  27047. }
  27048. /**
  27049. * Creates a function that performs a mathematical operation on two values.
  27050. *
  27051. * @private
  27052. * @param {Function} operator The function to perform the operation.
  27053. * @param {number} [defaultValue] The value used for `undefined` arguments.
  27054. * @returns {Function} Returns the new mathematical operation function.
  27055. */
  27056. function createMathOperation(operator, defaultValue) {
  27057. return function(value, other) {
  27058. var result;
  27059. if (value === undefined && other === undefined) {
  27060. return defaultValue;
  27061. }
  27062. if (value !== undefined) {
  27063. result = value;
  27064. }
  27065. if (other !== undefined) {
  27066. if (result === undefined) {
  27067. return other;
  27068. }
  27069. if (typeof value == 'string' || typeof other == 'string') {
  27070. value = baseToString(value);
  27071. other = baseToString(other);
  27072. } else {
  27073. value = baseToNumber(value);
  27074. other = baseToNumber(other);
  27075. }
  27076. result = operator(value, other);
  27077. }
  27078. return result;
  27079. };
  27080. }
  27081. /**
  27082. * Creates a function like `_.over`.
  27083. *
  27084. * @private
  27085. * @param {Function} arrayFunc The function to iterate over iteratees.
  27086. * @returns {Function} Returns the new over function.
  27087. */
  27088. function createOver(arrayFunc) {
  27089. return flatRest(function(iteratees) {
  27090. iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
  27091. return baseRest(function(args) {
  27092. var thisArg = this;
  27093. return arrayFunc(iteratees, function(iteratee) {
  27094. return apply(iteratee, thisArg, args);
  27095. });
  27096. });
  27097. });
  27098. }
  27099. /**
  27100. * Creates the padding for `string` based on `length`. The `chars` string
  27101. * is truncated if the number of characters exceeds `length`.
  27102. *
  27103. * @private
  27104. * @param {number} length The padding length.
  27105. * @param {string} [chars=' '] The string used as padding.
  27106. * @returns {string} Returns the padding for `string`.
  27107. */
  27108. function createPadding(length, chars) {
  27109. chars = chars === undefined ? ' ' : baseToString(chars);
  27110. var charsLength = chars.length;
  27111. if (charsLength < 2) {
  27112. return charsLength ? baseRepeat(chars, length) : chars;
  27113. }
  27114. var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
  27115. return hasUnicode(chars)
  27116. ? castSlice(stringToArray(result), 0, length).join('')
  27117. : result.slice(0, length);
  27118. }
  27119. /**
  27120. * Creates a function that wraps `func` to invoke it with the `this` binding
  27121. * of `thisArg` and `partials` prepended to the arguments it receives.
  27122. *
  27123. * @private
  27124. * @param {Function} func The function to wrap.
  27125. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  27126. * @param {*} thisArg The `this` binding of `func`.
  27127. * @param {Array} partials The arguments to prepend to those provided to
  27128. * the new function.
  27129. * @returns {Function} Returns the new wrapped function.
  27130. */
  27131. function createPartial(func, bitmask, thisArg, partials) {
  27132. var isBind = bitmask & WRAP_BIND_FLAG,
  27133. Ctor = createCtor(func);
  27134. function wrapper() {
  27135. var argsIndex = -1,
  27136. argsLength = arguments.length,
  27137. leftIndex = -1,
  27138. leftLength = partials.length,
  27139. args = Array(leftLength + argsLength),
  27140. fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
  27141. while (++leftIndex < leftLength) {
  27142. args[leftIndex] = partials[leftIndex];
  27143. }
  27144. while (argsLength--) {
  27145. args[leftIndex++] = arguments[++argsIndex];
  27146. }
  27147. return apply(fn, isBind ? thisArg : this, args);
  27148. }
  27149. return wrapper;
  27150. }
  27151. /**
  27152. * Creates a `_.range` or `_.rangeRight` function.
  27153. *
  27154. * @private
  27155. * @param {boolean} [fromRight] Specify iterating from right to left.
  27156. * @returns {Function} Returns the new range function.
  27157. */
  27158. function createRange(fromRight) {
  27159. return function(start, end, step) {
  27160. if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
  27161. end = step = undefined;
  27162. }
  27163. // Ensure the sign of `-0` is preserved.
  27164. start = toFinite(start);
  27165. if (end === undefined) {
  27166. end = start;
  27167. start = 0;
  27168. } else {
  27169. end = toFinite(end);
  27170. }
  27171. step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
  27172. return baseRange(start, end, step, fromRight);
  27173. };
  27174. }
  27175. /**
  27176. * Creates a function that performs a relational operation on two values.
  27177. *
  27178. * @private
  27179. * @param {Function} operator The function to perform the operation.
  27180. * @returns {Function} Returns the new relational operation function.
  27181. */
  27182. function createRelationalOperation(operator) {
  27183. return function(value, other) {
  27184. if (!(typeof value == 'string' && typeof other == 'string')) {
  27185. value = toNumber(value);
  27186. other = toNumber(other);
  27187. }
  27188. return operator(value, other);
  27189. };
  27190. }
  27191. /**
  27192. * Creates a function that wraps `func` to continue currying.
  27193. *
  27194. * @private
  27195. * @param {Function} func The function to wrap.
  27196. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  27197. * @param {Function} wrapFunc The function to create the `func` wrapper.
  27198. * @param {*} placeholder The placeholder value.
  27199. * @param {*} [thisArg] The `this` binding of `func`.
  27200. * @param {Array} [partials] The arguments to prepend to those provided to
  27201. * the new function.
  27202. * @param {Array} [holders] The `partials` placeholder indexes.
  27203. * @param {Array} [argPos] The argument positions of the new function.
  27204. * @param {number} [ary] The arity cap of `func`.
  27205. * @param {number} [arity] The arity of `func`.
  27206. * @returns {Function} Returns the new wrapped function.
  27207. */
  27208. function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
  27209. var isCurry = bitmask & WRAP_CURRY_FLAG,
  27210. newHolders = isCurry ? holders : undefined,
  27211. newHoldersRight = isCurry ? undefined : holders,
  27212. newPartials = isCurry ? partials : undefined,
  27213. newPartialsRight = isCurry ? undefined : partials;
  27214. bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
  27215. bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
  27216. if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
  27217. bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
  27218. }
  27219. var newData = [
  27220. func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
  27221. newHoldersRight, argPos, ary, arity
  27222. ];
  27223. var result = wrapFunc.apply(undefined, newData);
  27224. if (isLaziable(func)) {
  27225. setData(result, newData);
  27226. }
  27227. result.placeholder = placeholder;
  27228. return setWrapToString(result, func, bitmask);
  27229. }
  27230. /**
  27231. * Creates a function like `_.round`.
  27232. *
  27233. * @private
  27234. * @param {string} methodName The name of the `Math` method to use when rounding.
  27235. * @returns {Function} Returns the new round function.
  27236. */
  27237. function createRound(methodName) {
  27238. var func = Math[methodName];
  27239. return function(number, precision) {
  27240. number = toNumber(number);
  27241. precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
  27242. if (precision) {
  27243. // Shift with exponential notation to avoid floating-point issues.
  27244. // See [MDN](https://mdn.io/round#Examples) for more details.
  27245. var pair = (toString(number) + 'e').split('e'),
  27246. value = func(pair[0] + 'e' + (+pair[1] + precision));
  27247. pair = (toString(value) + 'e').split('e');
  27248. return +(pair[0] + 'e' + (+pair[1] - precision));
  27249. }
  27250. return func(number);
  27251. };
  27252. }
  27253. /**
  27254. * Creates a set object of `values`.
  27255. *
  27256. * @private
  27257. * @param {Array} values The values to add to the set.
  27258. * @returns {Object} Returns the new set.
  27259. */
  27260. var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
  27261. return new Set(values);
  27262. };
  27263. /**
  27264. * Creates a `_.toPairs` or `_.toPairsIn` function.
  27265. *
  27266. * @private
  27267. * @param {Function} keysFunc The function to get the keys of a given object.
  27268. * @returns {Function} Returns the new pairs function.
  27269. */
  27270. function createToPairs(keysFunc) {
  27271. return function(object) {
  27272. var tag = getTag(object);
  27273. if (tag == mapTag) {
  27274. return mapToArray(object);
  27275. }
  27276. if (tag == setTag) {
  27277. return setToPairs(object);
  27278. }
  27279. return baseToPairs(object, keysFunc(object));
  27280. };
  27281. }
  27282. /**
  27283. * Creates a function that either curries or invokes `func` with optional
  27284. * `this` binding and partially applied arguments.
  27285. *
  27286. * @private
  27287. * @param {Function|string} func The function or method name to wrap.
  27288. * @param {number} bitmask The bitmask flags.
  27289. * 1 - `_.bind`
  27290. * 2 - `_.bindKey`
  27291. * 4 - `_.curry` or `_.curryRight` of a bound function
  27292. * 8 - `_.curry`
  27293. * 16 - `_.curryRight`
  27294. * 32 - `_.partial`
  27295. * 64 - `_.partialRight`
  27296. * 128 - `_.rearg`
  27297. * 256 - `_.ary`
  27298. * 512 - `_.flip`
  27299. * @param {*} [thisArg] The `this` binding of `func`.
  27300. * @param {Array} [partials] The arguments to be partially applied.
  27301. * @param {Array} [holders] The `partials` placeholder indexes.
  27302. * @param {Array} [argPos] The argument positions of the new function.
  27303. * @param {number} [ary] The arity cap of `func`.
  27304. * @param {number} [arity] The arity of `func`.
  27305. * @returns {Function} Returns the new wrapped function.
  27306. */
  27307. function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  27308. var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
  27309. if (!isBindKey && typeof func != 'function') {
  27310. throw new TypeError(FUNC_ERROR_TEXT);
  27311. }
  27312. var length = partials ? partials.length : 0;
  27313. if (!length) {
  27314. bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
  27315. partials = holders = undefined;
  27316. }
  27317. ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
  27318. arity = arity === undefined ? arity : toInteger(arity);
  27319. length -= holders ? holders.length : 0;
  27320. if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
  27321. var partialsRight = partials,
  27322. holdersRight = holders;
  27323. partials = holders = undefined;
  27324. }
  27325. var data = isBindKey ? undefined : getData(func);
  27326. var newData = [
  27327. func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
  27328. argPos, ary, arity
  27329. ];
  27330. if (data) {
  27331. mergeData(newData, data);
  27332. }
  27333. func = newData[0];
  27334. bitmask = newData[1];
  27335. thisArg = newData[2];
  27336. partials = newData[3];
  27337. holders = newData[4];
  27338. arity = newData[9] = newData[9] === undefined
  27339. ? (isBindKey ? 0 : func.length)
  27340. : nativeMax(newData[9] - length, 0);
  27341. if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
  27342. bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
  27343. }
  27344. if (!bitmask || bitmask == WRAP_BIND_FLAG) {
  27345. var result = createBind(func, bitmask, thisArg);
  27346. } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
  27347. result = createCurry(func, bitmask, arity);
  27348. } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
  27349. result = createPartial(func, bitmask, thisArg, partials);
  27350. } else {
  27351. result = createHybrid.apply(undefined, newData);
  27352. }
  27353. var setter = data ? baseSetData : setData;
  27354. return setWrapToString(setter(result, newData), func, bitmask);
  27355. }
  27356. /**
  27357. * Used by `_.defaults` to customize its `_.assignIn` use to assign properties
  27358. * of source objects to the destination object for all destination properties
  27359. * that resolve to `undefined`.
  27360. *
  27361. * @private
  27362. * @param {*} objValue The destination value.
  27363. * @param {*} srcValue The source value.
  27364. * @param {string} key The key of the property to assign.
  27365. * @param {Object} object The parent object of `objValue`.
  27366. * @returns {*} Returns the value to assign.
  27367. */
  27368. function customDefaultsAssignIn(objValue, srcValue, key, object) {
  27369. if (objValue === undefined ||
  27370. (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
  27371. return srcValue;
  27372. }
  27373. return objValue;
  27374. }
  27375. /**
  27376. * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
  27377. * objects into destination objects that are passed thru.
  27378. *
  27379. * @private
  27380. * @param {*} objValue The destination value.
  27381. * @param {*} srcValue The source value.
  27382. * @param {string} key The key of the property to merge.
  27383. * @param {Object} object The parent object of `objValue`.
  27384. * @param {Object} source The parent object of `srcValue`.
  27385. * @param {Object} [stack] Tracks traversed source values and their merged
  27386. * counterparts.
  27387. * @returns {*} Returns the value to assign.
  27388. */
  27389. function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
  27390. if (isObject(objValue) && isObject(srcValue)) {
  27391. // Recursively merge objects and arrays (susceptible to call stack limits).
  27392. stack.set(srcValue, objValue);
  27393. baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
  27394. stack['delete'](srcValue);
  27395. }
  27396. return objValue;
  27397. }
  27398. /**
  27399. * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
  27400. * objects.
  27401. *
  27402. * @private
  27403. * @param {*} value The value to inspect.
  27404. * @param {string} key The key of the property to inspect.
  27405. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
  27406. */
  27407. function customOmitClone(value) {
  27408. return isPlainObject(value) ? undefined : value;
  27409. }
  27410. /**
  27411. * A specialized version of `baseIsEqualDeep` for arrays with support for
  27412. * partial deep comparisons.
  27413. *
  27414. * @private
  27415. * @param {Array} array The array to compare.
  27416. * @param {Array} other The other array to compare.
  27417. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  27418. * @param {Function} customizer The function to customize comparisons.
  27419. * @param {Function} equalFunc The function to determine equivalents of values.
  27420. * @param {Object} stack Tracks traversed `array` and `other` objects.
  27421. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  27422. */
  27423. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  27424. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  27425. arrLength = array.length,
  27426. othLength = other.length;
  27427. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  27428. return false;
  27429. }
  27430. // Assume cyclic values are equal.
  27431. var stacked = stack.get(array);
  27432. if (stacked && stack.get(other)) {
  27433. return stacked == other;
  27434. }
  27435. var index = -1,
  27436. result = true,
  27437. seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
  27438. stack.set(array, other);
  27439. stack.set(other, array);
  27440. // Ignore non-index properties.
  27441. while (++index < arrLength) {
  27442. var arrValue = array[index],
  27443. othValue = other[index];
  27444. if (customizer) {
  27445. var compared = isPartial
  27446. ? customizer(othValue, arrValue, index, other, array, stack)
  27447. : customizer(arrValue, othValue, index, array, other, stack);
  27448. }
  27449. if (compared !== undefined) {
  27450. if (compared) {
  27451. continue;
  27452. }
  27453. result = false;
  27454. break;
  27455. }
  27456. // Recursively compare arrays (susceptible to call stack limits).
  27457. if (seen) {
  27458. if (!arraySome(other, function(othValue, othIndex) {
  27459. if (!cacheHas(seen, othIndex) &&
  27460. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  27461. return seen.push(othIndex);
  27462. }
  27463. })) {
  27464. result = false;
  27465. break;
  27466. }
  27467. } else if (!(
  27468. arrValue === othValue ||
  27469. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  27470. )) {
  27471. result = false;
  27472. break;
  27473. }
  27474. }
  27475. stack['delete'](array);
  27476. stack['delete'](other);
  27477. return result;
  27478. }
  27479. /**
  27480. * A specialized version of `baseIsEqualDeep` for comparing objects of
  27481. * the same `toStringTag`.
  27482. *
  27483. * **Note:** This function only supports comparing values with tags of
  27484. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  27485. *
  27486. * @private
  27487. * @param {Object} object The object to compare.
  27488. * @param {Object} other The other object to compare.
  27489. * @param {string} tag The `toStringTag` of the objects to compare.
  27490. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  27491. * @param {Function} customizer The function to customize comparisons.
  27492. * @param {Function} equalFunc The function to determine equivalents of values.
  27493. * @param {Object} stack Tracks traversed `object` and `other` objects.
  27494. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  27495. */
  27496. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  27497. switch (tag) {
  27498. case dataViewTag:
  27499. if ((object.byteLength != other.byteLength) ||
  27500. (object.byteOffset != other.byteOffset)) {
  27501. return false;
  27502. }
  27503. object = object.buffer;
  27504. other = other.buffer;
  27505. case arrayBufferTag:
  27506. if ((object.byteLength != other.byteLength) ||
  27507. !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
  27508. return false;
  27509. }
  27510. return true;
  27511. case boolTag:
  27512. case dateTag:
  27513. case numberTag:
  27514. // Coerce booleans to `1` or `0` and dates to milliseconds.
  27515. // Invalid dates are coerced to `NaN`.
  27516. return eq(+object, +other);
  27517. case errorTag:
  27518. return object.name == other.name && object.message == other.message;
  27519. case regexpTag:
  27520. case stringTag:
  27521. // Coerce regexes to strings and treat strings, primitives and objects,
  27522. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  27523. // for more details.
  27524. return object == (other + '');
  27525. case mapTag:
  27526. var convert = mapToArray;
  27527. case setTag:
  27528. var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
  27529. convert || (convert = setToArray);
  27530. if (object.size != other.size && !isPartial) {
  27531. return false;
  27532. }
  27533. // Assume cyclic values are equal.
  27534. var stacked = stack.get(object);
  27535. if (stacked) {
  27536. return stacked == other;
  27537. }
  27538. bitmask |= COMPARE_UNORDERED_FLAG;
  27539. // Recursively compare objects (susceptible to call stack limits).
  27540. stack.set(object, other);
  27541. var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  27542. stack['delete'](object);
  27543. return result;
  27544. case symbolTag:
  27545. if (symbolValueOf) {
  27546. return symbolValueOf.call(object) == symbolValueOf.call(other);
  27547. }
  27548. }
  27549. return false;
  27550. }
  27551. /**
  27552. * A specialized version of `baseIsEqualDeep` for objects with support for
  27553. * partial deep comparisons.
  27554. *
  27555. * @private
  27556. * @param {Object} object The object to compare.
  27557. * @param {Object} other The other object to compare.
  27558. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  27559. * @param {Function} customizer The function to customize comparisons.
  27560. * @param {Function} equalFunc The function to determine equivalents of values.
  27561. * @param {Object} stack Tracks traversed `object` and `other` objects.
  27562. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  27563. */
  27564. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  27565. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  27566. objProps = getAllKeys(object),
  27567. objLength = objProps.length,
  27568. othProps = getAllKeys(other),
  27569. othLength = othProps.length;
  27570. if (objLength != othLength && !isPartial) {
  27571. return false;
  27572. }
  27573. var index = objLength;
  27574. while (index--) {
  27575. var key = objProps[index];
  27576. if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
  27577. return false;
  27578. }
  27579. }
  27580. // Assume cyclic values are equal.
  27581. var stacked = stack.get(object);
  27582. if (stacked && stack.get(other)) {
  27583. return stacked == other;
  27584. }
  27585. var result = true;
  27586. stack.set(object, other);
  27587. stack.set(other, object);
  27588. var skipCtor = isPartial;
  27589. while (++index < objLength) {
  27590. key = objProps[index];
  27591. var objValue = object[key],
  27592. othValue = other[key];
  27593. if (customizer) {
  27594. var compared = isPartial
  27595. ? customizer(othValue, objValue, key, other, object, stack)
  27596. : customizer(objValue, othValue, key, object, other, stack);
  27597. }
  27598. // Recursively compare objects (susceptible to call stack limits).
  27599. if (!(compared === undefined
  27600. ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
  27601. : compared
  27602. )) {
  27603. result = false;
  27604. break;
  27605. }
  27606. skipCtor || (skipCtor = key == 'constructor');
  27607. }
  27608. if (result && !skipCtor) {
  27609. var objCtor = object.constructor,
  27610. othCtor = other.constructor;
  27611. // Non `Object` object instances with different constructors are not equal.
  27612. if (objCtor != othCtor &&
  27613. ('constructor' in object && 'constructor' in other) &&
  27614. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  27615. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  27616. result = false;
  27617. }
  27618. }
  27619. stack['delete'](object);
  27620. stack['delete'](other);
  27621. return result;
  27622. }
  27623. /**
  27624. * A specialized version of `baseRest` which flattens the rest array.
  27625. *
  27626. * @private
  27627. * @param {Function} func The function to apply a rest parameter to.
  27628. * @returns {Function} Returns the new function.
  27629. */
  27630. function flatRest(func) {
  27631. return setToString(overRest(func, undefined, flatten), func + '');
  27632. }
  27633. /**
  27634. * Creates an array of own enumerable property names and symbols of `object`.
  27635. *
  27636. * @private
  27637. * @param {Object} object The object to query.
  27638. * @returns {Array} Returns the array of property names and symbols.
  27639. */
  27640. function getAllKeys(object) {
  27641. return baseGetAllKeys(object, keys, getSymbols);
  27642. }
  27643. /**
  27644. * Creates an array of own and inherited enumerable property names and
  27645. * symbols of `object`.
  27646. *
  27647. * @private
  27648. * @param {Object} object The object to query.
  27649. * @returns {Array} Returns the array of property names and symbols.
  27650. */
  27651. function getAllKeysIn(object) {
  27652. return baseGetAllKeys(object, keysIn, getSymbolsIn);
  27653. }
  27654. /**
  27655. * Gets metadata for `func`.
  27656. *
  27657. * @private
  27658. * @param {Function} func The function to query.
  27659. * @returns {*} Returns the metadata for `func`.
  27660. */
  27661. var getData = !metaMap ? noop : function(func) {
  27662. return metaMap.get(func);
  27663. };
  27664. /**
  27665. * Gets the name of `func`.
  27666. *
  27667. * @private
  27668. * @param {Function} func The function to query.
  27669. * @returns {string} Returns the function name.
  27670. */
  27671. function getFuncName(func) {
  27672. var result = (func.name + ''),
  27673. array = realNames[result],
  27674. length = hasOwnProperty.call(realNames, result) ? array.length : 0;
  27675. while (length--) {
  27676. var data = array[length],
  27677. otherFunc = data.func;
  27678. if (otherFunc == null || otherFunc == func) {
  27679. return data.name;
  27680. }
  27681. }
  27682. return result;
  27683. }
  27684. /**
  27685. * Gets the argument placeholder value for `func`.
  27686. *
  27687. * @private
  27688. * @param {Function} func The function to inspect.
  27689. * @returns {*} Returns the placeholder value.
  27690. */
  27691. function getHolder(func) {
  27692. var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
  27693. return object.placeholder;
  27694. }
  27695. /**
  27696. * Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
  27697. * this function returns the custom method, otherwise it returns `baseIteratee`.
  27698. * If arguments are provided, the chosen function is invoked with them and
  27699. * its result is returned.
  27700. *
  27701. * @private
  27702. * @param {*} [value] The value to convert to an iteratee.
  27703. * @param {number} [arity] The arity of the created iteratee.
  27704. * @returns {Function} Returns the chosen function or its result.
  27705. */
  27706. function getIteratee() {
  27707. var result = lodash.iteratee || iteratee;
  27708. result = result === iteratee ? baseIteratee : result;
  27709. return arguments.length ? result(arguments[0], arguments[1]) : result;
  27710. }
  27711. /**
  27712. * Gets the data for `map`.
  27713. *
  27714. * @private
  27715. * @param {Object} map The map to query.
  27716. * @param {string} key The reference key.
  27717. * @returns {*} Returns the map data.
  27718. */
  27719. function getMapData(map, key) {
  27720. var data = map.__data__;
  27721. return isKeyable(key)
  27722. ? data[typeof key == 'string' ? 'string' : 'hash']
  27723. : data.map;
  27724. }
  27725. /**
  27726. * Gets the property names, values, and compare flags of `object`.
  27727. *
  27728. * @private
  27729. * @param {Object} object The object to query.
  27730. * @returns {Array} Returns the match data of `object`.
  27731. */
  27732. function getMatchData(object) {
  27733. var result = keys(object),
  27734. length = result.length;
  27735. while (length--) {
  27736. var key = result[length],
  27737. value = object[key];
  27738. result[length] = [key, value, isStrictComparable(value)];
  27739. }
  27740. return result;
  27741. }
  27742. /**
  27743. * Gets the native function at `key` of `object`.
  27744. *
  27745. * @private
  27746. * @param {Object} object The object to query.
  27747. * @param {string} key The key of the method to get.
  27748. * @returns {*} Returns the function if it's native, else `undefined`.
  27749. */
  27750. function getNative(object, key) {
  27751. var value = getValue(object, key);
  27752. return baseIsNative(value) ? value : undefined;
  27753. }
  27754. /**
  27755. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  27756. *
  27757. * @private
  27758. * @param {*} value The value to query.
  27759. * @returns {string} Returns the raw `toStringTag`.
  27760. */
  27761. function getRawTag(value) {
  27762. var isOwn = hasOwnProperty.call(value, symToStringTag),
  27763. tag = value[symToStringTag];
  27764. try {
  27765. value[symToStringTag] = undefined;
  27766. var unmasked = true;
  27767. } catch (e) {}
  27768. var result = nativeObjectToString.call(value);
  27769. if (unmasked) {
  27770. if (isOwn) {
  27771. value[symToStringTag] = tag;
  27772. } else {
  27773. delete value[symToStringTag];
  27774. }
  27775. }
  27776. return result;
  27777. }
  27778. /**
  27779. * Creates an array of the own enumerable symbols of `object`.
  27780. *
  27781. * @private
  27782. * @param {Object} object The object to query.
  27783. * @returns {Array} Returns the array of symbols.
  27784. */
  27785. var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
  27786. if (object == null) {
  27787. return [];
  27788. }
  27789. object = Object(object);
  27790. return arrayFilter(nativeGetSymbols(object), function(symbol) {
  27791. return propertyIsEnumerable.call(object, symbol);
  27792. });
  27793. };
  27794. /**
  27795. * Creates an array of the own and inherited enumerable symbols of `object`.
  27796. *
  27797. * @private
  27798. * @param {Object} object The object to query.
  27799. * @returns {Array} Returns the array of symbols.
  27800. */
  27801. var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
  27802. var result = [];
  27803. while (object) {
  27804. arrayPush(result, getSymbols(object));
  27805. object = getPrototype(object);
  27806. }
  27807. return result;
  27808. };
  27809. /**
  27810. * Gets the `toStringTag` of `value`.
  27811. *
  27812. * @private
  27813. * @param {*} value The value to query.
  27814. * @returns {string} Returns the `toStringTag`.
  27815. */
  27816. var getTag = baseGetTag;
  27817. // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  27818. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
  27819. (Map && getTag(new Map) != mapTag) ||
  27820. (Promise && getTag(Promise.resolve()) != promiseTag) ||
  27821. (Set && getTag(new Set) != setTag) ||
  27822. (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  27823. getTag = function(value) {
  27824. var result = baseGetTag(value),
  27825. Ctor = result == objectTag ? value.constructor : undefined,
  27826. ctorString = Ctor ? toSource(Ctor) : '';
  27827. if (ctorString) {
  27828. switch (ctorString) {
  27829. case dataViewCtorString: return dataViewTag;
  27830. case mapCtorString: return mapTag;
  27831. case promiseCtorString: return promiseTag;
  27832. case setCtorString: return setTag;
  27833. case weakMapCtorString: return weakMapTag;
  27834. }
  27835. }
  27836. return result;
  27837. };
  27838. }
  27839. /**
  27840. * Gets the view, applying any `transforms` to the `start` and `end` positions.
  27841. *
  27842. * @private
  27843. * @param {number} start The start of the view.
  27844. * @param {number} end The end of the view.
  27845. * @param {Array} transforms The transformations to apply to the view.
  27846. * @returns {Object} Returns an object containing the `start` and `end`
  27847. * positions of the view.
  27848. */
  27849. function getView(start, end, transforms) {
  27850. var index = -1,
  27851. length = transforms.length;
  27852. while (++index < length) {
  27853. var data = transforms[index],
  27854. size = data.size;
  27855. switch (data.type) {
  27856. case 'drop': start += size; break;
  27857. case 'dropRight': end -= size; break;
  27858. case 'take': end = nativeMin(end, start + size); break;
  27859. case 'takeRight': start = nativeMax(start, end - size); break;
  27860. }
  27861. }
  27862. return { 'start': start, 'end': end };
  27863. }
  27864. /**
  27865. * Extracts wrapper details from the `source` body comment.
  27866. *
  27867. * @private
  27868. * @param {string} source The source to inspect.
  27869. * @returns {Array} Returns the wrapper details.
  27870. */
  27871. function getWrapDetails(source) {
  27872. var match = source.match(reWrapDetails);
  27873. return match ? match[1].split(reSplitDetails) : [];
  27874. }
  27875. /**
  27876. * Checks if `path` exists on `object`.
  27877. *
  27878. * @private
  27879. * @param {Object} object The object to query.
  27880. * @param {Array|string} path The path to check.
  27881. * @param {Function} hasFunc The function to check properties.
  27882. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  27883. */
  27884. function hasPath(object, path, hasFunc) {
  27885. path = castPath(path, object);
  27886. var index = -1,
  27887. length = path.length,
  27888. result = false;
  27889. while (++index < length) {
  27890. var key = toKey(path[index]);
  27891. if (!(result = object != null && hasFunc(object, key))) {
  27892. break;
  27893. }
  27894. object = object[key];
  27895. }
  27896. if (result || ++index != length) {
  27897. return result;
  27898. }
  27899. length = object == null ? 0 : object.length;
  27900. return !!length && isLength(length) && isIndex(key, length) &&
  27901. (isArray(object) || isArguments(object));
  27902. }
  27903. /**
  27904. * Initializes an array clone.
  27905. *
  27906. * @private
  27907. * @param {Array} array The array to clone.
  27908. * @returns {Array} Returns the initialized clone.
  27909. */
  27910. function initCloneArray(array) {
  27911. var length = array.length,
  27912. result = array.constructor(length);
  27913. // Add properties assigned by `RegExp#exec`.
  27914. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
  27915. result.index = array.index;
  27916. result.input = array.input;
  27917. }
  27918. return result;
  27919. }
  27920. /**
  27921. * Initializes an object clone.
  27922. *
  27923. * @private
  27924. * @param {Object} object The object to clone.
  27925. * @returns {Object} Returns the initialized clone.
  27926. */
  27927. function initCloneObject(object) {
  27928. return (typeof object.constructor == 'function' && !isPrototype(object))
  27929. ? baseCreate(getPrototype(object))
  27930. : {};
  27931. }
  27932. /**
  27933. * Initializes an object clone based on its `toStringTag`.
  27934. *
  27935. * **Note:** This function only supports cloning values with tags of
  27936. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  27937. *
  27938. * @private
  27939. * @param {Object} object The object to clone.
  27940. * @param {string} tag The `toStringTag` of the object to clone.
  27941. * @param {Function} cloneFunc The function to clone values.
  27942. * @param {boolean} [isDeep] Specify a deep clone.
  27943. * @returns {Object} Returns the initialized clone.
  27944. */
  27945. function initCloneByTag(object, tag, cloneFunc, isDeep) {
  27946. var Ctor = object.constructor;
  27947. switch (tag) {
  27948. case arrayBufferTag:
  27949. return cloneArrayBuffer(object);
  27950. case boolTag:
  27951. case dateTag:
  27952. return new Ctor(+object);
  27953. case dataViewTag:
  27954. return cloneDataView(object, isDeep);
  27955. case float32Tag: case float64Tag:
  27956. case int8Tag: case int16Tag: case int32Tag:
  27957. case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
  27958. return cloneTypedArray(object, isDeep);
  27959. case mapTag:
  27960. return cloneMap(object, isDeep, cloneFunc);
  27961. case numberTag:
  27962. case stringTag:
  27963. return new Ctor(object);
  27964. case regexpTag:
  27965. return cloneRegExp(object);
  27966. case setTag:
  27967. return cloneSet(object, isDeep, cloneFunc);
  27968. case symbolTag:
  27969. return cloneSymbol(object);
  27970. }
  27971. }
  27972. /**
  27973. * Inserts wrapper `details` in a comment at the top of the `source` body.
  27974. *
  27975. * @private
  27976. * @param {string} source The source to modify.
  27977. * @returns {Array} details The details to insert.
  27978. * @returns {string} Returns the modified source.
  27979. */
  27980. function insertWrapDetails(source, details) {
  27981. var length = details.length;
  27982. if (!length) {
  27983. return source;
  27984. }
  27985. var lastIndex = length - 1;
  27986. details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
  27987. details = details.join(length > 2 ? ', ' : ' ');
  27988. return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
  27989. }
  27990. /**
  27991. * Checks if `value` is a flattenable `arguments` object or array.
  27992. *
  27993. * @private
  27994. * @param {*} value The value to check.
  27995. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
  27996. */
  27997. function isFlattenable(value) {
  27998. return isArray(value) || isArguments(value) ||
  27999. !!(spreadableSymbol && value && value[spreadableSymbol]);
  28000. }
  28001. /**
  28002. * Checks if `value` is a valid array-like index.
  28003. *
  28004. * @private
  28005. * @param {*} value The value to check.
  28006. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  28007. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  28008. */
  28009. function isIndex(value, length) {
  28010. length = length == null ? MAX_SAFE_INTEGER : length;
  28011. return !!length &&
  28012. (typeof value == 'number' || reIsUint.test(value)) &&
  28013. (value > -1 && value % 1 == 0 && value < length);
  28014. }
  28015. /**
  28016. * Checks if the given arguments are from an iteratee call.
  28017. *
  28018. * @private
  28019. * @param {*} value The potential iteratee value argument.
  28020. * @param {*} index The potential iteratee index or key argument.
  28021. * @param {*} object The potential iteratee object argument.
  28022. * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
  28023. * else `false`.
  28024. */
  28025. function isIterateeCall(value, index, object) {
  28026. if (!isObject(object)) {
  28027. return false;
  28028. }
  28029. var type = typeof index;
  28030. if (type == 'number'
  28031. ? (isArrayLike(object) && isIndex(index, object.length))
  28032. : (type == 'string' && index in object)
  28033. ) {
  28034. return eq(object[index], value);
  28035. }
  28036. return false;
  28037. }
  28038. /**
  28039. * Checks if `value` is a property name and not a property path.
  28040. *
  28041. * @private
  28042. * @param {*} value The value to check.
  28043. * @param {Object} [object] The object to query keys on.
  28044. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  28045. */
  28046. function isKey(value, object) {
  28047. if (isArray(value)) {
  28048. return false;
  28049. }
  28050. var type = typeof value;
  28051. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  28052. value == null || isSymbol(value)) {
  28053. return true;
  28054. }
  28055. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  28056. (object != null && value in Object(object));
  28057. }
  28058. /**
  28059. * Checks if `value` is suitable for use as unique object key.
  28060. *
  28061. * @private
  28062. * @param {*} value The value to check.
  28063. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  28064. */
  28065. function isKeyable(value) {
  28066. var type = typeof value;
  28067. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  28068. ? (value !== '__proto__')
  28069. : (value === null);
  28070. }
  28071. /**
  28072. * Checks if `func` has a lazy counterpart.
  28073. *
  28074. * @private
  28075. * @param {Function} func The function to check.
  28076. * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
  28077. * else `false`.
  28078. */
  28079. function isLaziable(func) {
  28080. var funcName = getFuncName(func),
  28081. other = lodash[funcName];
  28082. if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
  28083. return false;
  28084. }
  28085. if (func === other) {
  28086. return true;
  28087. }
  28088. var data = getData(other);
  28089. return !!data && func === data[0];
  28090. }
  28091. /**
  28092. * Checks if `func` has its source masked.
  28093. *
  28094. * @private
  28095. * @param {Function} func The function to check.
  28096. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  28097. */
  28098. function isMasked(func) {
  28099. return !!maskSrcKey && (maskSrcKey in func);
  28100. }
  28101. /**
  28102. * Checks if `func` is capable of being masked.
  28103. *
  28104. * @private
  28105. * @param {*} value The value to check.
  28106. * @returns {boolean} Returns `true` if `func` is maskable, else `false`.
  28107. */
  28108. var isMaskable = coreJsData ? isFunction : stubFalse;
  28109. /**
  28110. * Checks if `value` is likely a prototype object.
  28111. *
  28112. * @private
  28113. * @param {*} value The value to check.
  28114. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  28115. */
  28116. function isPrototype(value) {
  28117. var Ctor = value && value.constructor,
  28118. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
  28119. return value === proto;
  28120. }
  28121. /**
  28122. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  28123. *
  28124. * @private
  28125. * @param {*} value The value to check.
  28126. * @returns {boolean} Returns `true` if `value` if suitable for strict
  28127. * equality comparisons, else `false`.
  28128. */
  28129. function isStrictComparable(value) {
  28130. return value === value && !isObject(value);
  28131. }
  28132. /**
  28133. * A specialized version of `matchesProperty` for source values suitable
  28134. * for strict equality comparisons, i.e. `===`.
  28135. *
  28136. * @private
  28137. * @param {string} key The key of the property to get.
  28138. * @param {*} srcValue The value to match.
  28139. * @returns {Function} Returns the new spec function.
  28140. */
  28141. function matchesStrictComparable(key, srcValue) {
  28142. return function(object) {
  28143. if (object == null) {
  28144. return false;
  28145. }
  28146. return object[key] === srcValue &&
  28147. (srcValue !== undefined || (key in Object(object)));
  28148. };
  28149. }
  28150. /**
  28151. * A specialized version of `_.memoize` which clears the memoized function's
  28152. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  28153. *
  28154. * @private
  28155. * @param {Function} func The function to have its output memoized.
  28156. * @returns {Function} Returns the new memoized function.
  28157. */
  28158. function memoizeCapped(func) {
  28159. var result = memoize(func, function(key) {
  28160. if (cache.size === MAX_MEMOIZE_SIZE) {
  28161. cache.clear();
  28162. }
  28163. return key;
  28164. });
  28165. var cache = result.cache;
  28166. return result;
  28167. }
  28168. /**
  28169. * Merges the function metadata of `source` into `data`.
  28170. *
  28171. * Merging metadata reduces the number of wrappers used to invoke a function.
  28172. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
  28173. * may be applied regardless of execution order. Methods like `_.ary` and
  28174. * `_.rearg` modify function arguments, making the order in which they are
  28175. * executed important, preventing the merging of metadata. However, we make
  28176. * an exception for a safe combined case where curried functions have `_.ary`
  28177. * and or `_.rearg` applied.
  28178. *
  28179. * @private
  28180. * @param {Array} data The destination metadata.
  28181. * @param {Array} source The source metadata.
  28182. * @returns {Array} Returns `data`.
  28183. */
  28184. function mergeData(data, source) {
  28185. var bitmask = data[1],
  28186. srcBitmask = source[1],
  28187. newBitmask = bitmask | srcBitmask,
  28188. isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
  28189. var isCombo =
  28190. ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
  28191. ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
  28192. ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
  28193. // Exit early if metadata can't be merged.
  28194. if (!(isCommon || isCombo)) {
  28195. return data;
  28196. }
  28197. // Use source `thisArg` if available.
  28198. if (srcBitmask & WRAP_BIND_FLAG) {
  28199. data[2] = source[2];
  28200. // Set when currying a bound function.
  28201. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
  28202. }
  28203. // Compose partial arguments.
  28204. var value = source[3];
  28205. if (value) {
  28206. var partials = data[3];
  28207. data[3] = partials ? composeArgs(partials, value, source[4]) : value;
  28208. data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
  28209. }
  28210. // Compose partial right arguments.
  28211. value = source[5];
  28212. if (value) {
  28213. partials = data[5];
  28214. data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
  28215. data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
  28216. }
  28217. // Use source `argPos` if available.
  28218. value = source[7];
  28219. if (value) {
  28220. data[7] = value;
  28221. }
  28222. // Use source `ary` if it's smaller.
  28223. if (srcBitmask & WRAP_ARY_FLAG) {
  28224. data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
  28225. }
  28226. // Use source `arity` if one is not provided.
  28227. if (data[9] == null) {
  28228. data[9] = source[9];
  28229. }
  28230. // Use source `func` and merge bitmasks.
  28231. data[0] = source[0];
  28232. data[1] = newBitmask;
  28233. return data;
  28234. }
  28235. /**
  28236. * This function is like
  28237. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  28238. * except that it includes inherited enumerable properties.
  28239. *
  28240. * @private
  28241. * @param {Object} object The object to query.
  28242. * @returns {Array} Returns the array of property names.
  28243. */
  28244. function nativeKeysIn(object) {
  28245. var result = [];
  28246. if (object != null) {
  28247. for (var key in Object(object)) {
  28248. result.push(key);
  28249. }
  28250. }
  28251. return result;
  28252. }
  28253. /**
  28254. * Converts `value` to a string using `Object.prototype.toString`.
  28255. *
  28256. * @private
  28257. * @param {*} value The value to convert.
  28258. * @returns {string} Returns the converted string.
  28259. */
  28260. function objectToString(value) {
  28261. return nativeObjectToString.call(value);
  28262. }
  28263. /**
  28264. * A specialized version of `baseRest` which transforms the rest array.
  28265. *
  28266. * @private
  28267. * @param {Function} func The function to apply a rest parameter to.
  28268. * @param {number} [start=func.length-1] The start position of the rest parameter.
  28269. * @param {Function} transform The rest array transform.
  28270. * @returns {Function} Returns the new function.
  28271. */
  28272. function overRest(func, start, transform) {
  28273. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  28274. return function() {
  28275. var args = arguments,
  28276. index = -1,
  28277. length = nativeMax(args.length - start, 0),
  28278. array = Array(length);
  28279. while (++index < length) {
  28280. array[index] = args[start + index];
  28281. }
  28282. index = -1;
  28283. var otherArgs = Array(start + 1);
  28284. while (++index < start) {
  28285. otherArgs[index] = args[index];
  28286. }
  28287. otherArgs[start] = transform(array);
  28288. return apply(func, this, otherArgs);
  28289. };
  28290. }
  28291. /**
  28292. * Gets the parent value at `path` of `object`.
  28293. *
  28294. * @private
  28295. * @param {Object} object The object to query.
  28296. * @param {Array} path The path to get the parent value of.
  28297. * @returns {*} Returns the parent value.
  28298. */
  28299. function parent(object, path) {
  28300. return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
  28301. }
  28302. /**
  28303. * Reorder `array` according to the specified indexes where the element at
  28304. * the first index is assigned as the first element, the element at
  28305. * the second index is assigned as the second element, and so on.
  28306. *
  28307. * @private
  28308. * @param {Array} array The array to reorder.
  28309. * @param {Array} indexes The arranged array indexes.
  28310. * @returns {Array} Returns `array`.
  28311. */
  28312. function reorder(array, indexes) {
  28313. var arrLength = array.length,
  28314. length = nativeMin(indexes.length, arrLength),
  28315. oldArray = copyArray(array);
  28316. while (length--) {
  28317. var index = indexes[length];
  28318. array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
  28319. }
  28320. return array;
  28321. }
  28322. /**
  28323. * Sets metadata for `func`.
  28324. *
  28325. * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
  28326. * period of time, it will trip its breaker and transition to an identity
  28327. * function to avoid garbage collection pauses in V8. See
  28328. * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
  28329. * for more details.
  28330. *
  28331. * @private
  28332. * @param {Function} func The function to associate metadata with.
  28333. * @param {*} data The metadata.
  28334. * @returns {Function} Returns `func`.
  28335. */
  28336. var setData = shortOut(baseSetData);
  28337. /**
  28338. * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
  28339. *
  28340. * @private
  28341. * @param {Function} func The function to delay.
  28342. * @param {number} wait The number of milliseconds to delay invocation.
  28343. * @returns {number|Object} Returns the timer id or timeout object.
  28344. */
  28345. var setTimeout = ctxSetTimeout || function(func, wait) {
  28346. return root.setTimeout(func, wait);
  28347. };
  28348. /**
  28349. * Sets the `toString` method of `func` to return `string`.
  28350. *
  28351. * @private
  28352. * @param {Function} func The function to modify.
  28353. * @param {Function} string The `toString` result.
  28354. * @returns {Function} Returns `func`.
  28355. */
  28356. var setToString = shortOut(baseSetToString);
  28357. /**
  28358. * Sets the `toString` method of `wrapper` to mimic the source of `reference`
  28359. * with wrapper details in a comment at the top of the source body.
  28360. *
  28361. * @private
  28362. * @param {Function} wrapper The function to modify.
  28363. * @param {Function} reference The reference function.
  28364. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  28365. * @returns {Function} Returns `wrapper`.
  28366. */
  28367. function setWrapToString(wrapper, reference, bitmask) {
  28368. var source = (reference + '');
  28369. return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
  28370. }
  28371. /**
  28372. * Creates a function that'll short out and invoke `identity` instead
  28373. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  28374. * milliseconds.
  28375. *
  28376. * @private
  28377. * @param {Function} func The function to restrict.
  28378. * @returns {Function} Returns the new shortable function.
  28379. */
  28380. function shortOut(func) {
  28381. var count = 0,
  28382. lastCalled = 0;
  28383. return function() {
  28384. var stamp = nativeNow(),
  28385. remaining = HOT_SPAN - (stamp - lastCalled);
  28386. lastCalled = stamp;
  28387. if (remaining > 0) {
  28388. if (++count >= HOT_COUNT) {
  28389. return arguments[0];
  28390. }
  28391. } else {
  28392. count = 0;
  28393. }
  28394. return func.apply(undefined, arguments);
  28395. };
  28396. }
  28397. /**
  28398. * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
  28399. *
  28400. * @private
  28401. * @param {Array} array The array to shuffle.
  28402. * @param {number} [size=array.length] The size of `array`.
  28403. * @returns {Array} Returns `array`.
  28404. */
  28405. function shuffleSelf(array, size) {
  28406. var index = -1,
  28407. length = array.length,
  28408. lastIndex = length - 1;
  28409. size = size === undefined ? length : size;
  28410. while (++index < size) {
  28411. var rand = baseRandom(index, lastIndex),
  28412. value = array[rand];
  28413. array[rand] = array[index];
  28414. array[index] = value;
  28415. }
  28416. array.length = size;
  28417. return array;
  28418. }
  28419. /**
  28420. * Converts `string` to a property path array.
  28421. *
  28422. * @private
  28423. * @param {string} string The string to convert.
  28424. * @returns {Array} Returns the property path array.
  28425. */
  28426. var stringToPath = memoizeCapped(function(string) {
  28427. var result = [];
  28428. if (reLeadingDot.test(string)) {
  28429. result.push('');
  28430. }
  28431. string.replace(rePropName, function(match, number, quote, string) {
  28432. result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
  28433. });
  28434. return result;
  28435. });
  28436. /**
  28437. * Converts `value` to a string key if it's not a string or symbol.
  28438. *
  28439. * @private
  28440. * @param {*} value The value to inspect.
  28441. * @returns {string|symbol} Returns the key.
  28442. */
  28443. function toKey(value) {
  28444. if (typeof value == 'string' || isSymbol(value)) {
  28445. return value;
  28446. }
  28447. var result = (value + '');
  28448. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  28449. }
  28450. /**
  28451. * Converts `func` to its source code.
  28452. *
  28453. * @private
  28454. * @param {Function} func The function to convert.
  28455. * @returns {string} Returns the source code.
  28456. */
  28457. function toSource(func) {
  28458. if (func != null) {
  28459. try {
  28460. return funcToString.call(func);
  28461. } catch (e) {}
  28462. try {
  28463. return (func + '');
  28464. } catch (e) {}
  28465. }
  28466. return '';
  28467. }
  28468. /**
  28469. * Updates wrapper `details` based on `bitmask` flags.
  28470. *
  28471. * @private
  28472. * @returns {Array} details The details to modify.
  28473. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  28474. * @returns {Array} Returns `details`.
  28475. */
  28476. function updateWrapDetails(details, bitmask) {
  28477. arrayEach(wrapFlags, function(pair) {
  28478. var value = '_.' + pair[0];
  28479. if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
  28480. details.push(value);
  28481. }
  28482. });
  28483. return details.sort();
  28484. }
  28485. /**
  28486. * Creates a clone of `wrapper`.
  28487. *
  28488. * @private
  28489. * @param {Object} wrapper The wrapper to clone.
  28490. * @returns {Object} Returns the cloned wrapper.
  28491. */
  28492. function wrapperClone(wrapper) {
  28493. if (wrapper instanceof LazyWrapper) {
  28494. return wrapper.clone();
  28495. }
  28496. var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
  28497. result.__actions__ = copyArray(wrapper.__actions__);
  28498. result.__index__ = wrapper.__index__;
  28499. result.__values__ = wrapper.__values__;
  28500. return result;
  28501. }
  28502. /*------------------------------------------------------------------------*/
  28503. /**
  28504. * Creates an array of elements split into groups the length of `size`.
  28505. * If `array` can't be split evenly, the final chunk will be the remaining
  28506. * elements.
  28507. *
  28508. * @static
  28509. * @memberOf _
  28510. * @since 3.0.0
  28511. * @category Array
  28512. * @param {Array} array The array to process.
  28513. * @param {number} [size=1] The length of each chunk
  28514. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  28515. * @returns {Array} Returns the new array of chunks.
  28516. * @example
  28517. *
  28518. * _.chunk(['a', 'b', 'c', 'd'], 2);
  28519. * // => [['a', 'b'], ['c', 'd']]
  28520. *
  28521. * _.chunk(['a', 'b', 'c', 'd'], 3);
  28522. * // => [['a', 'b', 'c'], ['d']]
  28523. */
  28524. function chunk(array, size, guard) {
  28525. if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
  28526. size = 1;
  28527. } else {
  28528. size = nativeMax(toInteger(size), 0);
  28529. }
  28530. var length = array == null ? 0 : array.length;
  28531. if (!length || size < 1) {
  28532. return [];
  28533. }
  28534. var index = 0,
  28535. resIndex = 0,
  28536. result = Array(nativeCeil(length / size));
  28537. while (index < length) {
  28538. result[resIndex++] = baseSlice(array, index, (index += size));
  28539. }
  28540. return result;
  28541. }
  28542. /**
  28543. * Creates an array with all falsey values removed. The values `false`, `null`,
  28544. * `0`, `""`, `undefined`, and `NaN` are falsey.
  28545. *
  28546. * @static
  28547. * @memberOf _
  28548. * @since 0.1.0
  28549. * @category Array
  28550. * @param {Array} array The array to compact.
  28551. * @returns {Array} Returns the new array of filtered values.
  28552. * @example
  28553. *
  28554. * _.compact([0, 1, false, 2, '', 3]);
  28555. * // => [1, 2, 3]
  28556. */
  28557. function compact(array) {
  28558. var index = -1,
  28559. length = array == null ? 0 : array.length,
  28560. resIndex = 0,
  28561. result = [];
  28562. while (++index < length) {
  28563. var value = array[index];
  28564. if (value) {
  28565. result[resIndex++] = value;
  28566. }
  28567. }
  28568. return result;
  28569. }
  28570. /**
  28571. * Creates a new array concatenating `array` with any additional arrays
  28572. * and/or values.
  28573. *
  28574. * @static
  28575. * @memberOf _
  28576. * @since 4.0.0
  28577. * @category Array
  28578. * @param {Array} array The array to concatenate.
  28579. * @param {...*} [values] The values to concatenate.
  28580. * @returns {Array} Returns the new concatenated array.
  28581. * @example
  28582. *
  28583. * var array = [1];
  28584. * var other = _.concat(array, 2, [3], [[4]]);
  28585. *
  28586. * console.log(other);
  28587. * // => [1, 2, 3, [4]]
  28588. *
  28589. * console.log(array);
  28590. * // => [1]
  28591. */
  28592. function concat() {
  28593. var length = arguments.length;
  28594. if (!length) {
  28595. return [];
  28596. }
  28597. var args = Array(length - 1),
  28598. array = arguments[0],
  28599. index = length;
  28600. while (index--) {
  28601. args[index - 1] = arguments[index];
  28602. }
  28603. return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
  28604. }
  28605. /**
  28606. * Creates an array of `array` values not included in the other given arrays
  28607. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  28608. * for equality comparisons. The order and references of result values are
  28609. * determined by the first array.
  28610. *
  28611. * **Note:** Unlike `_.pullAll`, this method returns a new array.
  28612. *
  28613. * @static
  28614. * @memberOf _
  28615. * @since 0.1.0
  28616. * @category Array
  28617. * @param {Array} array The array to inspect.
  28618. * @param {...Array} [values] The values to exclude.
  28619. * @returns {Array} Returns the new array of filtered values.
  28620. * @see _.without, _.xor
  28621. * @example
  28622. *
  28623. * _.difference([2, 1], [2, 3]);
  28624. * // => [1]
  28625. */
  28626. var difference = baseRest(function(array, values) {
  28627. return isArrayLikeObject(array)
  28628. ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
  28629. : [];
  28630. });
  28631. /**
  28632. * This method is like `_.difference` except that it accepts `iteratee` which
  28633. * is invoked for each element of `array` and `values` to generate the criterion
  28634. * by which they're compared. The order and references of result values are
  28635. * determined by the first array. The iteratee is invoked with one argument:
  28636. * (value).
  28637. *
  28638. * **Note:** Unlike `_.pullAllBy`, this method returns a new array.
  28639. *
  28640. * @static
  28641. * @memberOf _
  28642. * @since 4.0.0
  28643. * @category Array
  28644. * @param {Array} array The array to inspect.
  28645. * @param {...Array} [values] The values to exclude.
  28646. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  28647. * @returns {Array} Returns the new array of filtered values.
  28648. * @example
  28649. *
  28650. * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
  28651. * // => [1.2]
  28652. *
  28653. * // The `_.property` iteratee shorthand.
  28654. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
  28655. * // => [{ 'x': 2 }]
  28656. */
  28657. var differenceBy = baseRest(function(array, values) {
  28658. var iteratee = last(values);
  28659. if (isArrayLikeObject(iteratee)) {
  28660. iteratee = undefined;
  28661. }
  28662. return isArrayLikeObject(array)
  28663. ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
  28664. : [];
  28665. });
  28666. /**
  28667. * This method is like `_.difference` except that it accepts `comparator`
  28668. * which is invoked to compare elements of `array` to `values`. The order and
  28669. * references of result values are determined by the first array. The comparator
  28670. * is invoked with two arguments: (arrVal, othVal).
  28671. *
  28672. * **Note:** Unlike `_.pullAllWith`, this method returns a new array.
  28673. *
  28674. * @static
  28675. * @memberOf _
  28676. * @since 4.0.0
  28677. * @category Array
  28678. * @param {Array} array The array to inspect.
  28679. * @param {...Array} [values] The values to exclude.
  28680. * @param {Function} [comparator] The comparator invoked per element.
  28681. * @returns {Array} Returns the new array of filtered values.
  28682. * @example
  28683. *
  28684. * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
  28685. *
  28686. * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
  28687. * // => [{ 'x': 2, 'y': 1 }]
  28688. */
  28689. var differenceWith = baseRest(function(array, values) {
  28690. var comparator = last(values);
  28691. if (isArrayLikeObject(comparator)) {
  28692. comparator = undefined;
  28693. }
  28694. return isArrayLikeObject(array)
  28695. ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
  28696. : [];
  28697. });
  28698. /**
  28699. * Creates a slice of `array` with `n` elements dropped from the beginning.
  28700. *
  28701. * @static
  28702. * @memberOf _
  28703. * @since 0.5.0
  28704. * @category Array
  28705. * @param {Array} array The array to query.
  28706. * @param {number} [n=1] The number of elements to drop.
  28707. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  28708. * @returns {Array} Returns the slice of `array`.
  28709. * @example
  28710. *
  28711. * _.drop([1, 2, 3]);
  28712. * // => [2, 3]
  28713. *
  28714. * _.drop([1, 2, 3], 2);
  28715. * // => [3]
  28716. *
  28717. * _.drop([1, 2, 3], 5);
  28718. * // => []
  28719. *
  28720. * _.drop([1, 2, 3], 0);
  28721. * // => [1, 2, 3]
  28722. */
  28723. function drop(array, n, guard) {
  28724. var length = array == null ? 0 : array.length;
  28725. if (!length) {
  28726. return [];
  28727. }
  28728. n = (guard || n === undefined) ? 1 : toInteger(n);
  28729. return baseSlice(array, n < 0 ? 0 : n, length);
  28730. }
  28731. /**
  28732. * Creates a slice of `array` with `n` elements dropped from the end.
  28733. *
  28734. * @static
  28735. * @memberOf _
  28736. * @since 3.0.0
  28737. * @category Array
  28738. * @param {Array} array The array to query.
  28739. * @param {number} [n=1] The number of elements to drop.
  28740. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  28741. * @returns {Array} Returns the slice of `array`.
  28742. * @example
  28743. *
  28744. * _.dropRight([1, 2, 3]);
  28745. * // => [1, 2]
  28746. *
  28747. * _.dropRight([1, 2, 3], 2);
  28748. * // => [1]
  28749. *
  28750. * _.dropRight([1, 2, 3], 5);
  28751. * // => []
  28752. *
  28753. * _.dropRight([1, 2, 3], 0);
  28754. * // => [1, 2, 3]
  28755. */
  28756. function dropRight(array, n, guard) {
  28757. var length = array == null ? 0 : array.length;
  28758. if (!length) {
  28759. return [];
  28760. }
  28761. n = (guard || n === undefined) ? 1 : toInteger(n);
  28762. n = length - n;
  28763. return baseSlice(array, 0, n < 0 ? 0 : n);
  28764. }
  28765. /**
  28766. * Creates a slice of `array` excluding elements dropped from the end.
  28767. * Elements are dropped until `predicate` returns falsey. The predicate is
  28768. * invoked with three arguments: (value, index, array).
  28769. *
  28770. * @static
  28771. * @memberOf _
  28772. * @since 3.0.0
  28773. * @category Array
  28774. * @param {Array} array The array to query.
  28775. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  28776. * @returns {Array} Returns the slice of `array`.
  28777. * @example
  28778. *
  28779. * var users = [
  28780. * { 'user': 'barney', 'active': true },
  28781. * { 'user': 'fred', 'active': false },
  28782. * { 'user': 'pebbles', 'active': false }
  28783. * ];
  28784. *
  28785. * _.dropRightWhile(users, function(o) { return !o.active; });
  28786. * // => objects for ['barney']
  28787. *
  28788. * // The `_.matches` iteratee shorthand.
  28789. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
  28790. * // => objects for ['barney', 'fred']
  28791. *
  28792. * // The `_.matchesProperty` iteratee shorthand.
  28793. * _.dropRightWhile(users, ['active', false]);
  28794. * // => objects for ['barney']
  28795. *
  28796. * // The `_.property` iteratee shorthand.
  28797. * _.dropRightWhile(users, 'active');
  28798. * // => objects for ['barney', 'fred', 'pebbles']
  28799. */
  28800. function dropRightWhile(array, predicate) {
  28801. return (array && array.length)
  28802. ? baseWhile(array, getIteratee(predicate, 3), true, true)
  28803. : [];
  28804. }
  28805. /**
  28806. * Creates a slice of `array` excluding elements dropped from the beginning.
  28807. * Elements are dropped until `predicate` returns falsey. The predicate is
  28808. * invoked with three arguments: (value, index, array).
  28809. *
  28810. * @static
  28811. * @memberOf _
  28812. * @since 3.0.0
  28813. * @category Array
  28814. * @param {Array} array The array to query.
  28815. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  28816. * @returns {Array} Returns the slice of `array`.
  28817. * @example
  28818. *
  28819. * var users = [
  28820. * { 'user': 'barney', 'active': false },
  28821. * { 'user': 'fred', 'active': false },
  28822. * { 'user': 'pebbles', 'active': true }
  28823. * ];
  28824. *
  28825. * _.dropWhile(users, function(o) { return !o.active; });
  28826. * // => objects for ['pebbles']
  28827. *
  28828. * // The `_.matches` iteratee shorthand.
  28829. * _.dropWhile(users, { 'user': 'barney', 'active': false });
  28830. * // => objects for ['fred', 'pebbles']
  28831. *
  28832. * // The `_.matchesProperty` iteratee shorthand.
  28833. * _.dropWhile(users, ['active', false]);
  28834. * // => objects for ['pebbles']
  28835. *
  28836. * // The `_.property` iteratee shorthand.
  28837. * _.dropWhile(users, 'active');
  28838. * // => objects for ['barney', 'fred', 'pebbles']
  28839. */
  28840. function dropWhile(array, predicate) {
  28841. return (array && array.length)
  28842. ? baseWhile(array, getIteratee(predicate, 3), true)
  28843. : [];
  28844. }
  28845. /**
  28846. * Fills elements of `array` with `value` from `start` up to, but not
  28847. * including, `end`.
  28848. *
  28849. * **Note:** This method mutates `array`.
  28850. *
  28851. * @static
  28852. * @memberOf _
  28853. * @since 3.2.0
  28854. * @category Array
  28855. * @param {Array} array The array to fill.
  28856. * @param {*} value The value to fill `array` with.
  28857. * @param {number} [start=0] The start position.
  28858. * @param {number} [end=array.length] The end position.
  28859. * @returns {Array} Returns `array`.
  28860. * @example
  28861. *
  28862. * var array = [1, 2, 3];
  28863. *
  28864. * _.fill(array, 'a');
  28865. * console.log(array);
  28866. * // => ['a', 'a', 'a']
  28867. *
  28868. * _.fill(Array(3), 2);
  28869. * // => [2, 2, 2]
  28870. *
  28871. * _.fill([4, 6, 8, 10], '*', 1, 3);
  28872. * // => [4, '*', '*', 10]
  28873. */
  28874. function fill(array, value, start, end) {
  28875. var length = array == null ? 0 : array.length;
  28876. if (!length) {
  28877. return [];
  28878. }
  28879. if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
  28880. start = 0;
  28881. end = length;
  28882. }
  28883. return baseFill(array, value, start, end);
  28884. }
  28885. /**
  28886. * This method is like `_.find` except that it returns the index of the first
  28887. * element `predicate` returns truthy for instead of the element itself.
  28888. *
  28889. * @static
  28890. * @memberOf _
  28891. * @since 1.1.0
  28892. * @category Array
  28893. * @param {Array} array The array to inspect.
  28894. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  28895. * @param {number} [fromIndex=0] The index to search from.
  28896. * @returns {number} Returns the index of the found element, else `-1`.
  28897. * @example
  28898. *
  28899. * var users = [
  28900. * { 'user': 'barney', 'active': false },
  28901. * { 'user': 'fred', 'active': false },
  28902. * { 'user': 'pebbles', 'active': true }
  28903. * ];
  28904. *
  28905. * _.findIndex(users, function(o) { return o.user == 'barney'; });
  28906. * // => 0
  28907. *
  28908. * // The `_.matches` iteratee shorthand.
  28909. * _.findIndex(users, { 'user': 'fred', 'active': false });
  28910. * // => 1
  28911. *
  28912. * // The `_.matchesProperty` iteratee shorthand.
  28913. * _.findIndex(users, ['active', false]);
  28914. * // => 0
  28915. *
  28916. * // The `_.property` iteratee shorthand.
  28917. * _.findIndex(users, 'active');
  28918. * // => 2
  28919. */
  28920. function findIndex(array, predicate, fromIndex) {
  28921. var length = array == null ? 0 : array.length;
  28922. if (!length) {
  28923. return -1;
  28924. }
  28925. var index = fromIndex == null ? 0 : toInteger(fromIndex);
  28926. if (index < 0) {
  28927. index = nativeMax(length + index, 0);
  28928. }
  28929. return baseFindIndex(array, getIteratee(predicate, 3), index);
  28930. }
  28931. /**
  28932. * This method is like `_.findIndex` except that it iterates over elements
  28933. * of `collection` from right to left.
  28934. *
  28935. * @static
  28936. * @memberOf _
  28937. * @since 2.0.0
  28938. * @category Array
  28939. * @param {Array} array The array to inspect.
  28940. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  28941. * @param {number} [fromIndex=array.length-1] The index to search from.
  28942. * @returns {number} Returns the index of the found element, else `-1`.
  28943. * @example
  28944. *
  28945. * var users = [
  28946. * { 'user': 'barney', 'active': true },
  28947. * { 'user': 'fred', 'active': false },
  28948. * { 'user': 'pebbles', 'active': false }
  28949. * ];
  28950. *
  28951. * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
  28952. * // => 2
  28953. *
  28954. * // The `_.matches` iteratee shorthand.
  28955. * _.findLastIndex(users, { 'user': 'barney', 'active': true });
  28956. * // => 0
  28957. *
  28958. * // The `_.matchesProperty` iteratee shorthand.
  28959. * _.findLastIndex(users, ['active', false]);
  28960. * // => 2
  28961. *
  28962. * // The `_.property` iteratee shorthand.
  28963. * _.findLastIndex(users, 'active');
  28964. * // => 0
  28965. */
  28966. function findLastIndex(array, predicate, fromIndex) {
  28967. var length = array == null ? 0 : array.length;
  28968. if (!length) {
  28969. return -1;
  28970. }
  28971. var index = length - 1;
  28972. if (fromIndex !== undefined) {
  28973. index = toInteger(fromIndex);
  28974. index = fromIndex < 0
  28975. ? nativeMax(length + index, 0)
  28976. : nativeMin(index, length - 1);
  28977. }
  28978. return baseFindIndex(array, getIteratee(predicate, 3), index, true);
  28979. }
  28980. /**
  28981. * Flattens `array` a single level deep.
  28982. *
  28983. * @static
  28984. * @memberOf _
  28985. * @since 0.1.0
  28986. * @category Array
  28987. * @param {Array} array The array to flatten.
  28988. * @returns {Array} Returns the new flattened array.
  28989. * @example
  28990. *
  28991. * _.flatten([1, [2, [3, [4]], 5]]);
  28992. * // => [1, 2, [3, [4]], 5]
  28993. */
  28994. function flatten(array) {
  28995. var length = array == null ? 0 : array.length;
  28996. return length ? baseFlatten(array, 1) : [];
  28997. }
  28998. /**
  28999. * Recursively flattens `array`.
  29000. *
  29001. * @static
  29002. * @memberOf _
  29003. * @since 3.0.0
  29004. * @category Array
  29005. * @param {Array} array The array to flatten.
  29006. * @returns {Array} Returns the new flattened array.
  29007. * @example
  29008. *
  29009. * _.flattenDeep([1, [2, [3, [4]], 5]]);
  29010. * // => [1, 2, 3, 4, 5]
  29011. */
  29012. function flattenDeep(array) {
  29013. var length = array == null ? 0 : array.length;
  29014. return length ? baseFlatten(array, INFINITY) : [];
  29015. }
  29016. /**
  29017. * Recursively flatten `array` up to `depth` times.
  29018. *
  29019. * @static
  29020. * @memberOf _
  29021. * @since 4.4.0
  29022. * @category Array
  29023. * @param {Array} array The array to flatten.
  29024. * @param {number} [depth=1] The maximum recursion depth.
  29025. * @returns {Array} Returns the new flattened array.
  29026. * @example
  29027. *
  29028. * var array = [1, [2, [3, [4]], 5]];
  29029. *
  29030. * _.flattenDepth(array, 1);
  29031. * // => [1, 2, [3, [4]], 5]
  29032. *
  29033. * _.flattenDepth(array, 2);
  29034. * // => [1, 2, 3, [4], 5]
  29035. */
  29036. function flattenDepth(array, depth) {
  29037. var length = array == null ? 0 : array.length;
  29038. if (!length) {
  29039. return [];
  29040. }
  29041. depth = depth === undefined ? 1 : toInteger(depth);
  29042. return baseFlatten(array, depth);
  29043. }
  29044. /**
  29045. * The inverse of `_.toPairs`; this method returns an object composed
  29046. * from key-value `pairs`.
  29047. *
  29048. * @static
  29049. * @memberOf _
  29050. * @since 4.0.0
  29051. * @category Array
  29052. * @param {Array} pairs The key-value pairs.
  29053. * @returns {Object} Returns the new object.
  29054. * @example
  29055. *
  29056. * _.fromPairs([['a', 1], ['b', 2]]);
  29057. * // => { 'a': 1, 'b': 2 }
  29058. */
  29059. function fromPairs(pairs) {
  29060. var index = -1,
  29061. length = pairs == null ? 0 : pairs.length,
  29062. result = {};
  29063. while (++index < length) {
  29064. var pair = pairs[index];
  29065. result[pair[0]] = pair[1];
  29066. }
  29067. return result;
  29068. }
  29069. /**
  29070. * Gets the first element of `array`.
  29071. *
  29072. * @static
  29073. * @memberOf _
  29074. * @since 0.1.0
  29075. * @alias first
  29076. * @category Array
  29077. * @param {Array} array The array to query.
  29078. * @returns {*} Returns the first element of `array`.
  29079. * @example
  29080. *
  29081. * _.head([1, 2, 3]);
  29082. * // => 1
  29083. *
  29084. * _.head([]);
  29085. * // => undefined
  29086. */
  29087. function head(array) {
  29088. return (array && array.length) ? array[0] : undefined;
  29089. }
  29090. /**
  29091. * Gets the index at which the first occurrence of `value` is found in `array`
  29092. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  29093. * for equality comparisons. If `fromIndex` is negative, it's used as the
  29094. * offset from the end of `array`.
  29095. *
  29096. * @static
  29097. * @memberOf _
  29098. * @since 0.1.0
  29099. * @category Array
  29100. * @param {Array} array The array to inspect.
  29101. * @param {*} value The value to search for.
  29102. * @param {number} [fromIndex=0] The index to search from.
  29103. * @returns {number} Returns the index of the matched value, else `-1`.
  29104. * @example
  29105. *
  29106. * _.indexOf([1, 2, 1, 2], 2);
  29107. * // => 1
  29108. *
  29109. * // Search from the `fromIndex`.
  29110. * _.indexOf([1, 2, 1, 2], 2, 2);
  29111. * // => 3
  29112. */
  29113. function indexOf(array, value, fromIndex) {
  29114. var length = array == null ? 0 : array.length;
  29115. if (!length) {
  29116. return -1;
  29117. }
  29118. var index = fromIndex == null ? 0 : toInteger(fromIndex);
  29119. if (index < 0) {
  29120. index = nativeMax(length + index, 0);
  29121. }
  29122. return baseIndexOf(array, value, index);
  29123. }
  29124. /**
  29125. * Gets all but the last element of `array`.
  29126. *
  29127. * @static
  29128. * @memberOf _
  29129. * @since 0.1.0
  29130. * @category Array
  29131. * @param {Array} array The array to query.
  29132. * @returns {Array} Returns the slice of `array`.
  29133. * @example
  29134. *
  29135. * _.initial([1, 2, 3]);
  29136. * // => [1, 2]
  29137. */
  29138. function initial(array) {
  29139. var length = array == null ? 0 : array.length;
  29140. return length ? baseSlice(array, 0, -1) : [];
  29141. }
  29142. /**
  29143. * Creates an array of unique values that are included in all given arrays
  29144. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  29145. * for equality comparisons. The order and references of result values are
  29146. * determined by the first array.
  29147. *
  29148. * @static
  29149. * @memberOf _
  29150. * @since 0.1.0
  29151. * @category Array
  29152. * @param {...Array} [arrays] The arrays to inspect.
  29153. * @returns {Array} Returns the new array of intersecting values.
  29154. * @example
  29155. *
  29156. * _.intersection([2, 1], [2, 3]);
  29157. * // => [2]
  29158. */
  29159. var intersection = baseRest(function(arrays) {
  29160. var mapped = arrayMap(arrays, castArrayLikeObject);
  29161. return (mapped.length && mapped[0] === arrays[0])
  29162. ? baseIntersection(mapped)
  29163. : [];
  29164. });
  29165. /**
  29166. * This method is like `_.intersection` except that it accepts `iteratee`
  29167. * which is invoked for each element of each `arrays` to generate the criterion
  29168. * by which they're compared. The order and references of result values are
  29169. * determined by the first array. The iteratee is invoked with one argument:
  29170. * (value).
  29171. *
  29172. * @static
  29173. * @memberOf _
  29174. * @since 4.0.0
  29175. * @category Array
  29176. * @param {...Array} [arrays] The arrays to inspect.
  29177. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  29178. * @returns {Array} Returns the new array of intersecting values.
  29179. * @example
  29180. *
  29181. * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
  29182. * // => [2.1]
  29183. *
  29184. * // The `_.property` iteratee shorthand.
  29185. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
  29186. * // => [{ 'x': 1 }]
  29187. */
  29188. var intersectionBy = baseRest(function(arrays) {
  29189. var iteratee = last(arrays),
  29190. mapped = arrayMap(arrays, castArrayLikeObject);
  29191. if (iteratee === last(mapped)) {
  29192. iteratee = undefined;
  29193. } else {
  29194. mapped.pop();
  29195. }
  29196. return (mapped.length && mapped[0] === arrays[0])
  29197. ? baseIntersection(mapped, getIteratee(iteratee, 2))
  29198. : [];
  29199. });
  29200. /**
  29201. * This method is like `_.intersection` except that it accepts `comparator`
  29202. * which is invoked to compare elements of `arrays`. The order and references
  29203. * of result values are determined by the first array. The comparator is
  29204. * invoked with two arguments: (arrVal, othVal).
  29205. *
  29206. * @static
  29207. * @memberOf _
  29208. * @since 4.0.0
  29209. * @category Array
  29210. * @param {...Array} [arrays] The arrays to inspect.
  29211. * @param {Function} [comparator] The comparator invoked per element.
  29212. * @returns {Array} Returns the new array of intersecting values.
  29213. * @example
  29214. *
  29215. * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
  29216. * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
  29217. *
  29218. * _.intersectionWith(objects, others, _.isEqual);
  29219. * // => [{ 'x': 1, 'y': 2 }]
  29220. */
  29221. var intersectionWith = baseRest(function(arrays) {
  29222. var comparator = last(arrays),
  29223. mapped = arrayMap(arrays, castArrayLikeObject);
  29224. comparator = typeof comparator == 'function' ? comparator : undefined;
  29225. if (comparator) {
  29226. mapped.pop();
  29227. }
  29228. return (mapped.length && mapped[0] === arrays[0])
  29229. ? baseIntersection(mapped, undefined, comparator)
  29230. : [];
  29231. });
  29232. /**
  29233. * Converts all elements in `array` into a string separated by `separator`.
  29234. *
  29235. * @static
  29236. * @memberOf _
  29237. * @since 4.0.0
  29238. * @category Array
  29239. * @param {Array} array The array to convert.
  29240. * @param {string} [separator=','] The element separator.
  29241. * @returns {string} Returns the joined string.
  29242. * @example
  29243. *
  29244. * _.join(['a', 'b', 'c'], '~');
  29245. * // => 'a~b~c'
  29246. */
  29247. function join(array, separator) {
  29248. return array == null ? '' : nativeJoin.call(array, separator);
  29249. }
  29250. /**
  29251. * Gets the last element of `array`.
  29252. *
  29253. * @static
  29254. * @memberOf _
  29255. * @since 0.1.0
  29256. * @category Array
  29257. * @param {Array} array The array to query.
  29258. * @returns {*} Returns the last element of `array`.
  29259. * @example
  29260. *
  29261. * _.last([1, 2, 3]);
  29262. * // => 3
  29263. */
  29264. function last(array) {
  29265. var length = array == null ? 0 : array.length;
  29266. return length ? array[length - 1] : undefined;
  29267. }
  29268. /**
  29269. * This method is like `_.indexOf` except that it iterates over elements of
  29270. * `array` from right to left.
  29271. *
  29272. * @static
  29273. * @memberOf _
  29274. * @since 0.1.0
  29275. * @category Array
  29276. * @param {Array} array The array to inspect.
  29277. * @param {*} value The value to search for.
  29278. * @param {number} [fromIndex=array.length-1] The index to search from.
  29279. * @returns {number} Returns the index of the matched value, else `-1`.
  29280. * @example
  29281. *
  29282. * _.lastIndexOf([1, 2, 1, 2], 2);
  29283. * // => 3
  29284. *
  29285. * // Search from the `fromIndex`.
  29286. * _.lastIndexOf([1, 2, 1, 2], 2, 2);
  29287. * // => 1
  29288. */
  29289. function lastIndexOf(array, value, fromIndex) {
  29290. var length = array == null ? 0 : array.length;
  29291. if (!length) {
  29292. return -1;
  29293. }
  29294. var index = length;
  29295. if (fromIndex !== undefined) {
  29296. index = toInteger(fromIndex);
  29297. index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
  29298. }
  29299. return value === value
  29300. ? strictLastIndexOf(array, value, index)
  29301. : baseFindIndex(array, baseIsNaN, index, true);
  29302. }
  29303. /**
  29304. * Gets the element at index `n` of `array`. If `n` is negative, the nth
  29305. * element from the end is returned.
  29306. *
  29307. * @static
  29308. * @memberOf _
  29309. * @since 4.11.0
  29310. * @category Array
  29311. * @param {Array} array The array to query.
  29312. * @param {number} [n=0] The index of the element to return.
  29313. * @returns {*} Returns the nth element of `array`.
  29314. * @example
  29315. *
  29316. * var array = ['a', 'b', 'c', 'd'];
  29317. *
  29318. * _.nth(array, 1);
  29319. * // => 'b'
  29320. *
  29321. * _.nth(array, -2);
  29322. * // => 'c';
  29323. */
  29324. function nth(array, n) {
  29325. return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
  29326. }
  29327. /**
  29328. * Removes all given values from `array` using
  29329. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  29330. * for equality comparisons.
  29331. *
  29332. * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
  29333. * to remove elements from an array by predicate.
  29334. *
  29335. * @static
  29336. * @memberOf _
  29337. * @since 2.0.0
  29338. * @category Array
  29339. * @param {Array} array The array to modify.
  29340. * @param {...*} [values] The values to remove.
  29341. * @returns {Array} Returns `array`.
  29342. * @example
  29343. *
  29344. * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
  29345. *
  29346. * _.pull(array, 'a', 'c');
  29347. * console.log(array);
  29348. * // => ['b', 'b']
  29349. */
  29350. var pull = baseRest(pullAll);
  29351. /**
  29352. * This method is like `_.pull` except that it accepts an array of values to remove.
  29353. *
  29354. * **Note:** Unlike `_.difference`, this method mutates `array`.
  29355. *
  29356. * @static
  29357. * @memberOf _
  29358. * @since 4.0.0
  29359. * @category Array
  29360. * @param {Array} array The array to modify.
  29361. * @param {Array} values The values to remove.
  29362. * @returns {Array} Returns `array`.
  29363. * @example
  29364. *
  29365. * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
  29366. *
  29367. * _.pullAll(array, ['a', 'c']);
  29368. * console.log(array);
  29369. * // => ['b', 'b']
  29370. */
  29371. function pullAll(array, values) {
  29372. return (array && array.length && values && values.length)
  29373. ? basePullAll(array, values)
  29374. : array;
  29375. }
  29376. /**
  29377. * This method is like `_.pullAll` except that it accepts `iteratee` which is
  29378. * invoked for each element of `array` and `values` to generate the criterion
  29379. * by which they're compared. The iteratee is invoked with one argument: (value).
  29380. *
  29381. * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
  29382. *
  29383. * @static
  29384. * @memberOf _
  29385. * @since 4.0.0
  29386. * @category Array
  29387. * @param {Array} array The array to modify.
  29388. * @param {Array} values The values to remove.
  29389. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  29390. * @returns {Array} Returns `array`.
  29391. * @example
  29392. *
  29393. * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
  29394. *
  29395. * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
  29396. * console.log(array);
  29397. * // => [{ 'x': 2 }]
  29398. */
  29399. function pullAllBy(array, values, iteratee) {
  29400. return (array && array.length && values && values.length)
  29401. ? basePullAll(array, values, getIteratee(iteratee, 2))
  29402. : array;
  29403. }
  29404. /**
  29405. * This method is like `_.pullAll` except that it accepts `comparator` which
  29406. * is invoked to compare elements of `array` to `values`. The comparator is
  29407. * invoked with two arguments: (arrVal, othVal).
  29408. *
  29409. * **Note:** Unlike `_.differenceWith`, this method mutates `array`.
  29410. *
  29411. * @static
  29412. * @memberOf _
  29413. * @since 4.6.0
  29414. * @category Array
  29415. * @param {Array} array The array to modify.
  29416. * @param {Array} values The values to remove.
  29417. * @param {Function} [comparator] The comparator invoked per element.
  29418. * @returns {Array} Returns `array`.
  29419. * @example
  29420. *
  29421. * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
  29422. *
  29423. * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
  29424. * console.log(array);
  29425. * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
  29426. */
  29427. function pullAllWith(array, values, comparator) {
  29428. return (array && array.length && values && values.length)
  29429. ? basePullAll(array, values, undefined, comparator)
  29430. : array;
  29431. }
  29432. /**
  29433. * Removes elements from `array` corresponding to `indexes` and returns an
  29434. * array of removed elements.
  29435. *
  29436. * **Note:** Unlike `_.at`, this method mutates `array`.
  29437. *
  29438. * @static
  29439. * @memberOf _
  29440. * @since 3.0.0
  29441. * @category Array
  29442. * @param {Array} array The array to modify.
  29443. * @param {...(number|number[])} [indexes] The indexes of elements to remove.
  29444. * @returns {Array} Returns the new array of removed elements.
  29445. * @example
  29446. *
  29447. * var array = ['a', 'b', 'c', 'd'];
  29448. * var pulled = _.pullAt(array, [1, 3]);
  29449. *
  29450. * console.log(array);
  29451. * // => ['a', 'c']
  29452. *
  29453. * console.log(pulled);
  29454. * // => ['b', 'd']
  29455. */
  29456. var pullAt = flatRest(function(array, indexes) {
  29457. var length = array == null ? 0 : array.length,
  29458. result = baseAt(array, indexes);
  29459. basePullAt(array, arrayMap(indexes, function(index) {
  29460. return isIndex(index, length) ? +index : index;
  29461. }).sort(compareAscending));
  29462. return result;
  29463. });
  29464. /**
  29465. * Removes all elements from `array` that `predicate` returns truthy for
  29466. * and returns an array of the removed elements. The predicate is invoked
  29467. * with three arguments: (value, index, array).
  29468. *
  29469. * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
  29470. * to pull elements from an array by value.
  29471. *
  29472. * @static
  29473. * @memberOf _
  29474. * @since 2.0.0
  29475. * @category Array
  29476. * @param {Array} array The array to modify.
  29477. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  29478. * @returns {Array} Returns the new array of removed elements.
  29479. * @example
  29480. *
  29481. * var array = [1, 2, 3, 4];
  29482. * var evens = _.remove(array, function(n) {
  29483. * return n % 2 == 0;
  29484. * });
  29485. *
  29486. * console.log(array);
  29487. * // => [1, 3]
  29488. *
  29489. * console.log(evens);
  29490. * // => [2, 4]
  29491. */
  29492. function remove(array, predicate) {
  29493. var result = [];
  29494. if (!(array && array.length)) {
  29495. return result;
  29496. }
  29497. var index = -1,
  29498. indexes = [],
  29499. length = array.length;
  29500. predicate = getIteratee(predicate, 3);
  29501. while (++index < length) {
  29502. var value = array[index];
  29503. if (predicate(value, index, array)) {
  29504. result.push(value);
  29505. indexes.push(index);
  29506. }
  29507. }
  29508. basePullAt(array, indexes);
  29509. return result;
  29510. }
  29511. /**
  29512. * Reverses `array` so that the first element becomes the last, the second
  29513. * element becomes the second to last, and so on.
  29514. *
  29515. * **Note:** This method mutates `array` and is based on
  29516. * [`Array#reverse`](https://mdn.io/Array/reverse).
  29517. *
  29518. * @static
  29519. * @memberOf _
  29520. * @since 4.0.0
  29521. * @category Array
  29522. * @param {Array} array The array to modify.
  29523. * @returns {Array} Returns `array`.
  29524. * @example
  29525. *
  29526. * var array = [1, 2, 3];
  29527. *
  29528. * _.reverse(array);
  29529. * // => [3, 2, 1]
  29530. *
  29531. * console.log(array);
  29532. * // => [3, 2, 1]
  29533. */
  29534. function reverse(array) {
  29535. return array == null ? array : nativeReverse.call(array);
  29536. }
  29537. /**
  29538. * Creates a slice of `array` from `start` up to, but not including, `end`.
  29539. *
  29540. * **Note:** This method is used instead of
  29541. * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
  29542. * returned.
  29543. *
  29544. * @static
  29545. * @memberOf _
  29546. * @since 3.0.0
  29547. * @category Array
  29548. * @param {Array} array The array to slice.
  29549. * @param {number} [start=0] The start position.
  29550. * @param {number} [end=array.length] The end position.
  29551. * @returns {Array} Returns the slice of `array`.
  29552. */
  29553. function slice(array, start, end) {
  29554. var length = array == null ? 0 : array.length;
  29555. if (!length) {
  29556. return [];
  29557. }
  29558. if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
  29559. start = 0;
  29560. end = length;
  29561. }
  29562. else {
  29563. start = start == null ? 0 : toInteger(start);
  29564. end = end === undefined ? length : toInteger(end);
  29565. }
  29566. return baseSlice(array, start, end);
  29567. }
  29568. /**
  29569. * Uses a binary search to determine the lowest index at which `value`
  29570. * should be inserted into `array` in order to maintain its sort order.
  29571. *
  29572. * @static
  29573. * @memberOf _
  29574. * @since 0.1.0
  29575. * @category Array
  29576. * @param {Array} array The sorted array to inspect.
  29577. * @param {*} value The value to evaluate.
  29578. * @returns {number} Returns the index at which `value` should be inserted
  29579. * into `array`.
  29580. * @example
  29581. *
  29582. * _.sortedIndex([30, 50], 40);
  29583. * // => 1
  29584. */
  29585. function sortedIndex(array, value) {
  29586. return baseSortedIndex(array, value);
  29587. }
  29588. /**
  29589. * This method is like `_.sortedIndex` except that it accepts `iteratee`
  29590. * which is invoked for `value` and each element of `array` to compute their
  29591. * sort ranking. The iteratee is invoked with one argument: (value).
  29592. *
  29593. * @static
  29594. * @memberOf _
  29595. * @since 4.0.0
  29596. * @category Array
  29597. * @param {Array} array The sorted array to inspect.
  29598. * @param {*} value The value to evaluate.
  29599. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  29600. * @returns {number} Returns the index at which `value` should be inserted
  29601. * into `array`.
  29602. * @example
  29603. *
  29604. * var objects = [{ 'x': 4 }, { 'x': 5 }];
  29605. *
  29606. * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
  29607. * // => 0
  29608. *
  29609. * // The `_.property` iteratee shorthand.
  29610. * _.sortedIndexBy(objects, { 'x': 4 }, 'x');
  29611. * // => 0
  29612. */
  29613. function sortedIndexBy(array, value, iteratee) {
  29614. return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
  29615. }
  29616. /**
  29617. * This method is like `_.indexOf` except that it performs a binary
  29618. * search on a sorted `array`.
  29619. *
  29620. * @static
  29621. * @memberOf _
  29622. * @since 4.0.0
  29623. * @category Array
  29624. * @param {Array} array The array to inspect.
  29625. * @param {*} value The value to search for.
  29626. * @returns {number} Returns the index of the matched value, else `-1`.
  29627. * @example
  29628. *
  29629. * _.sortedIndexOf([4, 5, 5, 5, 6], 5);
  29630. * // => 1
  29631. */
  29632. function sortedIndexOf(array, value) {
  29633. var length = array == null ? 0 : array.length;
  29634. if (length) {
  29635. var index = baseSortedIndex(array, value);
  29636. if (index < length && eq(array[index], value)) {
  29637. return index;
  29638. }
  29639. }
  29640. return -1;
  29641. }
  29642. /**
  29643. * This method is like `_.sortedIndex` except that it returns the highest
  29644. * index at which `value` should be inserted into `array` in order to
  29645. * maintain its sort order.
  29646. *
  29647. * @static
  29648. * @memberOf _
  29649. * @since 3.0.0
  29650. * @category Array
  29651. * @param {Array} array The sorted array to inspect.
  29652. * @param {*} value The value to evaluate.
  29653. * @returns {number} Returns the index at which `value` should be inserted
  29654. * into `array`.
  29655. * @example
  29656. *
  29657. * _.sortedLastIndex([4, 5, 5, 5, 6], 5);
  29658. * // => 4
  29659. */
  29660. function sortedLastIndex(array, value) {
  29661. return baseSortedIndex(array, value, true);
  29662. }
  29663. /**
  29664. * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
  29665. * which is invoked for `value` and each element of `array` to compute their
  29666. * sort ranking. The iteratee is invoked with one argument: (value).
  29667. *
  29668. * @static
  29669. * @memberOf _
  29670. * @since 4.0.0
  29671. * @category Array
  29672. * @param {Array} array The sorted array to inspect.
  29673. * @param {*} value The value to evaluate.
  29674. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  29675. * @returns {number} Returns the index at which `value` should be inserted
  29676. * into `array`.
  29677. * @example
  29678. *
  29679. * var objects = [{ 'x': 4 }, { 'x': 5 }];
  29680. *
  29681. * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
  29682. * // => 1
  29683. *
  29684. * // The `_.property` iteratee shorthand.
  29685. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
  29686. * // => 1
  29687. */
  29688. function sortedLastIndexBy(array, value, iteratee) {
  29689. return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
  29690. }
  29691. /**
  29692. * This method is like `_.lastIndexOf` except that it performs a binary
  29693. * search on a sorted `array`.
  29694. *
  29695. * @static
  29696. * @memberOf _
  29697. * @since 4.0.0
  29698. * @category Array
  29699. * @param {Array} array The array to inspect.
  29700. * @param {*} value The value to search for.
  29701. * @returns {number} Returns the index of the matched value, else `-1`.
  29702. * @example
  29703. *
  29704. * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
  29705. * // => 3
  29706. */
  29707. function sortedLastIndexOf(array, value) {
  29708. var length = array == null ? 0 : array.length;
  29709. if (length) {
  29710. var index = baseSortedIndex(array, value, true) - 1;
  29711. if (eq(array[index], value)) {
  29712. return index;
  29713. }
  29714. }
  29715. return -1;
  29716. }
  29717. /**
  29718. * This method is like `_.uniq` except that it's designed and optimized
  29719. * for sorted arrays.
  29720. *
  29721. * @static
  29722. * @memberOf _
  29723. * @since 4.0.0
  29724. * @category Array
  29725. * @param {Array} array The array to inspect.
  29726. * @returns {Array} Returns the new duplicate free array.
  29727. * @example
  29728. *
  29729. * _.sortedUniq([1, 1, 2]);
  29730. * // => [1, 2]
  29731. */
  29732. function sortedUniq(array) {
  29733. return (array && array.length)
  29734. ? baseSortedUniq(array)
  29735. : [];
  29736. }
  29737. /**
  29738. * This method is like `_.uniqBy` except that it's designed and optimized
  29739. * for sorted arrays.
  29740. *
  29741. * @static
  29742. * @memberOf _
  29743. * @since 4.0.0
  29744. * @category Array
  29745. * @param {Array} array The array to inspect.
  29746. * @param {Function} [iteratee] The iteratee invoked per element.
  29747. * @returns {Array} Returns the new duplicate free array.
  29748. * @example
  29749. *
  29750. * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
  29751. * // => [1.1, 2.3]
  29752. */
  29753. function sortedUniqBy(array, iteratee) {
  29754. return (array && array.length)
  29755. ? baseSortedUniq(array, getIteratee(iteratee, 2))
  29756. : [];
  29757. }
  29758. /**
  29759. * Gets all but the first element of `array`.
  29760. *
  29761. * @static
  29762. * @memberOf _
  29763. * @since 4.0.0
  29764. * @category Array
  29765. * @param {Array} array The array to query.
  29766. * @returns {Array} Returns the slice of `array`.
  29767. * @example
  29768. *
  29769. * _.tail([1, 2, 3]);
  29770. * // => [2, 3]
  29771. */
  29772. function tail(array) {
  29773. var length = array == null ? 0 : array.length;
  29774. return length ? baseSlice(array, 1, length) : [];
  29775. }
  29776. /**
  29777. * Creates a slice of `array` with `n` elements taken from the beginning.
  29778. *
  29779. * @static
  29780. * @memberOf _
  29781. * @since 0.1.0
  29782. * @category Array
  29783. * @param {Array} array The array to query.
  29784. * @param {number} [n=1] The number of elements to take.
  29785. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  29786. * @returns {Array} Returns the slice of `array`.
  29787. * @example
  29788. *
  29789. * _.take([1, 2, 3]);
  29790. * // => [1]
  29791. *
  29792. * _.take([1, 2, 3], 2);
  29793. * // => [1, 2]
  29794. *
  29795. * _.take([1, 2, 3], 5);
  29796. * // => [1, 2, 3]
  29797. *
  29798. * _.take([1, 2, 3], 0);
  29799. * // => []
  29800. */
  29801. function take(array, n, guard) {
  29802. if (!(array && array.length)) {
  29803. return [];
  29804. }
  29805. n = (guard || n === undefined) ? 1 : toInteger(n);
  29806. return baseSlice(array, 0, n < 0 ? 0 : n);
  29807. }
  29808. /**
  29809. * Creates a slice of `array` with `n` elements taken from the end.
  29810. *
  29811. * @static
  29812. * @memberOf _
  29813. * @since 3.0.0
  29814. * @category Array
  29815. * @param {Array} array The array to query.
  29816. * @param {number} [n=1] The number of elements to take.
  29817. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  29818. * @returns {Array} Returns the slice of `array`.
  29819. * @example
  29820. *
  29821. * _.takeRight([1, 2, 3]);
  29822. * // => [3]
  29823. *
  29824. * _.takeRight([1, 2, 3], 2);
  29825. * // => [2, 3]
  29826. *
  29827. * _.takeRight([1, 2, 3], 5);
  29828. * // => [1, 2, 3]
  29829. *
  29830. * _.takeRight([1, 2, 3], 0);
  29831. * // => []
  29832. */
  29833. function takeRight(array, n, guard) {
  29834. var length = array == null ? 0 : array.length;
  29835. if (!length) {
  29836. return [];
  29837. }
  29838. n = (guard || n === undefined) ? 1 : toInteger(n);
  29839. n = length - n;
  29840. return baseSlice(array, n < 0 ? 0 : n, length);
  29841. }
  29842. /**
  29843. * Creates a slice of `array` with elements taken from the end. Elements are
  29844. * taken until `predicate` returns falsey. The predicate is invoked with
  29845. * three arguments: (value, index, array).
  29846. *
  29847. * @static
  29848. * @memberOf _
  29849. * @since 3.0.0
  29850. * @category Array
  29851. * @param {Array} array The array to query.
  29852. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  29853. * @returns {Array} Returns the slice of `array`.
  29854. * @example
  29855. *
  29856. * var users = [
  29857. * { 'user': 'barney', 'active': true },
  29858. * { 'user': 'fred', 'active': false },
  29859. * { 'user': 'pebbles', 'active': false }
  29860. * ];
  29861. *
  29862. * _.takeRightWhile(users, function(o) { return !o.active; });
  29863. * // => objects for ['fred', 'pebbles']
  29864. *
  29865. * // The `_.matches` iteratee shorthand.
  29866. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
  29867. * // => objects for ['pebbles']
  29868. *
  29869. * // The `_.matchesProperty` iteratee shorthand.
  29870. * _.takeRightWhile(users, ['active', false]);
  29871. * // => objects for ['fred', 'pebbles']
  29872. *
  29873. * // The `_.property` iteratee shorthand.
  29874. * _.takeRightWhile(users, 'active');
  29875. * // => []
  29876. */
  29877. function takeRightWhile(array, predicate) {
  29878. return (array && array.length)
  29879. ? baseWhile(array, getIteratee(predicate, 3), false, true)
  29880. : [];
  29881. }
  29882. /**
  29883. * Creates a slice of `array` with elements taken from the beginning. Elements
  29884. * are taken until `predicate` returns falsey. The predicate is invoked with
  29885. * three arguments: (value, index, array).
  29886. *
  29887. * @static
  29888. * @memberOf _
  29889. * @since 3.0.0
  29890. * @category Array
  29891. * @param {Array} array The array to query.
  29892. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  29893. * @returns {Array} Returns the slice of `array`.
  29894. * @example
  29895. *
  29896. * var users = [
  29897. * { 'user': 'barney', 'active': false },
  29898. * { 'user': 'fred', 'active': false },
  29899. * { 'user': 'pebbles', 'active': true }
  29900. * ];
  29901. *
  29902. * _.takeWhile(users, function(o) { return !o.active; });
  29903. * // => objects for ['barney', 'fred']
  29904. *
  29905. * // The `_.matches` iteratee shorthand.
  29906. * _.takeWhile(users, { 'user': 'barney', 'active': false });
  29907. * // => objects for ['barney']
  29908. *
  29909. * // The `_.matchesProperty` iteratee shorthand.
  29910. * _.takeWhile(users, ['active', false]);
  29911. * // => objects for ['barney', 'fred']
  29912. *
  29913. * // The `_.property` iteratee shorthand.
  29914. * _.takeWhile(users, 'active');
  29915. * // => []
  29916. */
  29917. function takeWhile(array, predicate) {
  29918. return (array && array.length)
  29919. ? baseWhile(array, getIteratee(predicate, 3))
  29920. : [];
  29921. }
  29922. /**
  29923. * Creates an array of unique values, in order, from all given arrays using
  29924. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  29925. * for equality comparisons.
  29926. *
  29927. * @static
  29928. * @memberOf _
  29929. * @since 0.1.0
  29930. * @category Array
  29931. * @param {...Array} [arrays] The arrays to inspect.
  29932. * @returns {Array} Returns the new array of combined values.
  29933. * @example
  29934. *
  29935. * _.union([2], [1, 2]);
  29936. * // => [2, 1]
  29937. */
  29938. var union = baseRest(function(arrays) {
  29939. return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
  29940. });
  29941. /**
  29942. * This method is like `_.union` except that it accepts `iteratee` which is
  29943. * invoked for each element of each `arrays` to generate the criterion by
  29944. * which uniqueness is computed. Result values are chosen from the first
  29945. * array in which the value occurs. The iteratee is invoked with one argument:
  29946. * (value).
  29947. *
  29948. * @static
  29949. * @memberOf _
  29950. * @since 4.0.0
  29951. * @category Array
  29952. * @param {...Array} [arrays] The arrays to inspect.
  29953. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  29954. * @returns {Array} Returns the new array of combined values.
  29955. * @example
  29956. *
  29957. * _.unionBy([2.1], [1.2, 2.3], Math.floor);
  29958. * // => [2.1, 1.2]
  29959. *
  29960. * // The `_.property` iteratee shorthand.
  29961. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
  29962. * // => [{ 'x': 1 }, { 'x': 2 }]
  29963. */
  29964. var unionBy = baseRest(function(arrays) {
  29965. var iteratee = last(arrays);
  29966. if (isArrayLikeObject(iteratee)) {
  29967. iteratee = undefined;
  29968. }
  29969. return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
  29970. });
  29971. /**
  29972. * This method is like `_.union` except that it accepts `comparator` which
  29973. * is invoked to compare elements of `arrays`. Result values are chosen from
  29974. * the first array in which the value occurs. The comparator is invoked
  29975. * with two arguments: (arrVal, othVal).
  29976. *
  29977. * @static
  29978. * @memberOf _
  29979. * @since 4.0.0
  29980. * @category Array
  29981. * @param {...Array} [arrays] The arrays to inspect.
  29982. * @param {Function} [comparator] The comparator invoked per element.
  29983. * @returns {Array} Returns the new array of combined values.
  29984. * @example
  29985. *
  29986. * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
  29987. * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
  29988. *
  29989. * _.unionWith(objects, others, _.isEqual);
  29990. * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
  29991. */
  29992. var unionWith = baseRest(function(arrays) {
  29993. var comparator = last(arrays);
  29994. comparator = typeof comparator == 'function' ? comparator : undefined;
  29995. return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
  29996. });
  29997. /**
  29998. * Creates a duplicate-free version of an array, using
  29999. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  30000. * for equality comparisons, in which only the first occurrence of each element
  30001. * is kept. The order of result values is determined by the order they occur
  30002. * in the array.
  30003. *
  30004. * @static
  30005. * @memberOf _
  30006. * @since 0.1.0
  30007. * @category Array
  30008. * @param {Array} array The array to inspect.
  30009. * @returns {Array} Returns the new duplicate free array.
  30010. * @example
  30011. *
  30012. * _.uniq([2, 1, 2]);
  30013. * // => [2, 1]
  30014. */
  30015. function uniq(array) {
  30016. return (array && array.length) ? baseUniq(array) : [];
  30017. }
  30018. /**
  30019. * This method is like `_.uniq` except that it accepts `iteratee` which is
  30020. * invoked for each element in `array` to generate the criterion by which
  30021. * uniqueness is computed. The order of result values is determined by the
  30022. * order they occur in the array. The iteratee is invoked with one argument:
  30023. * (value).
  30024. *
  30025. * @static
  30026. * @memberOf _
  30027. * @since 4.0.0
  30028. * @category Array
  30029. * @param {Array} array The array to inspect.
  30030. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  30031. * @returns {Array} Returns the new duplicate free array.
  30032. * @example
  30033. *
  30034. * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
  30035. * // => [2.1, 1.2]
  30036. *
  30037. * // The `_.property` iteratee shorthand.
  30038. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
  30039. * // => [{ 'x': 1 }, { 'x': 2 }]
  30040. */
  30041. function uniqBy(array, iteratee) {
  30042. return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];
  30043. }
  30044. /**
  30045. * This method is like `_.uniq` except that it accepts `comparator` which
  30046. * is invoked to compare elements of `array`. The order of result values is
  30047. * determined by the order they occur in the array.The comparator is invoked
  30048. * with two arguments: (arrVal, othVal).
  30049. *
  30050. * @static
  30051. * @memberOf _
  30052. * @since 4.0.0
  30053. * @category Array
  30054. * @param {Array} array The array to inspect.
  30055. * @param {Function} [comparator] The comparator invoked per element.
  30056. * @returns {Array} Returns the new duplicate free array.
  30057. * @example
  30058. *
  30059. * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
  30060. *
  30061. * _.uniqWith(objects, _.isEqual);
  30062. * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
  30063. */
  30064. function uniqWith(array, comparator) {
  30065. comparator = typeof comparator == 'function' ? comparator : undefined;
  30066. return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
  30067. }
  30068. /**
  30069. * This method is like `_.zip` except that it accepts an array of grouped
  30070. * elements and creates an array regrouping the elements to their pre-zip
  30071. * configuration.
  30072. *
  30073. * @static
  30074. * @memberOf _
  30075. * @since 1.2.0
  30076. * @category Array
  30077. * @param {Array} array The array of grouped elements to process.
  30078. * @returns {Array} Returns the new array of regrouped elements.
  30079. * @example
  30080. *
  30081. * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
  30082. * // => [['a', 1, true], ['b', 2, false]]
  30083. *
  30084. * _.unzip(zipped);
  30085. * // => [['a', 'b'], [1, 2], [true, false]]
  30086. */
  30087. function unzip(array) {
  30088. if (!(array && array.length)) {
  30089. return [];
  30090. }
  30091. var length = 0;
  30092. array = arrayFilter(array, function(group) {
  30093. if (isArrayLikeObject(group)) {
  30094. length = nativeMax(group.length, length);
  30095. return true;
  30096. }
  30097. });
  30098. return baseTimes(length, function(index) {
  30099. return arrayMap(array, baseProperty(index));
  30100. });
  30101. }
  30102. /**
  30103. * This method is like `_.unzip` except that it accepts `iteratee` to specify
  30104. * how regrouped values should be combined. The iteratee is invoked with the
  30105. * elements of each group: (...group).
  30106. *
  30107. * @static
  30108. * @memberOf _
  30109. * @since 3.8.0
  30110. * @category Array
  30111. * @param {Array} array The array of grouped elements to process.
  30112. * @param {Function} [iteratee=_.identity] The function to combine
  30113. * regrouped values.
  30114. * @returns {Array} Returns the new array of regrouped elements.
  30115. * @example
  30116. *
  30117. * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
  30118. * // => [[1, 10, 100], [2, 20, 200]]
  30119. *
  30120. * _.unzipWith(zipped, _.add);
  30121. * // => [3, 30, 300]
  30122. */
  30123. function unzipWith(array, iteratee) {
  30124. if (!(array && array.length)) {
  30125. return [];
  30126. }
  30127. var result = unzip(array);
  30128. if (iteratee == null) {
  30129. return result;
  30130. }
  30131. return arrayMap(result, function(group) {
  30132. return apply(iteratee, undefined, group);
  30133. });
  30134. }
  30135. /**
  30136. * Creates an array excluding all given values using
  30137. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  30138. * for equality comparisons.
  30139. *
  30140. * **Note:** Unlike `_.pull`, this method returns a new array.
  30141. *
  30142. * @static
  30143. * @memberOf _
  30144. * @since 0.1.0
  30145. * @category Array
  30146. * @param {Array} array The array to inspect.
  30147. * @param {...*} [values] The values to exclude.
  30148. * @returns {Array} Returns the new array of filtered values.
  30149. * @see _.difference, _.xor
  30150. * @example
  30151. *
  30152. * _.without([2, 1, 2, 3], 1, 2);
  30153. * // => [3]
  30154. */
  30155. var without = baseRest(function(array, values) {
  30156. return isArrayLikeObject(array)
  30157. ? baseDifference(array, values)
  30158. : [];
  30159. });
  30160. /**
  30161. * Creates an array of unique values that is the
  30162. * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
  30163. * of the given arrays. The order of result values is determined by the order
  30164. * they occur in the arrays.
  30165. *
  30166. * @static
  30167. * @memberOf _
  30168. * @since 2.4.0
  30169. * @category Array
  30170. * @param {...Array} [arrays] The arrays to inspect.
  30171. * @returns {Array} Returns the new array of filtered values.
  30172. * @see _.difference, _.without
  30173. * @example
  30174. *
  30175. * _.xor([2, 1], [2, 3]);
  30176. * // => [1, 3]
  30177. */
  30178. var xor = baseRest(function(arrays) {
  30179. return baseXor(arrayFilter(arrays, isArrayLikeObject));
  30180. });
  30181. /**
  30182. * This method is like `_.xor` except that it accepts `iteratee` which is
  30183. * invoked for each element of each `arrays` to generate the criterion by
  30184. * which by which they're compared. The order of result values is determined
  30185. * by the order they occur in the arrays. The iteratee is invoked with one
  30186. * argument: (value).
  30187. *
  30188. * @static
  30189. * @memberOf _
  30190. * @since 4.0.0
  30191. * @category Array
  30192. * @param {...Array} [arrays] The arrays to inspect.
  30193. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  30194. * @returns {Array} Returns the new array of filtered values.
  30195. * @example
  30196. *
  30197. * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
  30198. * // => [1.2, 3.4]
  30199. *
  30200. * // The `_.property` iteratee shorthand.
  30201. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
  30202. * // => [{ 'x': 2 }]
  30203. */
  30204. var xorBy = baseRest(function(arrays) {
  30205. var iteratee = last(arrays);
  30206. if (isArrayLikeObject(iteratee)) {
  30207. iteratee = undefined;
  30208. }
  30209. return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
  30210. });
  30211. /**
  30212. * This method is like `_.xor` except that it accepts `comparator` which is
  30213. * invoked to compare elements of `arrays`. The order of result values is
  30214. * determined by the order they occur in the arrays. The comparator is invoked
  30215. * with two arguments: (arrVal, othVal).
  30216. *
  30217. * @static
  30218. * @memberOf _
  30219. * @since 4.0.0
  30220. * @category Array
  30221. * @param {...Array} [arrays] The arrays to inspect.
  30222. * @param {Function} [comparator] The comparator invoked per element.
  30223. * @returns {Array} Returns the new array of filtered values.
  30224. * @example
  30225. *
  30226. * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
  30227. * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
  30228. *
  30229. * _.xorWith(objects, others, _.isEqual);
  30230. * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
  30231. */
  30232. var xorWith = baseRest(function(arrays) {
  30233. var comparator = last(arrays);
  30234. comparator = typeof comparator == 'function' ? comparator : undefined;
  30235. return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
  30236. });
  30237. /**
  30238. * Creates an array of grouped elements, the first of which contains the
  30239. * first elements of the given arrays, the second of which contains the
  30240. * second elements of the given arrays, and so on.
  30241. *
  30242. * @static
  30243. * @memberOf _
  30244. * @since 0.1.0
  30245. * @category Array
  30246. * @param {...Array} [arrays] The arrays to process.
  30247. * @returns {Array} Returns the new array of grouped elements.
  30248. * @example
  30249. *
  30250. * _.zip(['a', 'b'], [1, 2], [true, false]);
  30251. * // => [['a', 1, true], ['b', 2, false]]
  30252. */
  30253. var zip = baseRest(unzip);
  30254. /**
  30255. * This method is like `_.fromPairs` except that it accepts two arrays,
  30256. * one of property identifiers and one of corresponding values.
  30257. *
  30258. * @static
  30259. * @memberOf _
  30260. * @since 0.4.0
  30261. * @category Array
  30262. * @param {Array} [props=[]] The property identifiers.
  30263. * @param {Array} [values=[]] The property values.
  30264. * @returns {Object} Returns the new object.
  30265. * @example
  30266. *
  30267. * _.zipObject(['a', 'b'], [1, 2]);
  30268. * // => { 'a': 1, 'b': 2 }
  30269. */
  30270. function zipObject(props, values) {
  30271. return baseZipObject(props || [], values || [], assignValue);
  30272. }
  30273. /**
  30274. * This method is like `_.zipObject` except that it supports property paths.
  30275. *
  30276. * @static
  30277. * @memberOf _
  30278. * @since 4.1.0
  30279. * @category Array
  30280. * @param {Array} [props=[]] The property identifiers.
  30281. * @param {Array} [values=[]] The property values.
  30282. * @returns {Object} Returns the new object.
  30283. * @example
  30284. *
  30285. * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
  30286. * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
  30287. */
  30288. function zipObjectDeep(props, values) {
  30289. return baseZipObject(props || [], values || [], baseSet);
  30290. }
  30291. /**
  30292. * This method is like `_.zip` except that it accepts `iteratee` to specify
  30293. * how grouped values should be combined. The iteratee is invoked with the
  30294. * elements of each group: (...group).
  30295. *
  30296. * @static
  30297. * @memberOf _
  30298. * @since 3.8.0
  30299. * @category Array
  30300. * @param {...Array} [arrays] The arrays to process.
  30301. * @param {Function} [iteratee=_.identity] The function to combine
  30302. * grouped values.
  30303. * @returns {Array} Returns the new array of grouped elements.
  30304. * @example
  30305. *
  30306. * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
  30307. * return a + b + c;
  30308. * });
  30309. * // => [111, 222]
  30310. */
  30311. var zipWith = baseRest(function(arrays) {
  30312. var length = arrays.length,
  30313. iteratee = length > 1 ? arrays[length - 1] : undefined;
  30314. iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
  30315. return unzipWith(arrays, iteratee);
  30316. });
  30317. /*------------------------------------------------------------------------*/
  30318. /**
  30319. * Creates a `lodash` wrapper instance that wraps `value` with explicit method
  30320. * chain sequences enabled. The result of such sequences must be unwrapped
  30321. * with `_#value`.
  30322. *
  30323. * @static
  30324. * @memberOf _
  30325. * @since 1.3.0
  30326. * @category Seq
  30327. * @param {*} value The value to wrap.
  30328. * @returns {Object} Returns the new `lodash` wrapper instance.
  30329. * @example
  30330. *
  30331. * var users = [
  30332. * { 'user': 'barney', 'age': 36 },
  30333. * { 'user': 'fred', 'age': 40 },
  30334. * { 'user': 'pebbles', 'age': 1 }
  30335. * ];
  30336. *
  30337. * var youngest = _
  30338. * .chain(users)
  30339. * .sortBy('age')
  30340. * .map(function(o) {
  30341. * return o.user + ' is ' + o.age;
  30342. * })
  30343. * .head()
  30344. * .value();
  30345. * // => 'pebbles is 1'
  30346. */
  30347. function chain(value) {
  30348. var result = lodash(value);
  30349. result.__chain__ = true;
  30350. return result;
  30351. }
  30352. /**
  30353. * This method invokes `interceptor` and returns `value`. The interceptor
  30354. * is invoked with one argument; (value). The purpose of this method is to
  30355. * "tap into" a method chain sequence in order to modify intermediate results.
  30356. *
  30357. * @static
  30358. * @memberOf _
  30359. * @since 0.1.0
  30360. * @category Seq
  30361. * @param {*} value The value to provide to `interceptor`.
  30362. * @param {Function} interceptor The function to invoke.
  30363. * @returns {*} Returns `value`.
  30364. * @example
  30365. *
  30366. * _([1, 2, 3])
  30367. * .tap(function(array) {
  30368. * // Mutate input array.
  30369. * array.pop();
  30370. * })
  30371. * .reverse()
  30372. * .value();
  30373. * // => [2, 1]
  30374. */
  30375. function tap(value, interceptor) {
  30376. interceptor(value);
  30377. return value;
  30378. }
  30379. /**
  30380. * This method is like `_.tap` except that it returns the result of `interceptor`.
  30381. * The purpose of this method is to "pass thru" values replacing intermediate
  30382. * results in a method chain sequence.
  30383. *
  30384. * @static
  30385. * @memberOf _
  30386. * @since 3.0.0
  30387. * @category Seq
  30388. * @param {*} value The value to provide to `interceptor`.
  30389. * @param {Function} interceptor The function to invoke.
  30390. * @returns {*} Returns the result of `interceptor`.
  30391. * @example
  30392. *
  30393. * _(' abc ')
  30394. * .chain()
  30395. * .trim()
  30396. * .thru(function(value) {
  30397. * return [value];
  30398. * })
  30399. * .value();
  30400. * // => ['abc']
  30401. */
  30402. function thru(value, interceptor) {
  30403. return interceptor(value);
  30404. }
  30405. /**
  30406. * This method is the wrapper version of `_.at`.
  30407. *
  30408. * @name at
  30409. * @memberOf _
  30410. * @since 1.0.0
  30411. * @category Seq
  30412. * @param {...(string|string[])} [paths] The property paths to pick.
  30413. * @returns {Object} Returns the new `lodash` wrapper instance.
  30414. * @example
  30415. *
  30416. * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
  30417. *
  30418. * _(object).at(['a[0].b.c', 'a[1]']).value();
  30419. * // => [3, 4]
  30420. */
  30421. var wrapperAt = flatRest(function(paths) {
  30422. var length = paths.length,
  30423. start = length ? paths[0] : 0,
  30424. value = this.__wrapped__,
  30425. interceptor = function(object) { return baseAt(object, paths); };
  30426. if (length > 1 || this.__actions__.length ||
  30427. !(value instanceof LazyWrapper) || !isIndex(start)) {
  30428. return this.thru(interceptor);
  30429. }
  30430. value = value.slice(start, +start + (length ? 1 : 0));
  30431. value.__actions__.push({
  30432. 'func': thru,
  30433. 'args': [interceptor],
  30434. 'thisArg': undefined
  30435. });
  30436. return new LodashWrapper(value, this.__chain__).thru(function(array) {
  30437. if (length && !array.length) {
  30438. array.push(undefined);
  30439. }
  30440. return array;
  30441. });
  30442. });
  30443. /**
  30444. * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
  30445. *
  30446. * @name chain
  30447. * @memberOf _
  30448. * @since 0.1.0
  30449. * @category Seq
  30450. * @returns {Object} Returns the new `lodash` wrapper instance.
  30451. * @example
  30452. *
  30453. * var users = [
  30454. * { 'user': 'barney', 'age': 36 },
  30455. * { 'user': 'fred', 'age': 40 }
  30456. * ];
  30457. *
  30458. * // A sequence without explicit chaining.
  30459. * _(users).head();
  30460. * // => { 'user': 'barney', 'age': 36 }
  30461. *
  30462. * // A sequence with explicit chaining.
  30463. * _(users)
  30464. * .chain()
  30465. * .head()
  30466. * .pick('user')
  30467. * .value();
  30468. * // => { 'user': 'barney' }
  30469. */
  30470. function wrapperChain() {
  30471. return chain(this);
  30472. }
  30473. /**
  30474. * Executes the chain sequence and returns the wrapped result.
  30475. *
  30476. * @name commit
  30477. * @memberOf _
  30478. * @since 3.2.0
  30479. * @category Seq
  30480. * @returns {Object} Returns the new `lodash` wrapper instance.
  30481. * @example
  30482. *
  30483. * var array = [1, 2];
  30484. * var wrapped = _(array).push(3);
  30485. *
  30486. * console.log(array);
  30487. * // => [1, 2]
  30488. *
  30489. * wrapped = wrapped.commit();
  30490. * console.log(array);
  30491. * // => [1, 2, 3]
  30492. *
  30493. * wrapped.last();
  30494. * // => 3
  30495. *
  30496. * console.log(array);
  30497. * // => [1, 2, 3]
  30498. */
  30499. function wrapperCommit() {
  30500. return new LodashWrapper(this.value(), this.__chain__);
  30501. }
  30502. /**
  30503. * Gets the next value on a wrapped object following the
  30504. * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
  30505. *
  30506. * @name next
  30507. * @memberOf _
  30508. * @since 4.0.0
  30509. * @category Seq
  30510. * @returns {Object} Returns the next iterator value.
  30511. * @example
  30512. *
  30513. * var wrapped = _([1, 2]);
  30514. *
  30515. * wrapped.next();
  30516. * // => { 'done': false, 'value': 1 }
  30517. *
  30518. * wrapped.next();
  30519. * // => { 'done': false, 'value': 2 }
  30520. *
  30521. * wrapped.next();
  30522. * // => { 'done': true, 'value': undefined }
  30523. */
  30524. function wrapperNext() {
  30525. if (this.__values__ === undefined) {
  30526. this.__values__ = toArray(this.value());
  30527. }
  30528. var done = this.__index__ >= this.__values__.length,
  30529. value = done ? undefined : this.__values__[this.__index__++];
  30530. return { 'done': done, 'value': value };
  30531. }
  30532. /**
  30533. * Enables the wrapper to be iterable.
  30534. *
  30535. * @name Symbol.iterator
  30536. * @memberOf _
  30537. * @since 4.0.0
  30538. * @category Seq
  30539. * @returns {Object} Returns the wrapper object.
  30540. * @example
  30541. *
  30542. * var wrapped = _([1, 2]);
  30543. *
  30544. * wrapped[Symbol.iterator]() === wrapped;
  30545. * // => true
  30546. *
  30547. * Array.from(wrapped);
  30548. * // => [1, 2]
  30549. */
  30550. function wrapperToIterator() {
  30551. return this;
  30552. }
  30553. /**
  30554. * Creates a clone of the chain sequence planting `value` as the wrapped value.
  30555. *
  30556. * @name plant
  30557. * @memberOf _
  30558. * @since 3.2.0
  30559. * @category Seq
  30560. * @param {*} value The value to plant.
  30561. * @returns {Object} Returns the new `lodash` wrapper instance.
  30562. * @example
  30563. *
  30564. * function square(n) {
  30565. * return n * n;
  30566. * }
  30567. *
  30568. * var wrapped = _([1, 2]).map(square);
  30569. * var other = wrapped.plant([3, 4]);
  30570. *
  30571. * other.value();
  30572. * // => [9, 16]
  30573. *
  30574. * wrapped.value();
  30575. * // => [1, 4]
  30576. */
  30577. function wrapperPlant(value) {
  30578. var result,
  30579. parent = this;
  30580. while (parent instanceof baseLodash) {
  30581. var clone = wrapperClone(parent);
  30582. clone.__index__ = 0;
  30583. clone.__values__ = undefined;
  30584. if (result) {
  30585. previous.__wrapped__ = clone;
  30586. } else {
  30587. result = clone;
  30588. }
  30589. var previous = clone;
  30590. parent = parent.__wrapped__;
  30591. }
  30592. previous.__wrapped__ = value;
  30593. return result;
  30594. }
  30595. /**
  30596. * This method is the wrapper version of `_.reverse`.
  30597. *
  30598. * **Note:** This method mutates the wrapped array.
  30599. *
  30600. * @name reverse
  30601. * @memberOf _
  30602. * @since 0.1.0
  30603. * @category Seq
  30604. * @returns {Object} Returns the new `lodash` wrapper instance.
  30605. * @example
  30606. *
  30607. * var array = [1, 2, 3];
  30608. *
  30609. * _(array).reverse().value()
  30610. * // => [3, 2, 1]
  30611. *
  30612. * console.log(array);
  30613. * // => [3, 2, 1]
  30614. */
  30615. function wrapperReverse() {
  30616. var value = this.__wrapped__;
  30617. if (value instanceof LazyWrapper) {
  30618. var wrapped = value;
  30619. if (this.__actions__.length) {
  30620. wrapped = new LazyWrapper(this);
  30621. }
  30622. wrapped = wrapped.reverse();
  30623. wrapped.__actions__.push({
  30624. 'func': thru,
  30625. 'args': [reverse],
  30626. 'thisArg': undefined
  30627. });
  30628. return new LodashWrapper(wrapped, this.__chain__);
  30629. }
  30630. return this.thru(reverse);
  30631. }
  30632. /**
  30633. * Executes the chain sequence to resolve the unwrapped value.
  30634. *
  30635. * @name value
  30636. * @memberOf _
  30637. * @since 0.1.0
  30638. * @alias toJSON, valueOf
  30639. * @category Seq
  30640. * @returns {*} Returns the resolved unwrapped value.
  30641. * @example
  30642. *
  30643. * _([1, 2, 3]).value();
  30644. * // => [1, 2, 3]
  30645. */
  30646. function wrapperValue() {
  30647. return baseWrapperValue(this.__wrapped__, this.__actions__);
  30648. }
  30649. /*------------------------------------------------------------------------*/
  30650. /**
  30651. * Creates an object composed of keys generated from the results of running
  30652. * each element of `collection` thru `iteratee`. The corresponding value of
  30653. * each key is the number of times the key was returned by `iteratee`. The
  30654. * iteratee is invoked with one argument: (value).
  30655. *
  30656. * @static
  30657. * @memberOf _
  30658. * @since 0.5.0
  30659. * @category Collection
  30660. * @param {Array|Object} collection The collection to iterate over.
  30661. * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
  30662. * @returns {Object} Returns the composed aggregate object.
  30663. * @example
  30664. *
  30665. * _.countBy([6.1, 4.2, 6.3], Math.floor);
  30666. * // => { '4': 1, '6': 2 }
  30667. *
  30668. * // The `_.property` iteratee shorthand.
  30669. * _.countBy(['one', 'two', 'three'], 'length');
  30670. * // => { '3': 2, '5': 1 }
  30671. */
  30672. var countBy = createAggregator(function(result, value, key) {
  30673. if (hasOwnProperty.call(result, key)) {
  30674. ++result[key];
  30675. } else {
  30676. baseAssignValue(result, key, 1);
  30677. }
  30678. });
  30679. /**
  30680. * Checks if `predicate` returns truthy for **all** elements of `collection`.
  30681. * Iteration is stopped once `predicate` returns falsey. The predicate is
  30682. * invoked with three arguments: (value, index|key, collection).
  30683. *
  30684. * **Note:** This method returns `true` for
  30685. * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
  30686. * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
  30687. * elements of empty collections.
  30688. *
  30689. * @static
  30690. * @memberOf _
  30691. * @since 0.1.0
  30692. * @category Collection
  30693. * @param {Array|Object} collection The collection to iterate over.
  30694. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  30695. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  30696. * @returns {boolean} Returns `true` if all elements pass the predicate check,
  30697. * else `false`.
  30698. * @example
  30699. *
  30700. * _.every([true, 1, null, 'yes'], Boolean);
  30701. * // => false
  30702. *
  30703. * var users = [
  30704. * { 'user': 'barney', 'age': 36, 'active': false },
  30705. * { 'user': 'fred', 'age': 40, 'active': false }
  30706. * ];
  30707. *
  30708. * // The `_.matches` iteratee shorthand.
  30709. * _.every(users, { 'user': 'barney', 'active': false });
  30710. * // => false
  30711. *
  30712. * // The `_.matchesProperty` iteratee shorthand.
  30713. * _.every(users, ['active', false]);
  30714. * // => true
  30715. *
  30716. * // The `_.property` iteratee shorthand.
  30717. * _.every(users, 'active');
  30718. * // => false
  30719. */
  30720. function every(collection, predicate, guard) {
  30721. var func = isArray(collection) ? arrayEvery : baseEvery;
  30722. if (guard && isIterateeCall(collection, predicate, guard)) {
  30723. predicate = undefined;
  30724. }
  30725. return func(collection, getIteratee(predicate, 3));
  30726. }
  30727. /**
  30728. * Iterates over elements of `collection`, returning an array of all elements
  30729. * `predicate` returns truthy for. The predicate is invoked with three
  30730. * arguments: (value, index|key, collection).
  30731. *
  30732. * **Note:** Unlike `_.remove`, this method returns a new array.
  30733. *
  30734. * @static
  30735. * @memberOf _
  30736. * @since 0.1.0
  30737. * @category Collection
  30738. * @param {Array|Object} collection The collection to iterate over.
  30739. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  30740. * @returns {Array} Returns the new filtered array.
  30741. * @see _.reject
  30742. * @example
  30743. *
  30744. * var users = [
  30745. * { 'user': 'barney', 'age': 36, 'active': true },
  30746. * { 'user': 'fred', 'age': 40, 'active': false }
  30747. * ];
  30748. *
  30749. * _.filter(users, function(o) { return !o.active; });
  30750. * // => objects for ['fred']
  30751. *
  30752. * // The `_.matches` iteratee shorthand.
  30753. * _.filter(users, { 'age': 36, 'active': true });
  30754. * // => objects for ['barney']
  30755. *
  30756. * // The `_.matchesProperty` iteratee shorthand.
  30757. * _.filter(users, ['active', false]);
  30758. * // => objects for ['fred']
  30759. *
  30760. * // The `_.property` iteratee shorthand.
  30761. * _.filter(users, 'active');
  30762. * // => objects for ['barney']
  30763. */
  30764. function filter(collection, predicate) {
  30765. var func = isArray(collection) ? arrayFilter : baseFilter;
  30766. return func(collection, getIteratee(predicate, 3));
  30767. }
  30768. /**
  30769. * Iterates over elements of `collection`, returning the first element
  30770. * `predicate` returns truthy for. The predicate is invoked with three
  30771. * arguments: (value, index|key, collection).
  30772. *
  30773. * @static
  30774. * @memberOf _
  30775. * @since 0.1.0
  30776. * @category Collection
  30777. * @param {Array|Object} collection The collection to inspect.
  30778. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  30779. * @param {number} [fromIndex=0] The index to search from.
  30780. * @returns {*} Returns the matched element, else `undefined`.
  30781. * @example
  30782. *
  30783. * var users = [
  30784. * { 'user': 'barney', 'age': 36, 'active': true },
  30785. * { 'user': 'fred', 'age': 40, 'active': false },
  30786. * { 'user': 'pebbles', 'age': 1, 'active': true }
  30787. * ];
  30788. *
  30789. * _.find(users, function(o) { return o.age < 40; });
  30790. * // => object for 'barney'
  30791. *
  30792. * // The `_.matches` iteratee shorthand.
  30793. * _.find(users, { 'age': 1, 'active': true });
  30794. * // => object for 'pebbles'
  30795. *
  30796. * // The `_.matchesProperty` iteratee shorthand.
  30797. * _.find(users, ['active', false]);
  30798. * // => object for 'fred'
  30799. *
  30800. * // The `_.property` iteratee shorthand.
  30801. * _.find(users, 'active');
  30802. * // => object for 'barney'
  30803. */
  30804. var find = createFind(findIndex);
  30805. /**
  30806. * This method is like `_.find` except that it iterates over elements of
  30807. * `collection` from right to left.
  30808. *
  30809. * @static
  30810. * @memberOf _
  30811. * @since 2.0.0
  30812. * @category Collection
  30813. * @param {Array|Object} collection The collection to inspect.
  30814. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  30815. * @param {number} [fromIndex=collection.length-1] The index to search from.
  30816. * @returns {*} Returns the matched element, else `undefined`.
  30817. * @example
  30818. *
  30819. * _.findLast([1, 2, 3, 4], function(n) {
  30820. * return n % 2 == 1;
  30821. * });
  30822. * // => 3
  30823. */
  30824. var findLast = createFind(findLastIndex);
  30825. /**
  30826. * Creates a flattened array of values by running each element in `collection`
  30827. * thru `iteratee` and flattening the mapped results. The iteratee is invoked
  30828. * with three arguments: (value, index|key, collection).
  30829. *
  30830. * @static
  30831. * @memberOf _
  30832. * @since 4.0.0
  30833. * @category Collection
  30834. * @param {Array|Object} collection The collection to iterate over.
  30835. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  30836. * @returns {Array} Returns the new flattened array.
  30837. * @example
  30838. *
  30839. * function duplicate(n) {
  30840. * return [n, n];
  30841. * }
  30842. *
  30843. * _.flatMap([1, 2], duplicate);
  30844. * // => [1, 1, 2, 2]
  30845. */
  30846. function flatMap(collection, iteratee) {
  30847. return baseFlatten(map(collection, iteratee), 1);
  30848. }
  30849. /**
  30850. * This method is like `_.flatMap` except that it recursively flattens the
  30851. * mapped results.
  30852. *
  30853. * @static
  30854. * @memberOf _
  30855. * @since 4.7.0
  30856. * @category Collection
  30857. * @param {Array|Object} collection The collection to iterate over.
  30858. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  30859. * @returns {Array} Returns the new flattened array.
  30860. * @example
  30861. *
  30862. * function duplicate(n) {
  30863. * return [[[n, n]]];
  30864. * }
  30865. *
  30866. * _.flatMapDeep([1, 2], duplicate);
  30867. * // => [1, 1, 2, 2]
  30868. */
  30869. function flatMapDeep(collection, iteratee) {
  30870. return baseFlatten(map(collection, iteratee), INFINITY);
  30871. }
  30872. /**
  30873. * This method is like `_.flatMap` except that it recursively flattens the
  30874. * mapped results up to `depth` times.
  30875. *
  30876. * @static
  30877. * @memberOf _
  30878. * @since 4.7.0
  30879. * @category Collection
  30880. * @param {Array|Object} collection The collection to iterate over.
  30881. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  30882. * @param {number} [depth=1] The maximum recursion depth.
  30883. * @returns {Array} Returns the new flattened array.
  30884. * @example
  30885. *
  30886. * function duplicate(n) {
  30887. * return [[[n, n]]];
  30888. * }
  30889. *
  30890. * _.flatMapDepth([1, 2], duplicate, 2);
  30891. * // => [[1, 1], [2, 2]]
  30892. */
  30893. function flatMapDepth(collection, iteratee, depth) {
  30894. depth = depth === undefined ? 1 : toInteger(depth);
  30895. return baseFlatten(map(collection, iteratee), depth);
  30896. }
  30897. /**
  30898. * Iterates over elements of `collection` and invokes `iteratee` for each element.
  30899. * The iteratee is invoked with three arguments: (value, index|key, collection).
  30900. * Iteratee functions may exit iteration early by explicitly returning `false`.
  30901. *
  30902. * **Note:** As with other "Collections" methods, objects with a "length"
  30903. * property are iterated like arrays. To avoid this behavior use `_.forIn`
  30904. * or `_.forOwn` for object iteration.
  30905. *
  30906. * @static
  30907. * @memberOf _
  30908. * @since 0.1.0
  30909. * @alias each
  30910. * @category Collection
  30911. * @param {Array|Object} collection The collection to iterate over.
  30912. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  30913. * @returns {Array|Object} Returns `collection`.
  30914. * @see _.forEachRight
  30915. * @example
  30916. *
  30917. * _.forEach([1, 2], function(value) {
  30918. * console.log(value);
  30919. * });
  30920. * // => Logs `1` then `2`.
  30921. *
  30922. * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  30923. * console.log(key);
  30924. * });
  30925. * // => Logs 'a' then 'b' (iteration order is not guaranteed).
  30926. */
  30927. function forEach(collection, iteratee) {
  30928. var func = isArray(collection) ? arrayEach : baseEach;
  30929. return func(collection, getIteratee(iteratee, 3));
  30930. }
  30931. /**
  30932. * This method is like `_.forEach` except that it iterates over elements of
  30933. * `collection` from right to left.
  30934. *
  30935. * @static
  30936. * @memberOf _
  30937. * @since 2.0.0
  30938. * @alias eachRight
  30939. * @category Collection
  30940. * @param {Array|Object} collection The collection to iterate over.
  30941. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  30942. * @returns {Array|Object} Returns `collection`.
  30943. * @see _.forEach
  30944. * @example
  30945. *
  30946. * _.forEachRight([1, 2], function(value) {
  30947. * console.log(value);
  30948. * });
  30949. * // => Logs `2` then `1`.
  30950. */
  30951. function forEachRight(collection, iteratee) {
  30952. var func = isArray(collection) ? arrayEachRight : baseEachRight;
  30953. return func(collection, getIteratee(iteratee, 3));
  30954. }
  30955. /**
  30956. * Creates an object composed of keys generated from the results of running
  30957. * each element of `collection` thru `iteratee`. The order of grouped values
  30958. * is determined by the order they occur in `collection`. The corresponding
  30959. * value of each key is an array of elements responsible for generating the
  30960. * key. The iteratee is invoked with one argument: (value).
  30961. *
  30962. * @static
  30963. * @memberOf _
  30964. * @since 0.1.0
  30965. * @category Collection
  30966. * @param {Array|Object} collection The collection to iterate over.
  30967. * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
  30968. * @returns {Object} Returns the composed aggregate object.
  30969. * @example
  30970. *
  30971. * _.groupBy([6.1, 4.2, 6.3], Math.floor);
  30972. * // => { '4': [4.2], '6': [6.1, 6.3] }
  30973. *
  30974. * // The `_.property` iteratee shorthand.
  30975. * _.groupBy(['one', 'two', 'three'], 'length');
  30976. * // => { '3': ['one', 'two'], '5': ['three'] }
  30977. */
  30978. var groupBy = createAggregator(function(result, value, key) {
  30979. if (hasOwnProperty.call(result, key)) {
  30980. result[key].push(value);
  30981. } else {
  30982. baseAssignValue(result, key, [value]);
  30983. }
  30984. });
  30985. /**
  30986. * Checks if `value` is in `collection`. If `collection` is a string, it's
  30987. * checked for a substring of `value`, otherwise
  30988. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  30989. * is used for equality comparisons. If `fromIndex` is negative, it's used as
  30990. * the offset from the end of `collection`.
  30991. *
  30992. * @static
  30993. * @memberOf _
  30994. * @since 0.1.0
  30995. * @category Collection
  30996. * @param {Array|Object|string} collection The collection to inspect.
  30997. * @param {*} value The value to search for.
  30998. * @param {number} [fromIndex=0] The index to search from.
  30999. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
  31000. * @returns {boolean} Returns `true` if `value` is found, else `false`.
  31001. * @example
  31002. *
  31003. * _.includes([1, 2, 3], 1);
  31004. * // => true
  31005. *
  31006. * _.includes([1, 2, 3], 1, 2);
  31007. * // => false
  31008. *
  31009. * _.includes({ 'a': 1, 'b': 2 }, 1);
  31010. * // => true
  31011. *
  31012. * _.includes('abcd', 'bc');
  31013. * // => true
  31014. */
  31015. function includes(collection, value, fromIndex, guard) {
  31016. collection = isArrayLike(collection) ? collection : values(collection);
  31017. fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
  31018. var length = collection.length;
  31019. if (fromIndex < 0) {
  31020. fromIndex = nativeMax(length + fromIndex, 0);
  31021. }
  31022. return isString(collection)
  31023. ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
  31024. : (!!length && baseIndexOf(collection, value, fromIndex) > -1);
  31025. }
  31026. /**
  31027. * Invokes the method at `path` of each element in `collection`, returning
  31028. * an array of the results of each invoked method. Any additional arguments
  31029. * are provided to each invoked method. If `path` is a function, it's invoked
  31030. * for, and `this` bound to, each element in `collection`.
  31031. *
  31032. * @static
  31033. * @memberOf _
  31034. * @since 4.0.0
  31035. * @category Collection
  31036. * @param {Array|Object} collection The collection to iterate over.
  31037. * @param {Array|Function|string} path The path of the method to invoke or
  31038. * the function invoked per iteration.
  31039. * @param {...*} [args] The arguments to invoke each method with.
  31040. * @returns {Array} Returns the array of results.
  31041. * @example
  31042. *
  31043. * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
  31044. * // => [[1, 5, 7], [1, 2, 3]]
  31045. *
  31046. * _.invokeMap([123, 456], String.prototype.split, '');
  31047. * // => [['1', '2', '3'], ['4', '5', '6']]
  31048. */
  31049. var invokeMap = baseRest(function(collection, path, args) {
  31050. var index = -1,
  31051. isFunc = typeof path == 'function',
  31052. result = isArrayLike(collection) ? Array(collection.length) : [];
  31053. baseEach(collection, function(value) {
  31054. result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
  31055. });
  31056. return result;
  31057. });
  31058. /**
  31059. * Creates an object composed of keys generated from the results of running
  31060. * each element of `collection` thru `iteratee`. The corresponding value of
  31061. * each key is the last element responsible for generating the key. The
  31062. * iteratee is invoked with one argument: (value).
  31063. *
  31064. * @static
  31065. * @memberOf _
  31066. * @since 4.0.0
  31067. * @category Collection
  31068. * @param {Array|Object} collection The collection to iterate over.
  31069. * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
  31070. * @returns {Object} Returns the composed aggregate object.
  31071. * @example
  31072. *
  31073. * var array = [
  31074. * { 'dir': 'left', 'code': 97 },
  31075. * { 'dir': 'right', 'code': 100 }
  31076. * ];
  31077. *
  31078. * _.keyBy(array, function(o) {
  31079. * return String.fromCharCode(o.code);
  31080. * });
  31081. * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
  31082. *
  31083. * _.keyBy(array, 'dir');
  31084. * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
  31085. */
  31086. var keyBy = createAggregator(function(result, value, key) {
  31087. baseAssignValue(result, key, value);
  31088. });
  31089. /**
  31090. * Creates an array of values by running each element in `collection` thru
  31091. * `iteratee`. The iteratee is invoked with three arguments:
  31092. * (value, index|key, collection).
  31093. *
  31094. * Many lodash methods are guarded to work as iteratees for methods like
  31095. * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
  31096. *
  31097. * The guarded methods are:
  31098. * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
  31099. * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
  31100. * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
  31101. * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
  31102. *
  31103. * @static
  31104. * @memberOf _
  31105. * @since 0.1.0
  31106. * @category Collection
  31107. * @param {Array|Object} collection The collection to iterate over.
  31108. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  31109. * @returns {Array} Returns the new mapped array.
  31110. * @example
  31111. *
  31112. * function square(n) {
  31113. * return n * n;
  31114. * }
  31115. *
  31116. * _.map([4, 8], square);
  31117. * // => [16, 64]
  31118. *
  31119. * _.map({ 'a': 4, 'b': 8 }, square);
  31120. * // => [16, 64] (iteration order is not guaranteed)
  31121. *
  31122. * var users = [
  31123. * { 'user': 'barney' },
  31124. * { 'user': 'fred' }
  31125. * ];
  31126. *
  31127. * // The `_.property` iteratee shorthand.
  31128. * _.map(users, 'user');
  31129. * // => ['barney', 'fred']
  31130. */
  31131. function map(collection, iteratee) {
  31132. var func = isArray(collection) ? arrayMap : baseMap;
  31133. return func(collection, getIteratee(iteratee, 3));
  31134. }
  31135. /**
  31136. * This method is like `_.sortBy` except that it allows specifying the sort
  31137. * orders of the iteratees to sort by. If `orders` is unspecified, all values
  31138. * are sorted in ascending order. Otherwise, specify an order of "desc" for
  31139. * descending or "asc" for ascending sort order of corresponding values.
  31140. *
  31141. * @static
  31142. * @memberOf _
  31143. * @since 4.0.0
  31144. * @category Collection
  31145. * @param {Array|Object} collection The collection to iterate over.
  31146. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
  31147. * The iteratees to sort by.
  31148. * @param {string[]} [orders] The sort orders of `iteratees`.
  31149. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
  31150. * @returns {Array} Returns the new sorted array.
  31151. * @example
  31152. *
  31153. * var users = [
  31154. * { 'user': 'fred', 'age': 48 },
  31155. * { 'user': 'barney', 'age': 34 },
  31156. * { 'user': 'fred', 'age': 40 },
  31157. * { 'user': 'barney', 'age': 36 }
  31158. * ];
  31159. *
  31160. * // Sort by `user` in ascending order and by `age` in descending order.
  31161. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
  31162. * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
  31163. */
  31164. function orderBy(collection, iteratees, orders, guard) {
  31165. if (collection == null) {
  31166. return [];
  31167. }
  31168. if (!isArray(iteratees)) {
  31169. iteratees = iteratees == null ? [] : [iteratees];
  31170. }
  31171. orders = guard ? undefined : orders;
  31172. if (!isArray(orders)) {
  31173. orders = orders == null ? [] : [orders];
  31174. }
  31175. return baseOrderBy(collection, iteratees, orders);
  31176. }
  31177. /**
  31178. * Creates an array of elements split into two groups, the first of which
  31179. * contains elements `predicate` returns truthy for, the second of which
  31180. * contains elements `predicate` returns falsey for. The predicate is
  31181. * invoked with one argument: (value).
  31182. *
  31183. * @static
  31184. * @memberOf _
  31185. * @since 3.0.0
  31186. * @category Collection
  31187. * @param {Array|Object} collection The collection to iterate over.
  31188. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  31189. * @returns {Array} Returns the array of grouped elements.
  31190. * @example
  31191. *
  31192. * var users = [
  31193. * { 'user': 'barney', 'age': 36, 'active': false },
  31194. * { 'user': 'fred', 'age': 40, 'active': true },
  31195. * { 'user': 'pebbles', 'age': 1, 'active': false }
  31196. * ];
  31197. *
  31198. * _.partition(users, function(o) { return o.active; });
  31199. * // => objects for [['fred'], ['barney', 'pebbles']]
  31200. *
  31201. * // The `_.matches` iteratee shorthand.
  31202. * _.partition(users, { 'age': 1, 'active': false });
  31203. * // => objects for [['pebbles'], ['barney', 'fred']]
  31204. *
  31205. * // The `_.matchesProperty` iteratee shorthand.
  31206. * _.partition(users, ['active', false]);
  31207. * // => objects for [['barney', 'pebbles'], ['fred']]
  31208. *
  31209. * // The `_.property` iteratee shorthand.
  31210. * _.partition(users, 'active');
  31211. * // => objects for [['fred'], ['barney', 'pebbles']]
  31212. */
  31213. var partition = createAggregator(function(result, value, key) {
  31214. result[key ? 0 : 1].push(value);
  31215. }, function() { return [[], []]; });
  31216. /**
  31217. * Reduces `collection` to a value which is the accumulated result of running
  31218. * each element in `collection` thru `iteratee`, where each successive
  31219. * invocation is supplied the return value of the previous. If `accumulator`
  31220. * is not given, the first element of `collection` is used as the initial
  31221. * value. The iteratee is invoked with four arguments:
  31222. * (accumulator, value, index|key, collection).
  31223. *
  31224. * Many lodash methods are guarded to work as iteratees for methods like
  31225. * `_.reduce`, `_.reduceRight`, and `_.transform`.
  31226. *
  31227. * The guarded methods are:
  31228. * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
  31229. * and `sortBy`
  31230. *
  31231. * @static
  31232. * @memberOf _
  31233. * @since 0.1.0
  31234. * @category Collection
  31235. * @param {Array|Object} collection The collection to iterate over.
  31236. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  31237. * @param {*} [accumulator] The initial value.
  31238. * @returns {*} Returns the accumulated value.
  31239. * @see _.reduceRight
  31240. * @example
  31241. *
  31242. * _.reduce([1, 2], function(sum, n) {
  31243. * return sum + n;
  31244. * }, 0);
  31245. * // => 3
  31246. *
  31247. * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  31248. * (result[value] || (result[value] = [])).push(key);
  31249. * return result;
  31250. * }, {});
  31251. * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
  31252. */
  31253. function reduce(collection, iteratee, accumulator) {
  31254. var func = isArray(collection) ? arrayReduce : baseReduce,
  31255. initAccum = arguments.length < 3;
  31256. return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
  31257. }
  31258. /**
  31259. * This method is like `_.reduce` except that it iterates over elements of
  31260. * `collection` from right to left.
  31261. *
  31262. * @static
  31263. * @memberOf _
  31264. * @since 0.1.0
  31265. * @category Collection
  31266. * @param {Array|Object} collection The collection to iterate over.
  31267. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  31268. * @param {*} [accumulator] The initial value.
  31269. * @returns {*} Returns the accumulated value.
  31270. * @see _.reduce
  31271. * @example
  31272. *
  31273. * var array = [[0, 1], [2, 3], [4, 5]];
  31274. *
  31275. * _.reduceRight(array, function(flattened, other) {
  31276. * return flattened.concat(other);
  31277. * }, []);
  31278. * // => [4, 5, 2, 3, 0, 1]
  31279. */
  31280. function reduceRight(collection, iteratee, accumulator) {
  31281. var func = isArray(collection) ? arrayReduceRight : baseReduce,
  31282. initAccum = arguments.length < 3;
  31283. return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
  31284. }
  31285. /**
  31286. * The opposite of `_.filter`; this method returns the elements of `collection`
  31287. * that `predicate` does **not** return truthy for.
  31288. *
  31289. * @static
  31290. * @memberOf _
  31291. * @since 0.1.0
  31292. * @category Collection
  31293. * @param {Array|Object} collection The collection to iterate over.
  31294. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  31295. * @returns {Array} Returns the new filtered array.
  31296. * @see _.filter
  31297. * @example
  31298. *
  31299. * var users = [
  31300. * { 'user': 'barney', 'age': 36, 'active': false },
  31301. * { 'user': 'fred', 'age': 40, 'active': true }
  31302. * ];
  31303. *
  31304. * _.reject(users, function(o) { return !o.active; });
  31305. * // => objects for ['fred']
  31306. *
  31307. * // The `_.matches` iteratee shorthand.
  31308. * _.reject(users, { 'age': 40, 'active': true });
  31309. * // => objects for ['barney']
  31310. *
  31311. * // The `_.matchesProperty` iteratee shorthand.
  31312. * _.reject(users, ['active', false]);
  31313. * // => objects for ['fred']
  31314. *
  31315. * // The `_.property` iteratee shorthand.
  31316. * _.reject(users, 'active');
  31317. * // => objects for ['barney']
  31318. */
  31319. function reject(collection, predicate) {
  31320. var func = isArray(collection) ? arrayFilter : baseFilter;
  31321. return func(collection, negate(getIteratee(predicate, 3)));
  31322. }
  31323. /**
  31324. * Gets a random element from `collection`.
  31325. *
  31326. * @static
  31327. * @memberOf _
  31328. * @since 2.0.0
  31329. * @category Collection
  31330. * @param {Array|Object} collection The collection to sample.
  31331. * @returns {*} Returns the random element.
  31332. * @example
  31333. *
  31334. * _.sample([1, 2, 3, 4]);
  31335. * // => 2
  31336. */
  31337. function sample(collection) {
  31338. var func = isArray(collection) ? arraySample : baseSample;
  31339. return func(collection);
  31340. }
  31341. /**
  31342. * Gets `n` random elements at unique keys from `collection` up to the
  31343. * size of `collection`.
  31344. *
  31345. * @static
  31346. * @memberOf _
  31347. * @since 4.0.0
  31348. * @category Collection
  31349. * @param {Array|Object} collection The collection to sample.
  31350. * @param {number} [n=1] The number of elements to sample.
  31351. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  31352. * @returns {Array} Returns the random elements.
  31353. * @example
  31354. *
  31355. * _.sampleSize([1, 2, 3], 2);
  31356. * // => [3, 1]
  31357. *
  31358. * _.sampleSize([1, 2, 3], 4);
  31359. * // => [2, 3, 1]
  31360. */
  31361. function sampleSize(collection, n, guard) {
  31362. if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
  31363. n = 1;
  31364. } else {
  31365. n = toInteger(n);
  31366. }
  31367. var func = isArray(collection) ? arraySampleSize : baseSampleSize;
  31368. return func(collection, n);
  31369. }
  31370. /**
  31371. * Creates an array of shuffled values, using a version of the
  31372. * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
  31373. *
  31374. * @static
  31375. * @memberOf _
  31376. * @since 0.1.0
  31377. * @category Collection
  31378. * @param {Array|Object} collection The collection to shuffle.
  31379. * @returns {Array} Returns the new shuffled array.
  31380. * @example
  31381. *
  31382. * _.shuffle([1, 2, 3, 4]);
  31383. * // => [4, 1, 3, 2]
  31384. */
  31385. function shuffle(collection) {
  31386. var func = isArray(collection) ? arrayShuffle : baseShuffle;
  31387. return func(collection);
  31388. }
  31389. /**
  31390. * Gets the size of `collection` by returning its length for array-like
  31391. * values or the number of own enumerable string keyed properties for objects.
  31392. *
  31393. * @static
  31394. * @memberOf _
  31395. * @since 0.1.0
  31396. * @category Collection
  31397. * @param {Array|Object|string} collection The collection to inspect.
  31398. * @returns {number} Returns the collection size.
  31399. * @example
  31400. *
  31401. * _.size([1, 2, 3]);
  31402. * // => 3
  31403. *
  31404. * _.size({ 'a': 1, 'b': 2 });
  31405. * // => 2
  31406. *
  31407. * _.size('pebbles');
  31408. * // => 7
  31409. */
  31410. function size(collection) {
  31411. if (collection == null) {
  31412. return 0;
  31413. }
  31414. if (isArrayLike(collection)) {
  31415. return isString(collection) ? stringSize(collection) : collection.length;
  31416. }
  31417. var tag = getTag(collection);
  31418. if (tag == mapTag || tag == setTag) {
  31419. return collection.size;
  31420. }
  31421. return baseKeys(collection).length;
  31422. }
  31423. /**
  31424. * Checks if `predicate` returns truthy for **any** element of `collection`.
  31425. * Iteration is stopped once `predicate` returns truthy. The predicate is
  31426. * invoked with three arguments: (value, index|key, collection).
  31427. *
  31428. * @static
  31429. * @memberOf _
  31430. * @since 0.1.0
  31431. * @category Collection
  31432. * @param {Array|Object} collection The collection to iterate over.
  31433. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  31434. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  31435. * @returns {boolean} Returns `true` if any element passes the predicate check,
  31436. * else `false`.
  31437. * @example
  31438. *
  31439. * _.some([null, 0, 'yes', false], Boolean);
  31440. * // => true
  31441. *
  31442. * var users = [
  31443. * { 'user': 'barney', 'active': true },
  31444. * { 'user': 'fred', 'active': false }
  31445. * ];
  31446. *
  31447. * // The `_.matches` iteratee shorthand.
  31448. * _.some(users, { 'user': 'barney', 'active': false });
  31449. * // => false
  31450. *
  31451. * // The `_.matchesProperty` iteratee shorthand.
  31452. * _.some(users, ['active', false]);
  31453. * // => true
  31454. *
  31455. * // The `_.property` iteratee shorthand.
  31456. * _.some(users, 'active');
  31457. * // => true
  31458. */
  31459. function some(collection, predicate, guard) {
  31460. var func = isArray(collection) ? arraySome : baseSome;
  31461. if (guard && isIterateeCall(collection, predicate, guard)) {
  31462. predicate = undefined;
  31463. }
  31464. return func(collection, getIteratee(predicate, 3));
  31465. }
  31466. /**
  31467. * Creates an array of elements, sorted in ascending order by the results of
  31468. * running each element in a collection thru each iteratee. This method
  31469. * performs a stable sort, that is, it preserves the original sort order of
  31470. * equal elements. The iteratees are invoked with one argument: (value).
  31471. *
  31472. * @static
  31473. * @memberOf _
  31474. * @since 0.1.0
  31475. * @category Collection
  31476. * @param {Array|Object} collection The collection to iterate over.
  31477. * @param {...(Function|Function[])} [iteratees=[_.identity]]
  31478. * The iteratees to sort by.
  31479. * @returns {Array} Returns the new sorted array.
  31480. * @example
  31481. *
  31482. * var users = [
  31483. * { 'user': 'fred', 'age': 48 },
  31484. * { 'user': 'barney', 'age': 36 },
  31485. * { 'user': 'fred', 'age': 40 },
  31486. * { 'user': 'barney', 'age': 34 }
  31487. * ];
  31488. *
  31489. * _.sortBy(users, [function(o) { return o.user; }]);
  31490. * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
  31491. *
  31492. * _.sortBy(users, ['user', 'age']);
  31493. * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
  31494. */
  31495. var sortBy = baseRest(function(collection, iteratees) {
  31496. if (collection == null) {
  31497. return [];
  31498. }
  31499. var length = iteratees.length;
  31500. if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
  31501. iteratees = [];
  31502. } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
  31503. iteratees = [iteratees[0]];
  31504. }
  31505. return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
  31506. });
  31507. /*------------------------------------------------------------------------*/
  31508. /**
  31509. * Gets the timestamp of the number of milliseconds that have elapsed since
  31510. * the Unix epoch (1 January 1970 00:00:00 UTC).
  31511. *
  31512. * @static
  31513. * @memberOf _
  31514. * @since 2.4.0
  31515. * @category Date
  31516. * @returns {number} Returns the timestamp.
  31517. * @example
  31518. *
  31519. * _.defer(function(stamp) {
  31520. * console.log(_.now() - stamp);
  31521. * }, _.now());
  31522. * // => Logs the number of milliseconds it took for the deferred invocation.
  31523. */
  31524. var now = ctxNow || function() {
  31525. return root.Date.now();
  31526. };
  31527. /*------------------------------------------------------------------------*/
  31528. /**
  31529. * The opposite of `_.before`; this method creates a function that invokes
  31530. * `func` once it's called `n` or more times.
  31531. *
  31532. * @static
  31533. * @memberOf _
  31534. * @since 0.1.0
  31535. * @category Function
  31536. * @param {number} n The number of calls before `func` is invoked.
  31537. * @param {Function} func The function to restrict.
  31538. * @returns {Function} Returns the new restricted function.
  31539. * @example
  31540. *
  31541. * var saves = ['profile', 'settings'];
  31542. *
  31543. * var done = _.after(saves.length, function() {
  31544. * console.log('done saving!');
  31545. * });
  31546. *
  31547. * _.forEach(saves, function(type) {
  31548. * asyncSave({ 'type': type, 'complete': done });
  31549. * });
  31550. * // => Logs 'done saving!' after the two async saves have completed.
  31551. */
  31552. function after(n, func) {
  31553. if (typeof func != 'function') {
  31554. throw new TypeError(FUNC_ERROR_TEXT);
  31555. }
  31556. n = toInteger(n);
  31557. return function() {
  31558. if (--n < 1) {
  31559. return func.apply(this, arguments);
  31560. }
  31561. };
  31562. }
  31563. /**
  31564. * Creates a function that invokes `func`, with up to `n` arguments,
  31565. * ignoring any additional arguments.
  31566. *
  31567. * @static
  31568. * @memberOf _
  31569. * @since 3.0.0
  31570. * @category Function
  31571. * @param {Function} func The function to cap arguments for.
  31572. * @param {number} [n=func.length] The arity cap.
  31573. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  31574. * @returns {Function} Returns the new capped function.
  31575. * @example
  31576. *
  31577. * _.map(['6', '8', '10'], _.ary(parseInt, 1));
  31578. * // => [6, 8, 10]
  31579. */
  31580. function ary(func, n, guard) {
  31581. n = guard ? undefined : n;
  31582. n = (func && n == null) ? func.length : n;
  31583. return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
  31584. }
  31585. /**
  31586. * Creates a function that invokes `func`, with the `this` binding and arguments
  31587. * of the created function, while it's called less than `n` times. Subsequent
  31588. * calls to the created function return the result of the last `func` invocation.
  31589. *
  31590. * @static
  31591. * @memberOf _
  31592. * @since 3.0.0
  31593. * @category Function
  31594. * @param {number} n The number of calls at which `func` is no longer invoked.
  31595. * @param {Function} func The function to restrict.
  31596. * @returns {Function} Returns the new restricted function.
  31597. * @example
  31598. *
  31599. * jQuery(element).on('click', _.before(5, addContactToList));
  31600. * // => Allows adding up to 4 contacts to the list.
  31601. */
  31602. function before(n, func) {
  31603. var result;
  31604. if (typeof func != 'function') {
  31605. throw new TypeError(FUNC_ERROR_TEXT);
  31606. }
  31607. n = toInteger(n);
  31608. return function() {
  31609. if (--n > 0) {
  31610. result = func.apply(this, arguments);
  31611. }
  31612. if (n <= 1) {
  31613. func = undefined;
  31614. }
  31615. return result;
  31616. };
  31617. }
  31618. /**
  31619. * Creates a function that invokes `func` with the `this` binding of `thisArg`
  31620. * and `partials` prepended to the arguments it receives.
  31621. *
  31622. * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
  31623. * may be used as a placeholder for partially applied arguments.
  31624. *
  31625. * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
  31626. * property of bound functions.
  31627. *
  31628. * @static
  31629. * @memberOf _
  31630. * @since 0.1.0
  31631. * @category Function
  31632. * @param {Function} func The function to bind.
  31633. * @param {*} thisArg The `this` binding of `func`.
  31634. * @param {...*} [partials] The arguments to be partially applied.
  31635. * @returns {Function} Returns the new bound function.
  31636. * @example
  31637. *
  31638. * function greet(greeting, punctuation) {
  31639. * return greeting + ' ' + this.user + punctuation;
  31640. * }
  31641. *
  31642. * var object = { 'user': 'fred' };
  31643. *
  31644. * var bound = _.bind(greet, object, 'hi');
  31645. * bound('!');
  31646. * // => 'hi fred!'
  31647. *
  31648. * // Bound with placeholders.
  31649. * var bound = _.bind(greet, object, _, '!');
  31650. * bound('hi');
  31651. * // => 'hi fred!'
  31652. */
  31653. var bind = baseRest(function(func, thisArg, partials) {
  31654. var bitmask = WRAP_BIND_FLAG;
  31655. if (partials.length) {
  31656. var holders = replaceHolders(partials, getHolder(bind));
  31657. bitmask |= WRAP_PARTIAL_FLAG;
  31658. }
  31659. return createWrap(func, bitmask, thisArg, partials, holders);
  31660. });
  31661. /**
  31662. * Creates a function that invokes the method at `object[key]` with `partials`
  31663. * prepended to the arguments it receives.
  31664. *
  31665. * This method differs from `_.bind` by allowing bound functions to reference
  31666. * methods that may be redefined or don't yet exist. See
  31667. * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
  31668. * for more details.
  31669. *
  31670. * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
  31671. * builds, may be used as a placeholder for partially applied arguments.
  31672. *
  31673. * @static
  31674. * @memberOf _
  31675. * @since 0.10.0
  31676. * @category Function
  31677. * @param {Object} object The object to invoke the method on.
  31678. * @param {string} key The key of the method.
  31679. * @param {...*} [partials] The arguments to be partially applied.
  31680. * @returns {Function} Returns the new bound function.
  31681. * @example
  31682. *
  31683. * var object = {
  31684. * 'user': 'fred',
  31685. * 'greet': function(greeting, punctuation) {
  31686. * return greeting + ' ' + this.user + punctuation;
  31687. * }
  31688. * };
  31689. *
  31690. * var bound = _.bindKey(object, 'greet', 'hi');
  31691. * bound('!');
  31692. * // => 'hi fred!'
  31693. *
  31694. * object.greet = function(greeting, punctuation) {
  31695. * return greeting + 'ya ' + this.user + punctuation;
  31696. * };
  31697. *
  31698. * bound('!');
  31699. * // => 'hiya fred!'
  31700. *
  31701. * // Bound with placeholders.
  31702. * var bound = _.bindKey(object, 'greet', _, '!');
  31703. * bound('hi');
  31704. * // => 'hiya fred!'
  31705. */
  31706. var bindKey = baseRest(function(object, key, partials) {
  31707. var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
  31708. if (partials.length) {
  31709. var holders = replaceHolders(partials, getHolder(bindKey));
  31710. bitmask |= WRAP_PARTIAL_FLAG;
  31711. }
  31712. return createWrap(key, bitmask, object, partials, holders);
  31713. });
  31714. /**
  31715. * Creates a function that accepts arguments of `func` and either invokes
  31716. * `func` returning its result, if at least `arity` number of arguments have
  31717. * been provided, or returns a function that accepts the remaining `func`
  31718. * arguments, and so on. The arity of `func` may be specified if `func.length`
  31719. * is not sufficient.
  31720. *
  31721. * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
  31722. * may be used as a placeholder for provided arguments.
  31723. *
  31724. * **Note:** This method doesn't set the "length" property of curried functions.
  31725. *
  31726. * @static
  31727. * @memberOf _
  31728. * @since 2.0.0
  31729. * @category Function
  31730. * @param {Function} func The function to curry.
  31731. * @param {number} [arity=func.length] The arity of `func`.
  31732. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  31733. * @returns {Function} Returns the new curried function.
  31734. * @example
  31735. *
  31736. * var abc = function(a, b, c) {
  31737. * return [a, b, c];
  31738. * };
  31739. *
  31740. * var curried = _.curry(abc);
  31741. *
  31742. * curried(1)(2)(3);
  31743. * // => [1, 2, 3]
  31744. *
  31745. * curried(1, 2)(3);
  31746. * // => [1, 2, 3]
  31747. *
  31748. * curried(1, 2, 3);
  31749. * // => [1, 2, 3]
  31750. *
  31751. * // Curried with placeholders.
  31752. * curried(1)(_, 3)(2);
  31753. * // => [1, 2, 3]
  31754. */
  31755. function curry(func, arity, guard) {
  31756. arity = guard ? undefined : arity;
  31757. var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  31758. result.placeholder = curry.placeholder;
  31759. return result;
  31760. }
  31761. /**
  31762. * This method is like `_.curry` except that arguments are applied to `func`
  31763. * in the manner of `_.partialRight` instead of `_.partial`.
  31764. *
  31765. * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
  31766. * builds, may be used as a placeholder for provided arguments.
  31767. *
  31768. * **Note:** This method doesn't set the "length" property of curried functions.
  31769. *
  31770. * @static
  31771. * @memberOf _
  31772. * @since 3.0.0
  31773. * @category Function
  31774. * @param {Function} func The function to curry.
  31775. * @param {number} [arity=func.length] The arity of `func`.
  31776. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  31777. * @returns {Function} Returns the new curried function.
  31778. * @example
  31779. *
  31780. * var abc = function(a, b, c) {
  31781. * return [a, b, c];
  31782. * };
  31783. *
  31784. * var curried = _.curryRight(abc);
  31785. *
  31786. * curried(3)(2)(1);
  31787. * // => [1, 2, 3]
  31788. *
  31789. * curried(2, 3)(1);
  31790. * // => [1, 2, 3]
  31791. *
  31792. * curried(1, 2, 3);
  31793. * // => [1, 2, 3]
  31794. *
  31795. * // Curried with placeholders.
  31796. * curried(3)(1, _)(2);
  31797. * // => [1, 2, 3]
  31798. */
  31799. function curryRight(func, arity, guard) {
  31800. arity = guard ? undefined : arity;
  31801. var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  31802. result.placeholder = curryRight.placeholder;
  31803. return result;
  31804. }
  31805. /**
  31806. * Creates a debounced function that delays invoking `func` until after `wait`
  31807. * milliseconds have elapsed since the last time the debounced function was
  31808. * invoked. The debounced function comes with a `cancel` method to cancel
  31809. * delayed `func` invocations and a `flush` method to immediately invoke them.
  31810. * Provide `options` to indicate whether `func` should be invoked on the
  31811. * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
  31812. * with the last arguments provided to the debounced function. Subsequent
  31813. * calls to the debounced function return the result of the last `func`
  31814. * invocation.
  31815. *
  31816. * **Note:** If `leading` and `trailing` options are `true`, `func` is
  31817. * invoked on the trailing edge of the timeout only if the debounced function
  31818. * is invoked more than once during the `wait` timeout.
  31819. *
  31820. * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
  31821. * until to the next tick, similar to `setTimeout` with a timeout of `0`.
  31822. *
  31823. * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
  31824. * for details over the differences between `_.debounce` and `_.throttle`.
  31825. *
  31826. * @static
  31827. * @memberOf _
  31828. * @since 0.1.0
  31829. * @category Function
  31830. * @param {Function} func The function to debounce.
  31831. * @param {number} [wait=0] The number of milliseconds to delay.
  31832. * @param {Object} [options={}] The options object.
  31833. * @param {boolean} [options.leading=false]
  31834. * Specify invoking on the leading edge of the timeout.
  31835. * @param {number} [options.maxWait]
  31836. * The maximum time `func` is allowed to be delayed before it's invoked.
  31837. * @param {boolean} [options.trailing=true]
  31838. * Specify invoking on the trailing edge of the timeout.
  31839. * @returns {Function} Returns the new debounced function.
  31840. * @example
  31841. *
  31842. * // Avoid costly calculations while the window size is in flux.
  31843. * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
  31844. *
  31845. * // Invoke `sendMail` when clicked, debouncing subsequent calls.
  31846. * jQuery(element).on('click', _.debounce(sendMail, 300, {
  31847. * 'leading': true,
  31848. * 'trailing': false
  31849. * }));
  31850. *
  31851. * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
  31852. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
  31853. * var source = new EventSource('/stream');
  31854. * jQuery(source).on('message', debounced);
  31855. *
  31856. * // Cancel the trailing debounced invocation.
  31857. * jQuery(window).on('popstate', debounced.cancel);
  31858. */
  31859. function debounce(func, wait, options) {
  31860. var lastArgs,
  31861. lastThis,
  31862. maxWait,
  31863. result,
  31864. timerId,
  31865. lastCallTime,
  31866. lastInvokeTime = 0,
  31867. leading = false,
  31868. maxing = false,
  31869. trailing = true;
  31870. if (typeof func != 'function') {
  31871. throw new TypeError(FUNC_ERROR_TEXT);
  31872. }
  31873. wait = toNumber(wait) || 0;
  31874. if (isObject(options)) {
  31875. leading = !!options.leading;
  31876. maxing = 'maxWait' in options;
  31877. maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
  31878. trailing = 'trailing' in options ? !!options.trailing : trailing;
  31879. }
  31880. function invokeFunc(time) {
  31881. var args = lastArgs,
  31882. thisArg = lastThis;
  31883. lastArgs = lastThis = undefined;
  31884. lastInvokeTime = time;
  31885. result = func.apply(thisArg, args);
  31886. return result;
  31887. }
  31888. function leadingEdge(time) {
  31889. // Reset any `maxWait` timer.
  31890. lastInvokeTime = time;
  31891. // Start the timer for the trailing edge.
  31892. timerId = setTimeout(timerExpired, wait);
  31893. // Invoke the leading edge.
  31894. return leading ? invokeFunc(time) : result;
  31895. }
  31896. function remainingWait(time) {
  31897. var timeSinceLastCall = time - lastCallTime,
  31898. timeSinceLastInvoke = time - lastInvokeTime,
  31899. result = wait - timeSinceLastCall;
  31900. return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
  31901. }
  31902. function shouldInvoke(time) {
  31903. var timeSinceLastCall = time - lastCallTime,
  31904. timeSinceLastInvoke = time - lastInvokeTime;
  31905. // Either this is the first call, activity has stopped and we're at the
  31906. // trailing edge, the system time has gone backwards and we're treating
  31907. // it as the trailing edge, or we've hit the `maxWait` limit.
  31908. return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
  31909. (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  31910. }
  31911. function timerExpired() {
  31912. var time = now();
  31913. if (shouldInvoke(time)) {
  31914. return trailingEdge(time);
  31915. }
  31916. // Restart the timer.
  31917. timerId = setTimeout(timerExpired, remainingWait(time));
  31918. }
  31919. function trailingEdge(time) {
  31920. timerId = undefined;
  31921. // Only invoke if we have `lastArgs` which means `func` has been
  31922. // debounced at least once.
  31923. if (trailing && lastArgs) {
  31924. return invokeFunc(time);
  31925. }
  31926. lastArgs = lastThis = undefined;
  31927. return result;
  31928. }
  31929. function cancel() {
  31930. if (timerId !== undefined) {
  31931. clearTimeout(timerId);
  31932. }
  31933. lastInvokeTime = 0;
  31934. lastArgs = lastCallTime = lastThis = timerId = undefined;
  31935. }
  31936. function flush() {
  31937. return timerId === undefined ? result : trailingEdge(now());
  31938. }
  31939. function debounced() {
  31940. var time = now(),
  31941. isInvoking = shouldInvoke(time);
  31942. lastArgs = arguments;
  31943. lastThis = this;
  31944. lastCallTime = time;
  31945. if (isInvoking) {
  31946. if (timerId === undefined) {
  31947. return leadingEdge(lastCallTime);
  31948. }
  31949. if (maxing) {
  31950. // Handle invocations in a tight loop.
  31951. timerId = setTimeout(timerExpired, wait);
  31952. return invokeFunc(lastCallTime);
  31953. }
  31954. }
  31955. if (timerId === undefined) {
  31956. timerId = setTimeout(timerExpired, wait);
  31957. }
  31958. return result;
  31959. }
  31960. debounced.cancel = cancel;
  31961. debounced.flush = flush;
  31962. return debounced;
  31963. }
  31964. /**
  31965. * Defers invoking the `func` until the current call stack has cleared. Any
  31966. * additional arguments are provided to `func` when it's invoked.
  31967. *
  31968. * @static
  31969. * @memberOf _
  31970. * @since 0.1.0
  31971. * @category Function
  31972. * @param {Function} func The function to defer.
  31973. * @param {...*} [args] The arguments to invoke `func` with.
  31974. * @returns {number} Returns the timer id.
  31975. * @example
  31976. *
  31977. * _.defer(function(text) {
  31978. * console.log(text);
  31979. * }, 'deferred');
  31980. * // => Logs 'deferred' after one millisecond.
  31981. */
  31982. var defer = baseRest(function(func, args) {
  31983. return baseDelay(func, 1, args);
  31984. });
  31985. /**
  31986. * Invokes `func` after `wait` milliseconds. Any additional arguments are
  31987. * provided to `func` when it's invoked.
  31988. *
  31989. * @static
  31990. * @memberOf _
  31991. * @since 0.1.0
  31992. * @category Function
  31993. * @param {Function} func The function to delay.
  31994. * @param {number} wait The number of milliseconds to delay invocation.
  31995. * @param {...*} [args] The arguments to invoke `func` with.
  31996. * @returns {number} Returns the timer id.
  31997. * @example
  31998. *
  31999. * _.delay(function(text) {
  32000. * console.log(text);
  32001. * }, 1000, 'later');
  32002. * // => Logs 'later' after one second.
  32003. */
  32004. var delay = baseRest(function(func, wait, args) {
  32005. return baseDelay(func, toNumber(wait) || 0, args);
  32006. });
  32007. /**
  32008. * Creates a function that invokes `func` with arguments reversed.
  32009. *
  32010. * @static
  32011. * @memberOf _
  32012. * @since 4.0.0
  32013. * @category Function
  32014. * @param {Function} func The function to flip arguments for.
  32015. * @returns {Function} Returns the new flipped function.
  32016. * @example
  32017. *
  32018. * var flipped = _.flip(function() {
  32019. * return _.toArray(arguments);
  32020. * });
  32021. *
  32022. * flipped('a', 'b', 'c', 'd');
  32023. * // => ['d', 'c', 'b', 'a']
  32024. */
  32025. function flip(func) {
  32026. return createWrap(func, WRAP_FLIP_FLAG);
  32027. }
  32028. /**
  32029. * Creates a function that memoizes the result of `func`. If `resolver` is
  32030. * provided, it determines the cache key for storing the result based on the
  32031. * arguments provided to the memoized function. By default, the first argument
  32032. * provided to the memoized function is used as the map cache key. The `func`
  32033. * is invoked with the `this` binding of the memoized function.
  32034. *
  32035. * **Note:** The cache is exposed as the `cache` property on the memoized
  32036. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  32037. * constructor with one whose instances implement the
  32038. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  32039. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  32040. *
  32041. * @static
  32042. * @memberOf _
  32043. * @since 0.1.0
  32044. * @category Function
  32045. * @param {Function} func The function to have its output memoized.
  32046. * @param {Function} [resolver] The function to resolve the cache key.
  32047. * @returns {Function} Returns the new memoized function.
  32048. * @example
  32049. *
  32050. * var object = { 'a': 1, 'b': 2 };
  32051. * var other = { 'c': 3, 'd': 4 };
  32052. *
  32053. * var values = _.memoize(_.values);
  32054. * values(object);
  32055. * // => [1, 2]
  32056. *
  32057. * values(other);
  32058. * // => [3, 4]
  32059. *
  32060. * object.a = 2;
  32061. * values(object);
  32062. * // => [1, 2]
  32063. *
  32064. * // Modify the result cache.
  32065. * values.cache.set(object, ['a', 'b']);
  32066. * values(object);
  32067. * // => ['a', 'b']
  32068. *
  32069. * // Replace `_.memoize.Cache`.
  32070. * _.memoize.Cache = WeakMap;
  32071. */
  32072. function memoize(func, resolver) {
  32073. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  32074. throw new TypeError(FUNC_ERROR_TEXT);
  32075. }
  32076. var memoized = function() {
  32077. var args = arguments,
  32078. key = resolver ? resolver.apply(this, args) : args[0],
  32079. cache = memoized.cache;
  32080. if (cache.has(key)) {
  32081. return cache.get(key);
  32082. }
  32083. var result = func.apply(this, args);
  32084. memoized.cache = cache.set(key, result) || cache;
  32085. return result;
  32086. };
  32087. memoized.cache = new (memoize.Cache || MapCache);
  32088. return memoized;
  32089. }
  32090. // Expose `MapCache`.
  32091. memoize.Cache = MapCache;
  32092. /**
  32093. * Creates a function that negates the result of the predicate `func`. The
  32094. * `func` predicate is invoked with the `this` binding and arguments of the
  32095. * created function.
  32096. *
  32097. * @static
  32098. * @memberOf _
  32099. * @since 3.0.0
  32100. * @category Function
  32101. * @param {Function} predicate The predicate to negate.
  32102. * @returns {Function} Returns the new negated function.
  32103. * @example
  32104. *
  32105. * function isEven(n) {
  32106. * return n % 2 == 0;
  32107. * }
  32108. *
  32109. * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
  32110. * // => [1, 3, 5]
  32111. */
  32112. function negate(predicate) {
  32113. if (typeof predicate != 'function') {
  32114. throw new TypeError(FUNC_ERROR_TEXT);
  32115. }
  32116. return function() {
  32117. var args = arguments;
  32118. switch (args.length) {
  32119. case 0: return !predicate.call(this);
  32120. case 1: return !predicate.call(this, args[0]);
  32121. case 2: return !predicate.call(this, args[0], args[1]);
  32122. case 3: return !predicate.call(this, args[0], args[1], args[2]);
  32123. }
  32124. return !predicate.apply(this, args);
  32125. };
  32126. }
  32127. /**
  32128. * Creates a function that is restricted to invoking `func` once. Repeat calls
  32129. * to the function return the value of the first invocation. The `func` is
  32130. * invoked with the `this` binding and arguments of the created function.
  32131. *
  32132. * @static
  32133. * @memberOf _
  32134. * @since 0.1.0
  32135. * @category Function
  32136. * @param {Function} func The function to restrict.
  32137. * @returns {Function} Returns the new restricted function.
  32138. * @example
  32139. *
  32140. * var initialize = _.once(createApplication);
  32141. * initialize();
  32142. * initialize();
  32143. * // => `createApplication` is invoked once
  32144. */
  32145. function once(func) {
  32146. return before(2, func);
  32147. }
  32148. /**
  32149. * Creates a function that invokes `func` with its arguments transformed.
  32150. *
  32151. * @static
  32152. * @since 4.0.0
  32153. * @memberOf _
  32154. * @category Function
  32155. * @param {Function} func The function to wrap.
  32156. * @param {...(Function|Function[])} [transforms=[_.identity]]
  32157. * The argument transforms.
  32158. * @returns {Function} Returns the new function.
  32159. * @example
  32160. *
  32161. * function doubled(n) {
  32162. * return n * 2;
  32163. * }
  32164. *
  32165. * function square(n) {
  32166. * return n * n;
  32167. * }
  32168. *
  32169. * var func = _.overArgs(function(x, y) {
  32170. * return [x, y];
  32171. * }, [square, doubled]);
  32172. *
  32173. * func(9, 3);
  32174. * // => [81, 6]
  32175. *
  32176. * func(10, 5);
  32177. * // => [100, 10]
  32178. */
  32179. var overArgs = castRest(function(func, transforms) {
  32180. transforms = (transforms.length == 1 && isArray(transforms[0]))
  32181. ? arrayMap(transforms[0], baseUnary(getIteratee()))
  32182. : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
  32183. var funcsLength = transforms.length;
  32184. return baseRest(function(args) {
  32185. var index = -1,
  32186. length = nativeMin(args.length, funcsLength);
  32187. while (++index < length) {
  32188. args[index] = transforms[index].call(this, args[index]);
  32189. }
  32190. return apply(func, this, args);
  32191. });
  32192. });
  32193. /**
  32194. * Creates a function that invokes `func` with `partials` prepended to the
  32195. * arguments it receives. This method is like `_.bind` except it does **not**
  32196. * alter the `this` binding.
  32197. *
  32198. * The `_.partial.placeholder` value, which defaults to `_` in monolithic
  32199. * builds, may be used as a placeholder for partially applied arguments.
  32200. *
  32201. * **Note:** This method doesn't set the "length" property of partially
  32202. * applied functions.
  32203. *
  32204. * @static
  32205. * @memberOf _
  32206. * @since 0.2.0
  32207. * @category Function
  32208. * @param {Function} func The function to partially apply arguments to.
  32209. * @param {...*} [partials] The arguments to be partially applied.
  32210. * @returns {Function} Returns the new partially applied function.
  32211. * @example
  32212. *
  32213. * function greet(greeting, name) {
  32214. * return greeting + ' ' + name;
  32215. * }
  32216. *
  32217. * var sayHelloTo = _.partial(greet, 'hello');
  32218. * sayHelloTo('fred');
  32219. * // => 'hello fred'
  32220. *
  32221. * // Partially applied with placeholders.
  32222. * var greetFred = _.partial(greet, _, 'fred');
  32223. * greetFred('hi');
  32224. * // => 'hi fred'
  32225. */
  32226. var partial = baseRest(function(func, partials) {
  32227. var holders = replaceHolders(partials, getHolder(partial));
  32228. return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
  32229. });
  32230. /**
  32231. * This method is like `_.partial` except that partially applied arguments
  32232. * are appended to the arguments it receives.
  32233. *
  32234. * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
  32235. * builds, may be used as a placeholder for partially applied arguments.
  32236. *
  32237. * **Note:** This method doesn't set the "length" property of partially
  32238. * applied functions.
  32239. *
  32240. * @static
  32241. * @memberOf _
  32242. * @since 1.0.0
  32243. * @category Function
  32244. * @param {Function} func The function to partially apply arguments to.
  32245. * @param {...*} [partials] The arguments to be partially applied.
  32246. * @returns {Function} Returns the new partially applied function.
  32247. * @example
  32248. *
  32249. * function greet(greeting, name) {
  32250. * return greeting + ' ' + name;
  32251. * }
  32252. *
  32253. * var greetFred = _.partialRight(greet, 'fred');
  32254. * greetFred('hi');
  32255. * // => 'hi fred'
  32256. *
  32257. * // Partially applied with placeholders.
  32258. * var sayHelloTo = _.partialRight(greet, 'hello', _);
  32259. * sayHelloTo('fred');
  32260. * // => 'hello fred'
  32261. */
  32262. var partialRight = baseRest(function(func, partials) {
  32263. var holders = replaceHolders(partials, getHolder(partialRight));
  32264. return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
  32265. });
  32266. /**
  32267. * Creates a function that invokes `func` with arguments arranged according
  32268. * to the specified `indexes` where the argument value at the first index is
  32269. * provided as the first argument, the argument value at the second index is
  32270. * provided as the second argument, and so on.
  32271. *
  32272. * @static
  32273. * @memberOf _
  32274. * @since 3.0.0
  32275. * @category Function
  32276. * @param {Function} func The function to rearrange arguments for.
  32277. * @param {...(number|number[])} indexes The arranged argument indexes.
  32278. * @returns {Function} Returns the new function.
  32279. * @example
  32280. *
  32281. * var rearged = _.rearg(function(a, b, c) {
  32282. * return [a, b, c];
  32283. * }, [2, 0, 1]);
  32284. *
  32285. * rearged('b', 'c', 'a')
  32286. * // => ['a', 'b', 'c']
  32287. */
  32288. var rearg = flatRest(function(func, indexes) {
  32289. return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
  32290. });
  32291. /**
  32292. * Creates a function that invokes `func` with the `this` binding of the
  32293. * created function and arguments from `start` and beyond provided as
  32294. * an array.
  32295. *
  32296. * **Note:** This method is based on the
  32297. * [rest parameter](https://mdn.io/rest_parameters).
  32298. *
  32299. * @static
  32300. * @memberOf _
  32301. * @since 4.0.0
  32302. * @category Function
  32303. * @param {Function} func The function to apply a rest parameter to.
  32304. * @param {number} [start=func.length-1] The start position of the rest parameter.
  32305. * @returns {Function} Returns the new function.
  32306. * @example
  32307. *
  32308. * var say = _.rest(function(what, names) {
  32309. * return what + ' ' + _.initial(names).join(', ') +
  32310. * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
  32311. * });
  32312. *
  32313. * say('hello', 'fred', 'barney', 'pebbles');
  32314. * // => 'hello fred, barney, & pebbles'
  32315. */
  32316. function rest(func, start) {
  32317. if (typeof func != 'function') {
  32318. throw new TypeError(FUNC_ERROR_TEXT);
  32319. }
  32320. start = start === undefined ? start : toInteger(start);
  32321. return baseRest(func, start);
  32322. }
  32323. /**
  32324. * Creates a function that invokes `func` with the `this` binding of the
  32325. * create function and an array of arguments much like
  32326. * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
  32327. *
  32328. * **Note:** This method is based on the
  32329. * [spread operator](https://mdn.io/spread_operator).
  32330. *
  32331. * @static
  32332. * @memberOf _
  32333. * @since 3.2.0
  32334. * @category Function
  32335. * @param {Function} func The function to spread arguments over.
  32336. * @param {number} [start=0] The start position of the spread.
  32337. * @returns {Function} Returns the new function.
  32338. * @example
  32339. *
  32340. * var say = _.spread(function(who, what) {
  32341. * return who + ' says ' + what;
  32342. * });
  32343. *
  32344. * say(['fred', 'hello']);
  32345. * // => 'fred says hello'
  32346. *
  32347. * var numbers = Promise.all([
  32348. * Promise.resolve(40),
  32349. * Promise.resolve(36)
  32350. * ]);
  32351. *
  32352. * numbers.then(_.spread(function(x, y) {
  32353. * return x + y;
  32354. * }));
  32355. * // => a Promise of 76
  32356. */
  32357. function spread(func, start) {
  32358. if (typeof func != 'function') {
  32359. throw new TypeError(FUNC_ERROR_TEXT);
  32360. }
  32361. start = start == null ? 0 : nativeMax(toInteger(start), 0);
  32362. return baseRest(function(args) {
  32363. var array = args[start],
  32364. otherArgs = castSlice(args, 0, start);
  32365. if (array) {
  32366. arrayPush(otherArgs, array);
  32367. }
  32368. return apply(func, this, otherArgs);
  32369. });
  32370. }
  32371. /**
  32372. * Creates a throttled function that only invokes `func` at most once per
  32373. * every `wait` milliseconds. The throttled function comes with a `cancel`
  32374. * method to cancel delayed `func` invocations and a `flush` method to
  32375. * immediately invoke them. Provide `options` to indicate whether `func`
  32376. * should be invoked on the leading and/or trailing edge of the `wait`
  32377. * timeout. The `func` is invoked with the last arguments provided to the
  32378. * throttled function. Subsequent calls to the throttled function return the
  32379. * result of the last `func` invocation.
  32380. *
  32381. * **Note:** If `leading` and `trailing` options are `true`, `func` is
  32382. * invoked on the trailing edge of the timeout only if the throttled function
  32383. * is invoked more than once during the `wait` timeout.
  32384. *
  32385. * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
  32386. * until to the next tick, similar to `setTimeout` with a timeout of `0`.
  32387. *
  32388. * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
  32389. * for details over the differences between `_.throttle` and `_.debounce`.
  32390. *
  32391. * @static
  32392. * @memberOf _
  32393. * @since 0.1.0
  32394. * @category Function
  32395. * @param {Function} func The function to throttle.
  32396. * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
  32397. * @param {Object} [options={}] The options object.
  32398. * @param {boolean} [options.leading=true]
  32399. * Specify invoking on the leading edge of the timeout.
  32400. * @param {boolean} [options.trailing=true]
  32401. * Specify invoking on the trailing edge of the timeout.
  32402. * @returns {Function} Returns the new throttled function.
  32403. * @example
  32404. *
  32405. * // Avoid excessively updating the position while scrolling.
  32406. * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
  32407. *
  32408. * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
  32409. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
  32410. * jQuery(element).on('click', throttled);
  32411. *
  32412. * // Cancel the trailing throttled invocation.
  32413. * jQuery(window).on('popstate', throttled.cancel);
  32414. */
  32415. function throttle(func, wait, options) {
  32416. var leading = true,
  32417. trailing = true;
  32418. if (typeof func != 'function') {
  32419. throw new TypeError(FUNC_ERROR_TEXT);
  32420. }
  32421. if (isObject(options)) {
  32422. leading = 'leading' in options ? !!options.leading : leading;
  32423. trailing = 'trailing' in options ? !!options.trailing : trailing;
  32424. }
  32425. return debounce(func, wait, {
  32426. 'leading': leading,
  32427. 'maxWait': wait,
  32428. 'trailing': trailing
  32429. });
  32430. }
  32431. /**
  32432. * Creates a function that accepts up to one argument, ignoring any
  32433. * additional arguments.
  32434. *
  32435. * @static
  32436. * @memberOf _
  32437. * @since 4.0.0
  32438. * @category Function
  32439. * @param {Function} func The function to cap arguments for.
  32440. * @returns {Function} Returns the new capped function.
  32441. * @example
  32442. *
  32443. * _.map(['6', '8', '10'], _.unary(parseInt));
  32444. * // => [6, 8, 10]
  32445. */
  32446. function unary(func) {
  32447. return ary(func, 1);
  32448. }
  32449. /**
  32450. * Creates a function that provides `value` to `wrapper` as its first
  32451. * argument. Any additional arguments provided to the function are appended
  32452. * to those provided to the `wrapper`. The wrapper is invoked with the `this`
  32453. * binding of the created function.
  32454. *
  32455. * @static
  32456. * @memberOf _
  32457. * @since 0.1.0
  32458. * @category Function
  32459. * @param {*} value The value to wrap.
  32460. * @param {Function} [wrapper=identity] The wrapper function.
  32461. * @returns {Function} Returns the new function.
  32462. * @example
  32463. *
  32464. * var p = _.wrap(_.escape, function(func, text) {
  32465. * return '<p>' + func(text) + '</p>';
  32466. * });
  32467. *
  32468. * p('fred, barney, & pebbles');
  32469. * // => '<p>fred, barney, &amp; pebbles</p>'
  32470. */
  32471. function wrap(value, wrapper) {
  32472. return partial(castFunction(wrapper), value);
  32473. }
  32474. /*------------------------------------------------------------------------*/
  32475. /**
  32476. * Casts `value` as an array if it's not one.
  32477. *
  32478. * @static
  32479. * @memberOf _
  32480. * @since 4.4.0
  32481. * @category Lang
  32482. * @param {*} value The value to inspect.
  32483. * @returns {Array} Returns the cast array.
  32484. * @example
  32485. *
  32486. * _.castArray(1);
  32487. * // => [1]
  32488. *
  32489. * _.castArray({ 'a': 1 });
  32490. * // => [{ 'a': 1 }]
  32491. *
  32492. * _.castArray('abc');
  32493. * // => ['abc']
  32494. *
  32495. * _.castArray(null);
  32496. * // => [null]
  32497. *
  32498. * _.castArray(undefined);
  32499. * // => [undefined]
  32500. *
  32501. * _.castArray();
  32502. * // => []
  32503. *
  32504. * var array = [1, 2, 3];
  32505. * console.log(_.castArray(array) === array);
  32506. * // => true
  32507. */
  32508. function castArray() {
  32509. if (!arguments.length) {
  32510. return [];
  32511. }
  32512. var value = arguments[0];
  32513. return isArray(value) ? value : [value];
  32514. }
  32515. /**
  32516. * Creates a shallow clone of `value`.
  32517. *
  32518. * **Note:** This method is loosely based on the
  32519. * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
  32520. * and supports cloning arrays, array buffers, booleans, date objects, maps,
  32521. * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
  32522. * arrays. The own enumerable properties of `arguments` objects are cloned
  32523. * as plain objects. An empty object is returned for uncloneable values such
  32524. * as error objects, functions, DOM nodes, and WeakMaps.
  32525. *
  32526. * @static
  32527. * @memberOf _
  32528. * @since 0.1.0
  32529. * @category Lang
  32530. * @param {*} value The value to clone.
  32531. * @returns {*} Returns the cloned value.
  32532. * @see _.cloneDeep
  32533. * @example
  32534. *
  32535. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  32536. *
  32537. * var shallow = _.clone(objects);
  32538. * console.log(shallow[0] === objects[0]);
  32539. * // => true
  32540. */
  32541. function clone(value) {
  32542. return baseClone(value, CLONE_SYMBOLS_FLAG);
  32543. }
  32544. /**
  32545. * This method is like `_.clone` except that it accepts `customizer` which
  32546. * is invoked to produce the cloned value. If `customizer` returns `undefined`,
  32547. * cloning is handled by the method instead. The `customizer` is invoked with
  32548. * up to four arguments; (value [, index|key, object, stack]).
  32549. *
  32550. * @static
  32551. * @memberOf _
  32552. * @since 4.0.0
  32553. * @category Lang
  32554. * @param {*} value The value to clone.
  32555. * @param {Function} [customizer] The function to customize cloning.
  32556. * @returns {*} Returns the cloned value.
  32557. * @see _.cloneDeepWith
  32558. * @example
  32559. *
  32560. * function customizer(value) {
  32561. * if (_.isElement(value)) {
  32562. * return value.cloneNode(false);
  32563. * }
  32564. * }
  32565. *
  32566. * var el = _.cloneWith(document.body, customizer);
  32567. *
  32568. * console.log(el === document.body);
  32569. * // => false
  32570. * console.log(el.nodeName);
  32571. * // => 'BODY'
  32572. * console.log(el.childNodes.length);
  32573. * // => 0
  32574. */
  32575. function cloneWith(value, customizer) {
  32576. customizer = typeof customizer == 'function' ? customizer : undefined;
  32577. return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
  32578. }
  32579. /**
  32580. * This method is like `_.clone` except that it recursively clones `value`.
  32581. *
  32582. * @static
  32583. * @memberOf _
  32584. * @since 1.0.0
  32585. * @category Lang
  32586. * @param {*} value The value to recursively clone.
  32587. * @returns {*} Returns the deep cloned value.
  32588. * @see _.clone
  32589. * @example
  32590. *
  32591. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  32592. *
  32593. * var deep = _.cloneDeep(objects);
  32594. * console.log(deep[0] === objects[0]);
  32595. * // => false
  32596. */
  32597. function cloneDeep(value) {
  32598. return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
  32599. }
  32600. /**
  32601. * This method is like `_.cloneWith` except that it recursively clones `value`.
  32602. *
  32603. * @static
  32604. * @memberOf _
  32605. * @since 4.0.0
  32606. * @category Lang
  32607. * @param {*} value The value to recursively clone.
  32608. * @param {Function} [customizer] The function to customize cloning.
  32609. * @returns {*} Returns the deep cloned value.
  32610. * @see _.cloneWith
  32611. * @example
  32612. *
  32613. * function customizer(value) {
  32614. * if (_.isElement(value)) {
  32615. * return value.cloneNode(true);
  32616. * }
  32617. * }
  32618. *
  32619. * var el = _.cloneDeepWith(document.body, customizer);
  32620. *
  32621. * console.log(el === document.body);
  32622. * // => false
  32623. * console.log(el.nodeName);
  32624. * // => 'BODY'
  32625. * console.log(el.childNodes.length);
  32626. * // => 20
  32627. */
  32628. function cloneDeepWith(value, customizer) {
  32629. customizer = typeof customizer == 'function' ? customizer : undefined;
  32630. return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
  32631. }
  32632. /**
  32633. * Checks if `object` conforms to `source` by invoking the predicate
  32634. * properties of `source` with the corresponding property values of `object`.
  32635. *
  32636. * **Note:** This method is equivalent to `_.conforms` when `source` is
  32637. * partially applied.
  32638. *
  32639. * @static
  32640. * @memberOf _
  32641. * @since 4.14.0
  32642. * @category Lang
  32643. * @param {Object} object The object to inspect.
  32644. * @param {Object} source The object of property predicates to conform to.
  32645. * @returns {boolean} Returns `true` if `object` conforms, else `false`.
  32646. * @example
  32647. *
  32648. * var object = { 'a': 1, 'b': 2 };
  32649. *
  32650. * _.conformsTo(object, { 'b': function(n) { return n > 1; } });
  32651. * // => true
  32652. *
  32653. * _.conformsTo(object, { 'b': function(n) { return n > 2; } });
  32654. * // => false
  32655. */
  32656. function conformsTo(object, source) {
  32657. return source == null || baseConformsTo(object, source, keys(source));
  32658. }
  32659. /**
  32660. * Performs a
  32661. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  32662. * comparison between two values to determine if they are equivalent.
  32663. *
  32664. * @static
  32665. * @memberOf _
  32666. * @since 4.0.0
  32667. * @category Lang
  32668. * @param {*} value The value to compare.
  32669. * @param {*} other The other value to compare.
  32670. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  32671. * @example
  32672. *
  32673. * var object = { 'a': 1 };
  32674. * var other = { 'a': 1 };
  32675. *
  32676. * _.eq(object, object);
  32677. * // => true
  32678. *
  32679. * _.eq(object, other);
  32680. * // => false
  32681. *
  32682. * _.eq('a', 'a');
  32683. * // => true
  32684. *
  32685. * _.eq('a', Object('a'));
  32686. * // => false
  32687. *
  32688. * _.eq(NaN, NaN);
  32689. * // => true
  32690. */
  32691. function eq(value, other) {
  32692. return value === other || (value !== value && other !== other);
  32693. }
  32694. /**
  32695. * Checks if `value` is greater than `other`.
  32696. *
  32697. * @static
  32698. * @memberOf _
  32699. * @since 3.9.0
  32700. * @category Lang
  32701. * @param {*} value The value to compare.
  32702. * @param {*} other The other value to compare.
  32703. * @returns {boolean} Returns `true` if `value` is greater than `other`,
  32704. * else `false`.
  32705. * @see _.lt
  32706. * @example
  32707. *
  32708. * _.gt(3, 1);
  32709. * // => true
  32710. *
  32711. * _.gt(3, 3);
  32712. * // => false
  32713. *
  32714. * _.gt(1, 3);
  32715. * // => false
  32716. */
  32717. var gt = createRelationalOperation(baseGt);
  32718. /**
  32719. * Checks if `value` is greater than or equal to `other`.
  32720. *
  32721. * @static
  32722. * @memberOf _
  32723. * @since 3.9.0
  32724. * @category Lang
  32725. * @param {*} value The value to compare.
  32726. * @param {*} other The other value to compare.
  32727. * @returns {boolean} Returns `true` if `value` is greater than or equal to
  32728. * `other`, else `false`.
  32729. * @see _.lte
  32730. * @example
  32731. *
  32732. * _.gte(3, 1);
  32733. * // => true
  32734. *
  32735. * _.gte(3, 3);
  32736. * // => true
  32737. *
  32738. * _.gte(1, 3);
  32739. * // => false
  32740. */
  32741. var gte = createRelationalOperation(function(value, other) {
  32742. return value >= other;
  32743. });
  32744. /**
  32745. * Checks if `value` is likely an `arguments` object.
  32746. *
  32747. * @static
  32748. * @memberOf _
  32749. * @since 0.1.0
  32750. * @category Lang
  32751. * @param {*} value The value to check.
  32752. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  32753. * else `false`.
  32754. * @example
  32755. *
  32756. * _.isArguments(function() { return arguments; }());
  32757. * // => true
  32758. *
  32759. * _.isArguments([1, 2, 3]);
  32760. * // => false
  32761. */
  32762. var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  32763. return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
  32764. !propertyIsEnumerable.call(value, 'callee');
  32765. };
  32766. /**
  32767. * Checks if `value` is classified as an `Array` object.
  32768. *
  32769. * @static
  32770. * @memberOf _
  32771. * @since 0.1.0
  32772. * @category Lang
  32773. * @param {*} value The value to check.
  32774. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  32775. * @example
  32776. *
  32777. * _.isArray([1, 2, 3]);
  32778. * // => true
  32779. *
  32780. * _.isArray(document.body.children);
  32781. * // => false
  32782. *
  32783. * _.isArray('abc');
  32784. * // => false
  32785. *
  32786. * _.isArray(_.noop);
  32787. * // => false
  32788. */
  32789. var isArray = Array.isArray;
  32790. /**
  32791. * Checks if `value` is classified as an `ArrayBuffer` object.
  32792. *
  32793. * @static
  32794. * @memberOf _
  32795. * @since 4.3.0
  32796. * @category Lang
  32797. * @param {*} value The value to check.
  32798. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
  32799. * @example
  32800. *
  32801. * _.isArrayBuffer(new ArrayBuffer(2));
  32802. * // => true
  32803. *
  32804. * _.isArrayBuffer(new Array(2));
  32805. * // => false
  32806. */
  32807. var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
  32808. /**
  32809. * Checks if `value` is array-like. A value is considered array-like if it's
  32810. * not a function and has a `value.length` that's an integer greater than or
  32811. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  32812. *
  32813. * @static
  32814. * @memberOf _
  32815. * @since 4.0.0
  32816. * @category Lang
  32817. * @param {*} value The value to check.
  32818. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  32819. * @example
  32820. *
  32821. * _.isArrayLike([1, 2, 3]);
  32822. * // => true
  32823. *
  32824. * _.isArrayLike(document.body.children);
  32825. * // => true
  32826. *
  32827. * _.isArrayLike('abc');
  32828. * // => true
  32829. *
  32830. * _.isArrayLike(_.noop);
  32831. * // => false
  32832. */
  32833. function isArrayLike(value) {
  32834. return value != null && isLength(value.length) && !isFunction(value);
  32835. }
  32836. /**
  32837. * This method is like `_.isArrayLike` except that it also checks if `value`
  32838. * is an object.
  32839. *
  32840. * @static
  32841. * @memberOf _
  32842. * @since 4.0.0
  32843. * @category Lang
  32844. * @param {*} value The value to check.
  32845. * @returns {boolean} Returns `true` if `value` is an array-like object,
  32846. * else `false`.
  32847. * @example
  32848. *
  32849. * _.isArrayLikeObject([1, 2, 3]);
  32850. * // => true
  32851. *
  32852. * _.isArrayLikeObject(document.body.children);
  32853. * // => true
  32854. *
  32855. * _.isArrayLikeObject('abc');
  32856. * // => false
  32857. *
  32858. * _.isArrayLikeObject(_.noop);
  32859. * // => false
  32860. */
  32861. function isArrayLikeObject(value) {
  32862. return isObjectLike(value) && isArrayLike(value);
  32863. }
  32864. /**
  32865. * Checks if `value` is classified as a boolean primitive or object.
  32866. *
  32867. * @static
  32868. * @memberOf _
  32869. * @since 0.1.0
  32870. * @category Lang
  32871. * @param {*} value The value to check.
  32872. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
  32873. * @example
  32874. *
  32875. * _.isBoolean(false);
  32876. * // => true
  32877. *
  32878. * _.isBoolean(null);
  32879. * // => false
  32880. */
  32881. function isBoolean(value) {
  32882. return value === true || value === false ||
  32883. (isObjectLike(value) && baseGetTag(value) == boolTag);
  32884. }
  32885. /**
  32886. * Checks if `value` is a buffer.
  32887. *
  32888. * @static
  32889. * @memberOf _
  32890. * @since 4.3.0
  32891. * @category Lang
  32892. * @param {*} value The value to check.
  32893. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  32894. * @example
  32895. *
  32896. * _.isBuffer(new Buffer(2));
  32897. * // => true
  32898. *
  32899. * _.isBuffer(new Uint8Array(2));
  32900. * // => false
  32901. */
  32902. var isBuffer = nativeIsBuffer || stubFalse;
  32903. /**
  32904. * Checks if `value` is classified as a `Date` object.
  32905. *
  32906. * @static
  32907. * @memberOf _
  32908. * @since 0.1.0
  32909. * @category Lang
  32910. * @param {*} value The value to check.
  32911. * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
  32912. * @example
  32913. *
  32914. * _.isDate(new Date);
  32915. * // => true
  32916. *
  32917. * _.isDate('Mon April 23 2012');
  32918. * // => false
  32919. */
  32920. var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
  32921. /**
  32922. * Checks if `value` is likely a DOM element.
  32923. *
  32924. * @static
  32925. * @memberOf _
  32926. * @since 0.1.0
  32927. * @category Lang
  32928. * @param {*} value The value to check.
  32929. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
  32930. * @example
  32931. *
  32932. * _.isElement(document.body);
  32933. * // => true
  32934. *
  32935. * _.isElement('<body>');
  32936. * // => false
  32937. */
  32938. function isElement(value) {
  32939. return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
  32940. }
  32941. /**
  32942. * Checks if `value` is an empty object, collection, map, or set.
  32943. *
  32944. * Objects are considered empty if they have no own enumerable string keyed
  32945. * properties.
  32946. *
  32947. * Array-like values such as `arguments` objects, arrays, buffers, strings, or
  32948. * jQuery-like collections are considered empty if they have a `length` of `0`.
  32949. * Similarly, maps and sets are considered empty if they have a `size` of `0`.
  32950. *
  32951. * @static
  32952. * @memberOf _
  32953. * @since 0.1.0
  32954. * @category Lang
  32955. * @param {*} value The value to check.
  32956. * @returns {boolean} Returns `true` if `value` is empty, else `false`.
  32957. * @example
  32958. *
  32959. * _.isEmpty(null);
  32960. * // => true
  32961. *
  32962. * _.isEmpty(true);
  32963. * // => true
  32964. *
  32965. * _.isEmpty(1);
  32966. * // => true
  32967. *
  32968. * _.isEmpty([1, 2, 3]);
  32969. * // => false
  32970. *
  32971. * _.isEmpty({ 'a': 1 });
  32972. * // => false
  32973. */
  32974. function isEmpty(value) {
  32975. if (value == null) {
  32976. return true;
  32977. }
  32978. if (isArrayLike(value) &&
  32979. (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
  32980. isBuffer(value) || isTypedArray(value) || isArguments(value))) {
  32981. return !value.length;
  32982. }
  32983. var tag = getTag(value);
  32984. if (tag == mapTag || tag == setTag) {
  32985. return !value.size;
  32986. }
  32987. if (isPrototype(value)) {
  32988. return !baseKeys(value).length;
  32989. }
  32990. for (var key in value) {
  32991. if (hasOwnProperty.call(value, key)) {
  32992. return false;
  32993. }
  32994. }
  32995. return true;
  32996. }
  32997. /**
  32998. * Performs a deep comparison between two values to determine if they are
  32999. * equivalent.
  33000. *
  33001. * **Note:** This method supports comparing arrays, array buffers, booleans,
  33002. * date objects, error objects, maps, numbers, `Object` objects, regexes,
  33003. * sets, strings, symbols, and typed arrays. `Object` objects are compared
  33004. * by their own, not inherited, enumerable properties. Functions and DOM
  33005. * nodes are compared by strict equality, i.e. `===`.
  33006. *
  33007. * @static
  33008. * @memberOf _
  33009. * @since 0.1.0
  33010. * @category Lang
  33011. * @param {*} value The value to compare.
  33012. * @param {*} other The other value to compare.
  33013. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  33014. * @example
  33015. *
  33016. * var object = { 'a': 1 };
  33017. * var other = { 'a': 1 };
  33018. *
  33019. * _.isEqual(object, other);
  33020. * // => true
  33021. *
  33022. * object === other;
  33023. * // => false
  33024. */
  33025. function isEqual(value, other) {
  33026. return baseIsEqual(value, other);
  33027. }
  33028. /**
  33029. * This method is like `_.isEqual` except that it accepts `customizer` which
  33030. * is invoked to compare values. If `customizer` returns `undefined`, comparisons
  33031. * are handled by the method instead. The `customizer` is invoked with up to
  33032. * six arguments: (objValue, othValue [, index|key, object, other, stack]).
  33033. *
  33034. * @static
  33035. * @memberOf _
  33036. * @since 4.0.0
  33037. * @category Lang
  33038. * @param {*} value The value to compare.
  33039. * @param {*} other The other value to compare.
  33040. * @param {Function} [customizer] The function to customize comparisons.
  33041. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  33042. * @example
  33043. *
  33044. * function isGreeting(value) {
  33045. * return /^h(?:i|ello)$/.test(value);
  33046. * }
  33047. *
  33048. * function customizer(objValue, othValue) {
  33049. * if (isGreeting(objValue) && isGreeting(othValue)) {
  33050. * return true;
  33051. * }
  33052. * }
  33053. *
  33054. * var array = ['hello', 'goodbye'];
  33055. * var other = ['hi', 'goodbye'];
  33056. *
  33057. * _.isEqualWith(array, other, customizer);
  33058. * // => true
  33059. */
  33060. function isEqualWith(value, other, customizer) {
  33061. customizer = typeof customizer == 'function' ? customizer : undefined;
  33062. var result = customizer ? customizer(value, other) : undefined;
  33063. return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
  33064. }
  33065. /**
  33066. * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
  33067. * `SyntaxError`, `TypeError`, or `URIError` object.
  33068. *
  33069. * @static
  33070. * @memberOf _
  33071. * @since 3.0.0
  33072. * @category Lang
  33073. * @param {*} value The value to check.
  33074. * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
  33075. * @example
  33076. *
  33077. * _.isError(new Error);
  33078. * // => true
  33079. *
  33080. * _.isError(Error);
  33081. * // => false
  33082. */
  33083. function isError(value) {
  33084. if (!isObjectLike(value)) {
  33085. return false;
  33086. }
  33087. var tag = baseGetTag(value);
  33088. return tag == errorTag || tag == domExcTag ||
  33089. (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
  33090. }
  33091. /**
  33092. * Checks if `value` is a finite primitive number.
  33093. *
  33094. * **Note:** This method is based on
  33095. * [`Number.isFinite`](https://mdn.io/Number/isFinite).
  33096. *
  33097. * @static
  33098. * @memberOf _
  33099. * @since 0.1.0
  33100. * @category Lang
  33101. * @param {*} value The value to check.
  33102. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
  33103. * @example
  33104. *
  33105. * _.isFinite(3);
  33106. * // => true
  33107. *
  33108. * _.isFinite(Number.MIN_VALUE);
  33109. * // => true
  33110. *
  33111. * _.isFinite(Infinity);
  33112. * // => false
  33113. *
  33114. * _.isFinite('3');
  33115. * // => false
  33116. */
  33117. function isFinite(value) {
  33118. return typeof value == 'number' && nativeIsFinite(value);
  33119. }
  33120. /**
  33121. * Checks if `value` is classified as a `Function` object.
  33122. *
  33123. * @static
  33124. * @memberOf _
  33125. * @since 0.1.0
  33126. * @category Lang
  33127. * @param {*} value The value to check.
  33128. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  33129. * @example
  33130. *
  33131. * _.isFunction(_);
  33132. * // => true
  33133. *
  33134. * _.isFunction(/abc/);
  33135. * // => false
  33136. */
  33137. function isFunction(value) {
  33138. if (!isObject(value)) {
  33139. return false;
  33140. }
  33141. // The use of `Object#toString` avoids issues with the `typeof` operator
  33142. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  33143. var tag = baseGetTag(value);
  33144. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  33145. }
  33146. /**
  33147. * Checks if `value` is an integer.
  33148. *
  33149. * **Note:** This method is based on
  33150. * [`Number.isInteger`](https://mdn.io/Number/isInteger).
  33151. *
  33152. * @static
  33153. * @memberOf _
  33154. * @since 4.0.0
  33155. * @category Lang
  33156. * @param {*} value The value to check.
  33157. * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
  33158. * @example
  33159. *
  33160. * _.isInteger(3);
  33161. * // => true
  33162. *
  33163. * _.isInteger(Number.MIN_VALUE);
  33164. * // => false
  33165. *
  33166. * _.isInteger(Infinity);
  33167. * // => false
  33168. *
  33169. * _.isInteger('3');
  33170. * // => false
  33171. */
  33172. function isInteger(value) {
  33173. return typeof value == 'number' && value == toInteger(value);
  33174. }
  33175. /**
  33176. * Checks if `value` is a valid array-like length.
  33177. *
  33178. * **Note:** This method is loosely based on
  33179. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  33180. *
  33181. * @static
  33182. * @memberOf _
  33183. * @since 4.0.0
  33184. * @category Lang
  33185. * @param {*} value The value to check.
  33186. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  33187. * @example
  33188. *
  33189. * _.isLength(3);
  33190. * // => true
  33191. *
  33192. * _.isLength(Number.MIN_VALUE);
  33193. * // => false
  33194. *
  33195. * _.isLength(Infinity);
  33196. * // => false
  33197. *
  33198. * _.isLength('3');
  33199. * // => false
  33200. */
  33201. function isLength(value) {
  33202. return typeof value == 'number' &&
  33203. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  33204. }
  33205. /**
  33206. * Checks if `value` is the
  33207. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  33208. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  33209. *
  33210. * @static
  33211. * @memberOf _
  33212. * @since 0.1.0
  33213. * @category Lang
  33214. * @param {*} value The value to check.
  33215. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  33216. * @example
  33217. *
  33218. * _.isObject({});
  33219. * // => true
  33220. *
  33221. * _.isObject([1, 2, 3]);
  33222. * // => true
  33223. *
  33224. * _.isObject(_.noop);
  33225. * // => true
  33226. *
  33227. * _.isObject(null);
  33228. * // => false
  33229. */
  33230. function isObject(value) {
  33231. var type = typeof value;
  33232. return value != null && (type == 'object' || type == 'function');
  33233. }
  33234. /**
  33235. * Checks if `value` is object-like. A value is object-like if it's not `null`
  33236. * and has a `typeof` result of "object".
  33237. *
  33238. * @static
  33239. * @memberOf _
  33240. * @since 4.0.0
  33241. * @category Lang
  33242. * @param {*} value The value to check.
  33243. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  33244. * @example
  33245. *
  33246. * _.isObjectLike({});
  33247. * // => true
  33248. *
  33249. * _.isObjectLike([1, 2, 3]);
  33250. * // => true
  33251. *
  33252. * _.isObjectLike(_.noop);
  33253. * // => false
  33254. *
  33255. * _.isObjectLike(null);
  33256. * // => false
  33257. */
  33258. function isObjectLike(value) {
  33259. return value != null && typeof value == 'object';
  33260. }
  33261. /**
  33262. * Checks if `value` is classified as a `Map` object.
  33263. *
  33264. * @static
  33265. * @memberOf _
  33266. * @since 4.3.0
  33267. * @category Lang
  33268. * @param {*} value The value to check.
  33269. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  33270. * @example
  33271. *
  33272. * _.isMap(new Map);
  33273. * // => true
  33274. *
  33275. * _.isMap(new WeakMap);
  33276. * // => false
  33277. */
  33278. var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
  33279. /**
  33280. * Performs a partial deep comparison between `object` and `source` to
  33281. * determine if `object` contains equivalent property values.
  33282. *
  33283. * **Note:** This method is equivalent to `_.matches` when `source` is
  33284. * partially applied.
  33285. *
  33286. * Partial comparisons will match empty array and empty object `source`
  33287. * values against any array or object value, respectively. See `_.isEqual`
  33288. * for a list of supported value comparisons.
  33289. *
  33290. * @static
  33291. * @memberOf _
  33292. * @since 3.0.0
  33293. * @category Lang
  33294. * @param {Object} object The object to inspect.
  33295. * @param {Object} source The object of property values to match.
  33296. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  33297. * @example
  33298. *
  33299. * var object = { 'a': 1, 'b': 2 };
  33300. *
  33301. * _.isMatch(object, { 'b': 2 });
  33302. * // => true
  33303. *
  33304. * _.isMatch(object, { 'b': 1 });
  33305. * // => false
  33306. */
  33307. function isMatch(object, source) {
  33308. return object === source || baseIsMatch(object, source, getMatchData(source));
  33309. }
  33310. /**
  33311. * This method is like `_.isMatch` except that it accepts `customizer` which
  33312. * is invoked to compare values. If `customizer` returns `undefined`, comparisons
  33313. * are handled by the method instead. The `customizer` is invoked with five
  33314. * arguments: (objValue, srcValue, index|key, object, source).
  33315. *
  33316. * @static
  33317. * @memberOf _
  33318. * @since 4.0.0
  33319. * @category Lang
  33320. * @param {Object} object The object to inspect.
  33321. * @param {Object} source The object of property values to match.
  33322. * @param {Function} [customizer] The function to customize comparisons.
  33323. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  33324. * @example
  33325. *
  33326. * function isGreeting(value) {
  33327. * return /^h(?:i|ello)$/.test(value);
  33328. * }
  33329. *
  33330. * function customizer(objValue, srcValue) {
  33331. * if (isGreeting(objValue) && isGreeting(srcValue)) {
  33332. * return true;
  33333. * }
  33334. * }
  33335. *
  33336. * var object = { 'greeting': 'hello' };
  33337. * var source = { 'greeting': 'hi' };
  33338. *
  33339. * _.isMatchWith(object, source, customizer);
  33340. * // => true
  33341. */
  33342. function isMatchWith(object, source, customizer) {
  33343. customizer = typeof customizer == 'function' ? customizer : undefined;
  33344. return baseIsMatch(object, source, getMatchData(source), customizer);
  33345. }
  33346. /**
  33347. * Checks if `value` is `NaN`.
  33348. *
  33349. * **Note:** This method is based on
  33350. * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
  33351. * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
  33352. * `undefined` and other non-number values.
  33353. *
  33354. * @static
  33355. * @memberOf _
  33356. * @since 0.1.0
  33357. * @category Lang
  33358. * @param {*} value The value to check.
  33359. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  33360. * @example
  33361. *
  33362. * _.isNaN(NaN);
  33363. * // => true
  33364. *
  33365. * _.isNaN(new Number(NaN));
  33366. * // => true
  33367. *
  33368. * isNaN(undefined);
  33369. * // => true
  33370. *
  33371. * _.isNaN(undefined);
  33372. * // => false
  33373. */
  33374. function isNaN(value) {
  33375. // An `NaN` primitive is the only value that is not equal to itself.
  33376. // Perform the `toStringTag` check first to avoid errors with some
  33377. // ActiveX objects in IE.
  33378. return isNumber(value) && value != +value;
  33379. }
  33380. /**
  33381. * Checks if `value` is a pristine native function.
  33382. *
  33383. * **Note:** This method can't reliably detect native functions in the presence
  33384. * of the core-js package because core-js circumvents this kind of detection.
  33385. * Despite multiple requests, the core-js maintainer has made it clear: any
  33386. * attempt to fix the detection will be obstructed. As a result, we're left
  33387. * with little choice but to throw an error. Unfortunately, this also affects
  33388. * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
  33389. * which rely on core-js.
  33390. *
  33391. * @static
  33392. * @memberOf _
  33393. * @since 3.0.0
  33394. * @category Lang
  33395. * @param {*} value The value to check.
  33396. * @returns {boolean} Returns `true` if `value` is a native function,
  33397. * else `false`.
  33398. * @example
  33399. *
  33400. * _.isNative(Array.prototype.push);
  33401. * // => true
  33402. *
  33403. * _.isNative(_);
  33404. * // => false
  33405. */
  33406. function isNative(value) {
  33407. if (isMaskable(value)) {
  33408. throw new Error(CORE_ERROR_TEXT);
  33409. }
  33410. return baseIsNative(value);
  33411. }
  33412. /**
  33413. * Checks if `value` is `null`.
  33414. *
  33415. * @static
  33416. * @memberOf _
  33417. * @since 0.1.0
  33418. * @category Lang
  33419. * @param {*} value The value to check.
  33420. * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
  33421. * @example
  33422. *
  33423. * _.isNull(null);
  33424. * // => true
  33425. *
  33426. * _.isNull(void 0);
  33427. * // => false
  33428. */
  33429. function isNull(value) {
  33430. return value === null;
  33431. }
  33432. /**
  33433. * Checks if `value` is `null` or `undefined`.
  33434. *
  33435. * @static
  33436. * @memberOf _
  33437. * @since 4.0.0
  33438. * @category Lang
  33439. * @param {*} value The value to check.
  33440. * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
  33441. * @example
  33442. *
  33443. * _.isNil(null);
  33444. * // => true
  33445. *
  33446. * _.isNil(void 0);
  33447. * // => true
  33448. *
  33449. * _.isNil(NaN);
  33450. * // => false
  33451. */
  33452. function isNil(value) {
  33453. return value == null;
  33454. }
  33455. /**
  33456. * Checks if `value` is classified as a `Number` primitive or object.
  33457. *
  33458. * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
  33459. * classified as numbers, use the `_.isFinite` method.
  33460. *
  33461. * @static
  33462. * @memberOf _
  33463. * @since 0.1.0
  33464. * @category Lang
  33465. * @param {*} value The value to check.
  33466. * @returns {boolean} Returns `true` if `value` is a number, else `false`.
  33467. * @example
  33468. *
  33469. * _.isNumber(3);
  33470. * // => true
  33471. *
  33472. * _.isNumber(Number.MIN_VALUE);
  33473. * // => true
  33474. *
  33475. * _.isNumber(Infinity);
  33476. * // => true
  33477. *
  33478. * _.isNumber('3');
  33479. * // => false
  33480. */
  33481. function isNumber(value) {
  33482. return typeof value == 'number' ||
  33483. (isObjectLike(value) && baseGetTag(value) == numberTag);
  33484. }
  33485. /**
  33486. * Checks if `value` is a plain object, that is, an object created by the
  33487. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  33488. *
  33489. * @static
  33490. * @memberOf _
  33491. * @since 0.8.0
  33492. * @category Lang
  33493. * @param {*} value The value to check.
  33494. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  33495. * @example
  33496. *
  33497. * function Foo() {
  33498. * this.a = 1;
  33499. * }
  33500. *
  33501. * _.isPlainObject(new Foo);
  33502. * // => false
  33503. *
  33504. * _.isPlainObject([1, 2, 3]);
  33505. * // => false
  33506. *
  33507. * _.isPlainObject({ 'x': 0, 'y': 0 });
  33508. * // => true
  33509. *
  33510. * _.isPlainObject(Object.create(null));
  33511. * // => true
  33512. */
  33513. function isPlainObject(value) {
  33514. if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
  33515. return false;
  33516. }
  33517. var proto = getPrototype(value);
  33518. if (proto === null) {
  33519. return true;
  33520. }
  33521. var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
  33522. return typeof Ctor == 'function' && Ctor instanceof Ctor &&
  33523. funcToString.call(Ctor) == objectCtorString;
  33524. }
  33525. /**
  33526. * Checks if `value` is classified as a `RegExp` object.
  33527. *
  33528. * @static
  33529. * @memberOf _
  33530. * @since 0.1.0
  33531. * @category Lang
  33532. * @param {*} value The value to check.
  33533. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
  33534. * @example
  33535. *
  33536. * _.isRegExp(/abc/);
  33537. * // => true
  33538. *
  33539. * _.isRegExp('/abc/');
  33540. * // => false
  33541. */
  33542. var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
  33543. /**
  33544. * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
  33545. * double precision number which isn't the result of a rounded unsafe integer.
  33546. *
  33547. * **Note:** This method is based on
  33548. * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
  33549. *
  33550. * @static
  33551. * @memberOf _
  33552. * @since 4.0.0
  33553. * @category Lang
  33554. * @param {*} value The value to check.
  33555. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
  33556. * @example
  33557. *
  33558. * _.isSafeInteger(3);
  33559. * // => true
  33560. *
  33561. * _.isSafeInteger(Number.MIN_VALUE);
  33562. * // => false
  33563. *
  33564. * _.isSafeInteger(Infinity);
  33565. * // => false
  33566. *
  33567. * _.isSafeInteger('3');
  33568. * // => false
  33569. */
  33570. function isSafeInteger(value) {
  33571. return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
  33572. }
  33573. /**
  33574. * Checks if `value` is classified as a `Set` object.
  33575. *
  33576. * @static
  33577. * @memberOf _
  33578. * @since 4.3.0
  33579. * @category Lang
  33580. * @param {*} value The value to check.
  33581. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  33582. * @example
  33583. *
  33584. * _.isSet(new Set);
  33585. * // => true
  33586. *
  33587. * _.isSet(new WeakSet);
  33588. * // => false
  33589. */
  33590. var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
  33591. /**
  33592. * Checks if `value` is classified as a `String` primitive or object.
  33593. *
  33594. * @static
  33595. * @since 0.1.0
  33596. * @memberOf _
  33597. * @category Lang
  33598. * @param {*} value The value to check.
  33599. * @returns {boolean} Returns `true` if `value` is a string, else `false`.
  33600. * @example
  33601. *
  33602. * _.isString('abc');
  33603. * // => true
  33604. *
  33605. * _.isString(1);
  33606. * // => false
  33607. */
  33608. function isString(value) {
  33609. return typeof value == 'string' ||
  33610. (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
  33611. }
  33612. /**
  33613. * Checks if `value` is classified as a `Symbol` primitive or object.
  33614. *
  33615. * @static
  33616. * @memberOf _
  33617. * @since 4.0.0
  33618. * @category Lang
  33619. * @param {*} value The value to check.
  33620. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  33621. * @example
  33622. *
  33623. * _.isSymbol(Symbol.iterator);
  33624. * // => true
  33625. *
  33626. * _.isSymbol('abc');
  33627. * // => false
  33628. */
  33629. function isSymbol(value) {
  33630. return typeof value == 'symbol' ||
  33631. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  33632. }
  33633. /**
  33634. * Checks if `value` is classified as a typed array.
  33635. *
  33636. * @static
  33637. * @memberOf _
  33638. * @since 3.0.0
  33639. * @category Lang
  33640. * @param {*} value The value to check.
  33641. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  33642. * @example
  33643. *
  33644. * _.isTypedArray(new Uint8Array);
  33645. * // => true
  33646. *
  33647. * _.isTypedArray([]);
  33648. * // => false
  33649. */
  33650. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  33651. /**
  33652. * Checks if `value` is `undefined`.
  33653. *
  33654. * @static
  33655. * @since 0.1.0
  33656. * @memberOf _
  33657. * @category Lang
  33658. * @param {*} value The value to check.
  33659. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
  33660. * @example
  33661. *
  33662. * _.isUndefined(void 0);
  33663. * // => true
  33664. *
  33665. * _.isUndefined(null);
  33666. * // => false
  33667. */
  33668. function isUndefined(value) {
  33669. return value === undefined;
  33670. }
  33671. /**
  33672. * Checks if `value` is classified as a `WeakMap` object.
  33673. *
  33674. * @static
  33675. * @memberOf _
  33676. * @since 4.3.0
  33677. * @category Lang
  33678. * @param {*} value The value to check.
  33679. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
  33680. * @example
  33681. *
  33682. * _.isWeakMap(new WeakMap);
  33683. * // => true
  33684. *
  33685. * _.isWeakMap(new Map);
  33686. * // => false
  33687. */
  33688. function isWeakMap(value) {
  33689. return isObjectLike(value) && getTag(value) == weakMapTag;
  33690. }
  33691. /**
  33692. * Checks if `value` is classified as a `WeakSet` object.
  33693. *
  33694. * @static
  33695. * @memberOf _
  33696. * @since 4.3.0
  33697. * @category Lang
  33698. * @param {*} value The value to check.
  33699. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
  33700. * @example
  33701. *
  33702. * _.isWeakSet(new WeakSet);
  33703. * // => true
  33704. *
  33705. * _.isWeakSet(new Set);
  33706. * // => false
  33707. */
  33708. function isWeakSet(value) {
  33709. return isObjectLike(value) && baseGetTag(value) == weakSetTag;
  33710. }
  33711. /**
  33712. * Checks if `value` is less than `other`.
  33713. *
  33714. * @static
  33715. * @memberOf _
  33716. * @since 3.9.0
  33717. * @category Lang
  33718. * @param {*} value The value to compare.
  33719. * @param {*} other The other value to compare.
  33720. * @returns {boolean} Returns `true` if `value` is less than `other`,
  33721. * else `false`.
  33722. * @see _.gt
  33723. * @example
  33724. *
  33725. * _.lt(1, 3);
  33726. * // => true
  33727. *
  33728. * _.lt(3, 3);
  33729. * // => false
  33730. *
  33731. * _.lt(3, 1);
  33732. * // => false
  33733. */
  33734. var lt = createRelationalOperation(baseLt);
  33735. /**
  33736. * Checks if `value` is less than or equal to `other`.
  33737. *
  33738. * @static
  33739. * @memberOf _
  33740. * @since 3.9.0
  33741. * @category Lang
  33742. * @param {*} value The value to compare.
  33743. * @param {*} other The other value to compare.
  33744. * @returns {boolean} Returns `true` if `value` is less than or equal to
  33745. * `other`, else `false`.
  33746. * @see _.gte
  33747. * @example
  33748. *
  33749. * _.lte(1, 3);
  33750. * // => true
  33751. *
  33752. * _.lte(3, 3);
  33753. * // => true
  33754. *
  33755. * _.lte(3, 1);
  33756. * // => false
  33757. */
  33758. var lte = createRelationalOperation(function(value, other) {
  33759. return value <= other;
  33760. });
  33761. /**
  33762. * Converts `value` to an array.
  33763. *
  33764. * @static
  33765. * @since 0.1.0
  33766. * @memberOf _
  33767. * @category Lang
  33768. * @param {*} value The value to convert.
  33769. * @returns {Array} Returns the converted array.
  33770. * @example
  33771. *
  33772. * _.toArray({ 'a': 1, 'b': 2 });
  33773. * // => [1, 2]
  33774. *
  33775. * _.toArray('abc');
  33776. * // => ['a', 'b', 'c']
  33777. *
  33778. * _.toArray(1);
  33779. * // => []
  33780. *
  33781. * _.toArray(null);
  33782. * // => []
  33783. */
  33784. function toArray(value) {
  33785. if (!value) {
  33786. return [];
  33787. }
  33788. if (isArrayLike(value)) {
  33789. return isString(value) ? stringToArray(value) : copyArray(value);
  33790. }
  33791. if (symIterator && value[symIterator]) {
  33792. return iteratorToArray(value[symIterator]());
  33793. }
  33794. var tag = getTag(value),
  33795. func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
  33796. return func(value);
  33797. }
  33798. /**
  33799. * Converts `value` to a finite number.
  33800. *
  33801. * @static
  33802. * @memberOf _
  33803. * @since 4.12.0
  33804. * @category Lang
  33805. * @param {*} value The value to convert.
  33806. * @returns {number} Returns the converted number.
  33807. * @example
  33808. *
  33809. * _.toFinite(3.2);
  33810. * // => 3.2
  33811. *
  33812. * _.toFinite(Number.MIN_VALUE);
  33813. * // => 5e-324
  33814. *
  33815. * _.toFinite(Infinity);
  33816. * // => 1.7976931348623157e+308
  33817. *
  33818. * _.toFinite('3.2');
  33819. * // => 3.2
  33820. */
  33821. function toFinite(value) {
  33822. if (!value) {
  33823. return value === 0 ? value : 0;
  33824. }
  33825. value = toNumber(value);
  33826. if (value === INFINITY || value === -INFINITY) {
  33827. var sign = (value < 0 ? -1 : 1);
  33828. return sign * MAX_INTEGER;
  33829. }
  33830. return value === value ? value : 0;
  33831. }
  33832. /**
  33833. * Converts `value` to an integer.
  33834. *
  33835. * **Note:** This method is loosely based on
  33836. * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
  33837. *
  33838. * @static
  33839. * @memberOf _
  33840. * @since 4.0.0
  33841. * @category Lang
  33842. * @param {*} value The value to convert.
  33843. * @returns {number} Returns the converted integer.
  33844. * @example
  33845. *
  33846. * _.toInteger(3.2);
  33847. * // => 3
  33848. *
  33849. * _.toInteger(Number.MIN_VALUE);
  33850. * // => 0
  33851. *
  33852. * _.toInteger(Infinity);
  33853. * // => 1.7976931348623157e+308
  33854. *
  33855. * _.toInteger('3.2');
  33856. * // => 3
  33857. */
  33858. function toInteger(value) {
  33859. var result = toFinite(value),
  33860. remainder = result % 1;
  33861. return result === result ? (remainder ? result - remainder : result) : 0;
  33862. }
  33863. /**
  33864. * Converts `value` to an integer suitable for use as the length of an
  33865. * array-like object.
  33866. *
  33867. * **Note:** This method is based on
  33868. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  33869. *
  33870. * @static
  33871. * @memberOf _
  33872. * @since 4.0.0
  33873. * @category Lang
  33874. * @param {*} value The value to convert.
  33875. * @returns {number} Returns the converted integer.
  33876. * @example
  33877. *
  33878. * _.toLength(3.2);
  33879. * // => 3
  33880. *
  33881. * _.toLength(Number.MIN_VALUE);
  33882. * // => 0
  33883. *
  33884. * _.toLength(Infinity);
  33885. * // => 4294967295
  33886. *
  33887. * _.toLength('3.2');
  33888. * // => 3
  33889. */
  33890. function toLength(value) {
  33891. return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
  33892. }
  33893. /**
  33894. * Converts `value` to a number.
  33895. *
  33896. * @static
  33897. * @memberOf _
  33898. * @since 4.0.0
  33899. * @category Lang
  33900. * @param {*} value The value to process.
  33901. * @returns {number} Returns the number.
  33902. * @example
  33903. *
  33904. * _.toNumber(3.2);
  33905. * // => 3.2
  33906. *
  33907. * _.toNumber(Number.MIN_VALUE);
  33908. * // => 5e-324
  33909. *
  33910. * _.toNumber(Infinity);
  33911. * // => Infinity
  33912. *
  33913. * _.toNumber('3.2');
  33914. * // => 3.2
  33915. */
  33916. function toNumber(value) {
  33917. if (typeof value == 'number') {
  33918. return value;
  33919. }
  33920. if (isSymbol(value)) {
  33921. return NAN;
  33922. }
  33923. if (isObject(value)) {
  33924. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  33925. value = isObject(other) ? (other + '') : other;
  33926. }
  33927. if (typeof value != 'string') {
  33928. return value === 0 ? value : +value;
  33929. }
  33930. value = value.replace(reTrim, '');
  33931. var isBinary = reIsBinary.test(value);
  33932. return (isBinary || reIsOctal.test(value))
  33933. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  33934. : (reIsBadHex.test(value) ? NAN : +value);
  33935. }
  33936. /**
  33937. * Converts `value` to a plain object flattening inherited enumerable string
  33938. * keyed properties of `value` to own properties of the plain object.
  33939. *
  33940. * @static
  33941. * @memberOf _
  33942. * @since 3.0.0
  33943. * @category Lang
  33944. * @param {*} value The value to convert.
  33945. * @returns {Object} Returns the converted plain object.
  33946. * @example
  33947. *
  33948. * function Foo() {
  33949. * this.b = 2;
  33950. * }
  33951. *
  33952. * Foo.prototype.c = 3;
  33953. *
  33954. * _.assign({ 'a': 1 }, new Foo);
  33955. * // => { 'a': 1, 'b': 2 }
  33956. *
  33957. * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
  33958. * // => { 'a': 1, 'b': 2, 'c': 3 }
  33959. */
  33960. function toPlainObject(value) {
  33961. return copyObject(value, keysIn(value));
  33962. }
  33963. /**
  33964. * Converts `value` to a safe integer. A safe integer can be compared and
  33965. * represented correctly.
  33966. *
  33967. * @static
  33968. * @memberOf _
  33969. * @since 4.0.0
  33970. * @category Lang
  33971. * @param {*} value The value to convert.
  33972. * @returns {number} Returns the converted integer.
  33973. * @example
  33974. *
  33975. * _.toSafeInteger(3.2);
  33976. * // => 3
  33977. *
  33978. * _.toSafeInteger(Number.MIN_VALUE);
  33979. * // => 0
  33980. *
  33981. * _.toSafeInteger(Infinity);
  33982. * // => 9007199254740991
  33983. *
  33984. * _.toSafeInteger('3.2');
  33985. * // => 3
  33986. */
  33987. function toSafeInteger(value) {
  33988. return value
  33989. ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
  33990. : (value === 0 ? value : 0);
  33991. }
  33992. /**
  33993. * Converts `value` to a string. An empty string is returned for `null`
  33994. * and `undefined` values. The sign of `-0` is preserved.
  33995. *
  33996. * @static
  33997. * @memberOf _
  33998. * @since 4.0.0
  33999. * @category Lang
  34000. * @param {*} value The value to convert.
  34001. * @returns {string} Returns the converted string.
  34002. * @example
  34003. *
  34004. * _.toString(null);
  34005. * // => ''
  34006. *
  34007. * _.toString(-0);
  34008. * // => '-0'
  34009. *
  34010. * _.toString([1, 2, 3]);
  34011. * // => '1,2,3'
  34012. */
  34013. function toString(value) {
  34014. return value == null ? '' : baseToString(value);
  34015. }
  34016. /*------------------------------------------------------------------------*/
  34017. /**
  34018. * Assigns own enumerable string keyed properties of source objects to the
  34019. * destination object. Source objects are applied from left to right.
  34020. * Subsequent sources overwrite property assignments of previous sources.
  34021. *
  34022. * **Note:** This method mutates `object` and is loosely based on
  34023. * [`Object.assign`](https://mdn.io/Object/assign).
  34024. *
  34025. * @static
  34026. * @memberOf _
  34027. * @since 0.10.0
  34028. * @category Object
  34029. * @param {Object} object The destination object.
  34030. * @param {...Object} [sources] The source objects.
  34031. * @returns {Object} Returns `object`.
  34032. * @see _.assignIn
  34033. * @example
  34034. *
  34035. * function Foo() {
  34036. * this.a = 1;
  34037. * }
  34038. *
  34039. * function Bar() {
  34040. * this.c = 3;
  34041. * }
  34042. *
  34043. * Foo.prototype.b = 2;
  34044. * Bar.prototype.d = 4;
  34045. *
  34046. * _.assign({ 'a': 0 }, new Foo, new Bar);
  34047. * // => { 'a': 1, 'c': 3 }
  34048. */
  34049. var assign = createAssigner(function(object, source) {
  34050. if (isPrototype(source) || isArrayLike(source)) {
  34051. copyObject(source, keys(source), object);
  34052. return;
  34053. }
  34054. for (var key in source) {
  34055. if (hasOwnProperty.call(source, key)) {
  34056. assignValue(object, key, source[key]);
  34057. }
  34058. }
  34059. });
  34060. /**
  34061. * This method is like `_.assign` except that it iterates over own and
  34062. * inherited source properties.
  34063. *
  34064. * **Note:** This method mutates `object`.
  34065. *
  34066. * @static
  34067. * @memberOf _
  34068. * @since 4.0.0
  34069. * @alias extend
  34070. * @category Object
  34071. * @param {Object} object The destination object.
  34072. * @param {...Object} [sources] The source objects.
  34073. * @returns {Object} Returns `object`.
  34074. * @see _.assign
  34075. * @example
  34076. *
  34077. * function Foo() {
  34078. * this.a = 1;
  34079. * }
  34080. *
  34081. * function Bar() {
  34082. * this.c = 3;
  34083. * }
  34084. *
  34085. * Foo.prototype.b = 2;
  34086. * Bar.prototype.d = 4;
  34087. *
  34088. * _.assignIn({ 'a': 0 }, new Foo, new Bar);
  34089. * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
  34090. */
  34091. var assignIn = createAssigner(function(object, source) {
  34092. copyObject(source, keysIn(source), object);
  34093. });
  34094. /**
  34095. * This method is like `_.assignIn` except that it accepts `customizer`
  34096. * which is invoked to produce the assigned values. If `customizer` returns
  34097. * `undefined`, assignment is handled by the method instead. The `customizer`
  34098. * is invoked with five arguments: (objValue, srcValue, key, object, source).
  34099. *
  34100. * **Note:** This method mutates `object`.
  34101. *
  34102. * @static
  34103. * @memberOf _
  34104. * @since 4.0.0
  34105. * @alias extendWith
  34106. * @category Object
  34107. * @param {Object} object The destination object.
  34108. * @param {...Object} sources The source objects.
  34109. * @param {Function} [customizer] The function to customize assigned values.
  34110. * @returns {Object} Returns `object`.
  34111. * @see _.assignWith
  34112. * @example
  34113. *
  34114. * function customizer(objValue, srcValue) {
  34115. * return _.isUndefined(objValue) ? srcValue : objValue;
  34116. * }
  34117. *
  34118. * var defaults = _.partialRight(_.assignInWith, customizer);
  34119. *
  34120. * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
  34121. * // => { 'a': 1, 'b': 2 }
  34122. */
  34123. var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
  34124. copyObject(source, keysIn(source), object, customizer);
  34125. });
  34126. /**
  34127. * This method is like `_.assign` except that it accepts `customizer`
  34128. * which is invoked to produce the assigned values. If `customizer` returns
  34129. * `undefined`, assignment is handled by the method instead. The `customizer`
  34130. * is invoked with five arguments: (objValue, srcValue, key, object, source).
  34131. *
  34132. * **Note:** This method mutates `object`.
  34133. *
  34134. * @static
  34135. * @memberOf _
  34136. * @since 4.0.0
  34137. * @category Object
  34138. * @param {Object} object The destination object.
  34139. * @param {...Object} sources The source objects.
  34140. * @param {Function} [customizer] The function to customize assigned values.
  34141. * @returns {Object} Returns `object`.
  34142. * @see _.assignInWith
  34143. * @example
  34144. *
  34145. * function customizer(objValue, srcValue) {
  34146. * return _.isUndefined(objValue) ? srcValue : objValue;
  34147. * }
  34148. *
  34149. * var defaults = _.partialRight(_.assignWith, customizer);
  34150. *
  34151. * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
  34152. * // => { 'a': 1, 'b': 2 }
  34153. */
  34154. var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
  34155. copyObject(source, keys(source), object, customizer);
  34156. });
  34157. /**
  34158. * Creates an array of values corresponding to `paths` of `object`.
  34159. *
  34160. * @static
  34161. * @memberOf _
  34162. * @since 1.0.0
  34163. * @category Object
  34164. * @param {Object} object The object to iterate over.
  34165. * @param {...(string|string[])} [paths] The property paths to pick.
  34166. * @returns {Array} Returns the picked values.
  34167. * @example
  34168. *
  34169. * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
  34170. *
  34171. * _.at(object, ['a[0].b.c', 'a[1]']);
  34172. * // => [3, 4]
  34173. */
  34174. var at = flatRest(baseAt);
  34175. /**
  34176. * Creates an object that inherits from the `prototype` object. If a
  34177. * `properties` object is given, its own enumerable string keyed properties
  34178. * are assigned to the created object.
  34179. *
  34180. * @static
  34181. * @memberOf _
  34182. * @since 2.3.0
  34183. * @category Object
  34184. * @param {Object} prototype The object to inherit from.
  34185. * @param {Object} [properties] The properties to assign to the object.
  34186. * @returns {Object} Returns the new object.
  34187. * @example
  34188. *
  34189. * function Shape() {
  34190. * this.x = 0;
  34191. * this.y = 0;
  34192. * }
  34193. *
  34194. * function Circle() {
  34195. * Shape.call(this);
  34196. * }
  34197. *
  34198. * Circle.prototype = _.create(Shape.prototype, {
  34199. * 'constructor': Circle
  34200. * });
  34201. *
  34202. * var circle = new Circle;
  34203. * circle instanceof Circle;
  34204. * // => true
  34205. *
  34206. * circle instanceof Shape;
  34207. * // => true
  34208. */
  34209. function create(prototype, properties) {
  34210. var result = baseCreate(prototype);
  34211. return properties == null ? result : baseAssign(result, properties);
  34212. }
  34213. /**
  34214. * Assigns own and inherited enumerable string keyed properties of source
  34215. * objects to the destination object for all destination properties that
  34216. * resolve to `undefined`. Source objects are applied from left to right.
  34217. * Once a property is set, additional values of the same property are ignored.
  34218. *
  34219. * **Note:** This method mutates `object`.
  34220. *
  34221. * @static
  34222. * @since 0.1.0
  34223. * @memberOf _
  34224. * @category Object
  34225. * @param {Object} object The destination object.
  34226. * @param {...Object} [sources] The source objects.
  34227. * @returns {Object} Returns `object`.
  34228. * @see _.defaultsDeep
  34229. * @example
  34230. *
  34231. * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
  34232. * // => { 'a': 1, 'b': 2 }
  34233. */
  34234. var defaults = baseRest(function(args) {
  34235. args.push(undefined, customDefaultsAssignIn);
  34236. return apply(assignInWith, undefined, args);
  34237. });
  34238. /**
  34239. * This method is like `_.defaults` except that it recursively assigns
  34240. * default properties.
  34241. *
  34242. * **Note:** This method mutates `object`.
  34243. *
  34244. * @static
  34245. * @memberOf _
  34246. * @since 3.10.0
  34247. * @category Object
  34248. * @param {Object} object The destination object.
  34249. * @param {...Object} [sources] The source objects.
  34250. * @returns {Object} Returns `object`.
  34251. * @see _.defaults
  34252. * @example
  34253. *
  34254. * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
  34255. * // => { 'a': { 'b': 2, 'c': 3 } }
  34256. */
  34257. var defaultsDeep = baseRest(function(args) {
  34258. args.push(undefined, customDefaultsMerge);
  34259. return apply(mergeWith, undefined, args);
  34260. });
  34261. /**
  34262. * This method is like `_.find` except that it returns the key of the first
  34263. * element `predicate` returns truthy for instead of the element itself.
  34264. *
  34265. * @static
  34266. * @memberOf _
  34267. * @since 1.1.0
  34268. * @category Object
  34269. * @param {Object} object The object to inspect.
  34270. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  34271. * @returns {string|undefined} Returns the key of the matched element,
  34272. * else `undefined`.
  34273. * @example
  34274. *
  34275. * var users = {
  34276. * 'barney': { 'age': 36, 'active': true },
  34277. * 'fred': { 'age': 40, 'active': false },
  34278. * 'pebbles': { 'age': 1, 'active': true }
  34279. * };
  34280. *
  34281. * _.findKey(users, function(o) { return o.age < 40; });
  34282. * // => 'barney' (iteration order is not guaranteed)
  34283. *
  34284. * // The `_.matches` iteratee shorthand.
  34285. * _.findKey(users, { 'age': 1, 'active': true });
  34286. * // => 'pebbles'
  34287. *
  34288. * // The `_.matchesProperty` iteratee shorthand.
  34289. * _.findKey(users, ['active', false]);
  34290. * // => 'fred'
  34291. *
  34292. * // The `_.property` iteratee shorthand.
  34293. * _.findKey(users, 'active');
  34294. * // => 'barney'
  34295. */
  34296. function findKey(object, predicate) {
  34297. return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
  34298. }
  34299. /**
  34300. * This method is like `_.findKey` except that it iterates over elements of
  34301. * a collection in the opposite order.
  34302. *
  34303. * @static
  34304. * @memberOf _
  34305. * @since 2.0.0
  34306. * @category Object
  34307. * @param {Object} object The object to inspect.
  34308. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  34309. * @returns {string|undefined} Returns the key of the matched element,
  34310. * else `undefined`.
  34311. * @example
  34312. *
  34313. * var users = {
  34314. * 'barney': { 'age': 36, 'active': true },
  34315. * 'fred': { 'age': 40, 'active': false },
  34316. * 'pebbles': { 'age': 1, 'active': true }
  34317. * };
  34318. *
  34319. * _.findLastKey(users, function(o) { return o.age < 40; });
  34320. * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
  34321. *
  34322. * // The `_.matches` iteratee shorthand.
  34323. * _.findLastKey(users, { 'age': 36, 'active': true });
  34324. * // => 'barney'
  34325. *
  34326. * // The `_.matchesProperty` iteratee shorthand.
  34327. * _.findLastKey(users, ['active', false]);
  34328. * // => 'fred'
  34329. *
  34330. * // The `_.property` iteratee shorthand.
  34331. * _.findLastKey(users, 'active');
  34332. * // => 'pebbles'
  34333. */
  34334. function findLastKey(object, predicate) {
  34335. return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
  34336. }
  34337. /**
  34338. * Iterates over own and inherited enumerable string keyed properties of an
  34339. * object and invokes `iteratee` for each property. The iteratee is invoked
  34340. * with three arguments: (value, key, object). Iteratee functions may exit
  34341. * iteration early by explicitly returning `false`.
  34342. *
  34343. * @static
  34344. * @memberOf _
  34345. * @since 0.3.0
  34346. * @category Object
  34347. * @param {Object} object The object to iterate over.
  34348. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  34349. * @returns {Object} Returns `object`.
  34350. * @see _.forInRight
  34351. * @example
  34352. *
  34353. * function Foo() {
  34354. * this.a = 1;
  34355. * this.b = 2;
  34356. * }
  34357. *
  34358. * Foo.prototype.c = 3;
  34359. *
  34360. * _.forIn(new Foo, function(value, key) {
  34361. * console.log(key);
  34362. * });
  34363. * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
  34364. */
  34365. function forIn(object, iteratee) {
  34366. return object == null
  34367. ? object
  34368. : baseFor(object, getIteratee(iteratee, 3), keysIn);
  34369. }
  34370. /**
  34371. * This method is like `_.forIn` except that it iterates over properties of
  34372. * `object` in the opposite order.
  34373. *
  34374. * @static
  34375. * @memberOf _
  34376. * @since 2.0.0
  34377. * @category Object
  34378. * @param {Object} object The object to iterate over.
  34379. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  34380. * @returns {Object} Returns `object`.
  34381. * @see _.forIn
  34382. * @example
  34383. *
  34384. * function Foo() {
  34385. * this.a = 1;
  34386. * this.b = 2;
  34387. * }
  34388. *
  34389. * Foo.prototype.c = 3;
  34390. *
  34391. * _.forInRight(new Foo, function(value, key) {
  34392. * console.log(key);
  34393. * });
  34394. * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
  34395. */
  34396. function forInRight(object, iteratee) {
  34397. return object == null
  34398. ? object
  34399. : baseForRight(object, getIteratee(iteratee, 3), keysIn);
  34400. }
  34401. /**
  34402. * Iterates over own enumerable string keyed properties of an object and
  34403. * invokes `iteratee` for each property. The iteratee is invoked with three
  34404. * arguments: (value, key, object). Iteratee functions may exit iteration
  34405. * early by explicitly returning `false`.
  34406. *
  34407. * @static
  34408. * @memberOf _
  34409. * @since 0.3.0
  34410. * @category Object
  34411. * @param {Object} object The object to iterate over.
  34412. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  34413. * @returns {Object} Returns `object`.
  34414. * @see _.forOwnRight
  34415. * @example
  34416. *
  34417. * function Foo() {
  34418. * this.a = 1;
  34419. * this.b = 2;
  34420. * }
  34421. *
  34422. * Foo.prototype.c = 3;
  34423. *
  34424. * _.forOwn(new Foo, function(value, key) {
  34425. * console.log(key);
  34426. * });
  34427. * // => Logs 'a' then 'b' (iteration order is not guaranteed).
  34428. */
  34429. function forOwn(object, iteratee) {
  34430. return object && baseForOwn(object, getIteratee(iteratee, 3));
  34431. }
  34432. /**
  34433. * This method is like `_.forOwn` except that it iterates over properties of
  34434. * `object` in the opposite order.
  34435. *
  34436. * @static
  34437. * @memberOf _
  34438. * @since 2.0.0
  34439. * @category Object
  34440. * @param {Object} object The object to iterate over.
  34441. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  34442. * @returns {Object} Returns `object`.
  34443. * @see _.forOwn
  34444. * @example
  34445. *
  34446. * function Foo() {
  34447. * this.a = 1;
  34448. * this.b = 2;
  34449. * }
  34450. *
  34451. * Foo.prototype.c = 3;
  34452. *
  34453. * _.forOwnRight(new Foo, function(value, key) {
  34454. * console.log(key);
  34455. * });
  34456. * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
  34457. */
  34458. function forOwnRight(object, iteratee) {
  34459. return object && baseForOwnRight(object, getIteratee(iteratee, 3));
  34460. }
  34461. /**
  34462. * Creates an array of function property names from own enumerable properties
  34463. * of `object`.
  34464. *
  34465. * @static
  34466. * @since 0.1.0
  34467. * @memberOf _
  34468. * @category Object
  34469. * @param {Object} object The object to inspect.
  34470. * @returns {Array} Returns the function names.
  34471. * @see _.functionsIn
  34472. * @example
  34473. *
  34474. * function Foo() {
  34475. * this.a = _.constant('a');
  34476. * this.b = _.constant('b');
  34477. * }
  34478. *
  34479. * Foo.prototype.c = _.constant('c');
  34480. *
  34481. * _.functions(new Foo);
  34482. * // => ['a', 'b']
  34483. */
  34484. function functions(object) {
  34485. return object == null ? [] : baseFunctions(object, keys(object));
  34486. }
  34487. /**
  34488. * Creates an array of function property names from own and inherited
  34489. * enumerable properties of `object`.
  34490. *
  34491. * @static
  34492. * @memberOf _
  34493. * @since 4.0.0
  34494. * @category Object
  34495. * @param {Object} object The object to inspect.
  34496. * @returns {Array} Returns the function names.
  34497. * @see _.functions
  34498. * @example
  34499. *
  34500. * function Foo() {
  34501. * this.a = _.constant('a');
  34502. * this.b = _.constant('b');
  34503. * }
  34504. *
  34505. * Foo.prototype.c = _.constant('c');
  34506. *
  34507. * _.functionsIn(new Foo);
  34508. * // => ['a', 'b', 'c']
  34509. */
  34510. function functionsIn(object) {
  34511. return object == null ? [] : baseFunctions(object, keysIn(object));
  34512. }
  34513. /**
  34514. * Gets the value at `path` of `object`. If the resolved value is
  34515. * `undefined`, the `defaultValue` is returned in its place.
  34516. *
  34517. * @static
  34518. * @memberOf _
  34519. * @since 3.7.0
  34520. * @category Object
  34521. * @param {Object} object The object to query.
  34522. * @param {Array|string} path The path of the property to get.
  34523. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  34524. * @returns {*} Returns the resolved value.
  34525. * @example
  34526. *
  34527. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  34528. *
  34529. * _.get(object, 'a[0].b.c');
  34530. * // => 3
  34531. *
  34532. * _.get(object, ['a', '0', 'b', 'c']);
  34533. * // => 3
  34534. *
  34535. * _.get(object, 'a.b.c', 'default');
  34536. * // => 'default'
  34537. */
  34538. function get(object, path, defaultValue) {
  34539. var result = object == null ? undefined : baseGet(object, path);
  34540. return result === undefined ? defaultValue : result;
  34541. }
  34542. /**
  34543. * Checks if `path` is a direct property of `object`.
  34544. *
  34545. * @static
  34546. * @since 0.1.0
  34547. * @memberOf _
  34548. * @category Object
  34549. * @param {Object} object The object to query.
  34550. * @param {Array|string} path The path to check.
  34551. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  34552. * @example
  34553. *
  34554. * var object = { 'a': { 'b': 2 } };
  34555. * var other = _.create({ 'a': _.create({ 'b': 2 }) });
  34556. *
  34557. * _.has(object, 'a');
  34558. * // => true
  34559. *
  34560. * _.has(object, 'a.b');
  34561. * // => true
  34562. *
  34563. * _.has(object, ['a', 'b']);
  34564. * // => true
  34565. *
  34566. * _.has(other, 'a');
  34567. * // => false
  34568. */
  34569. function has(object, path) {
  34570. return object != null && hasPath(object, path, baseHas);
  34571. }
  34572. /**
  34573. * Checks if `path` is a direct or inherited property of `object`.
  34574. *
  34575. * @static
  34576. * @memberOf _
  34577. * @since 4.0.0
  34578. * @category Object
  34579. * @param {Object} object The object to query.
  34580. * @param {Array|string} path The path to check.
  34581. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  34582. * @example
  34583. *
  34584. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  34585. *
  34586. * _.hasIn(object, 'a');
  34587. * // => true
  34588. *
  34589. * _.hasIn(object, 'a.b');
  34590. * // => true
  34591. *
  34592. * _.hasIn(object, ['a', 'b']);
  34593. * // => true
  34594. *
  34595. * _.hasIn(object, 'b');
  34596. * // => false
  34597. */
  34598. function hasIn(object, path) {
  34599. return object != null && hasPath(object, path, baseHasIn);
  34600. }
  34601. /**
  34602. * Creates an object composed of the inverted keys and values of `object`.
  34603. * If `object` contains duplicate values, subsequent values overwrite
  34604. * property assignments of previous values.
  34605. *
  34606. * @static
  34607. * @memberOf _
  34608. * @since 0.7.0
  34609. * @category Object
  34610. * @param {Object} object The object to invert.
  34611. * @returns {Object} Returns the new inverted object.
  34612. * @example
  34613. *
  34614. * var object = { 'a': 1, 'b': 2, 'c': 1 };
  34615. *
  34616. * _.invert(object);
  34617. * // => { '1': 'c', '2': 'b' }
  34618. */
  34619. var invert = createInverter(function(result, value, key) {
  34620. result[value] = key;
  34621. }, constant(identity));
  34622. /**
  34623. * This method is like `_.invert` except that the inverted object is generated
  34624. * from the results of running each element of `object` thru `iteratee`. The
  34625. * corresponding inverted value of each inverted key is an array of keys
  34626. * responsible for generating the inverted value. The iteratee is invoked
  34627. * with one argument: (value).
  34628. *
  34629. * @static
  34630. * @memberOf _
  34631. * @since 4.1.0
  34632. * @category Object
  34633. * @param {Object} object The object to invert.
  34634. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  34635. * @returns {Object} Returns the new inverted object.
  34636. * @example
  34637. *
  34638. * var object = { 'a': 1, 'b': 2, 'c': 1 };
  34639. *
  34640. * _.invertBy(object);
  34641. * // => { '1': ['a', 'c'], '2': ['b'] }
  34642. *
  34643. * _.invertBy(object, function(value) {
  34644. * return 'group' + value;
  34645. * });
  34646. * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
  34647. */
  34648. var invertBy = createInverter(function(result, value, key) {
  34649. if (hasOwnProperty.call(result, value)) {
  34650. result[value].push(key);
  34651. } else {
  34652. result[value] = [key];
  34653. }
  34654. }, getIteratee);
  34655. /**
  34656. * Invokes the method at `path` of `object`.
  34657. *
  34658. * @static
  34659. * @memberOf _
  34660. * @since 4.0.0
  34661. * @category Object
  34662. * @param {Object} object The object to query.
  34663. * @param {Array|string} path The path of the method to invoke.
  34664. * @param {...*} [args] The arguments to invoke the method with.
  34665. * @returns {*} Returns the result of the invoked method.
  34666. * @example
  34667. *
  34668. * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
  34669. *
  34670. * _.invoke(object, 'a[0].b.c.slice', 1, 3);
  34671. * // => [2, 3]
  34672. */
  34673. var invoke = baseRest(baseInvoke);
  34674. /**
  34675. * Creates an array of the own enumerable property names of `object`.
  34676. *
  34677. * **Note:** Non-object values are coerced to objects. See the
  34678. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  34679. * for more details.
  34680. *
  34681. * @static
  34682. * @since 0.1.0
  34683. * @memberOf _
  34684. * @category Object
  34685. * @param {Object} object The object to query.
  34686. * @returns {Array} Returns the array of property names.
  34687. * @example
  34688. *
  34689. * function Foo() {
  34690. * this.a = 1;
  34691. * this.b = 2;
  34692. * }
  34693. *
  34694. * Foo.prototype.c = 3;
  34695. *
  34696. * _.keys(new Foo);
  34697. * // => ['a', 'b'] (iteration order is not guaranteed)
  34698. *
  34699. * _.keys('hi');
  34700. * // => ['0', '1']
  34701. */
  34702. function keys(object) {
  34703. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  34704. }
  34705. /**
  34706. * Creates an array of the own and inherited enumerable property names of `object`.
  34707. *
  34708. * **Note:** Non-object values are coerced to objects.
  34709. *
  34710. * @static
  34711. * @memberOf _
  34712. * @since 3.0.0
  34713. * @category Object
  34714. * @param {Object} object The object to query.
  34715. * @returns {Array} Returns the array of property names.
  34716. * @example
  34717. *
  34718. * function Foo() {
  34719. * this.a = 1;
  34720. * this.b = 2;
  34721. * }
  34722. *
  34723. * Foo.prototype.c = 3;
  34724. *
  34725. * _.keysIn(new Foo);
  34726. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  34727. */
  34728. function keysIn(object) {
  34729. return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
  34730. }
  34731. /**
  34732. * The opposite of `_.mapValues`; this method creates an object with the
  34733. * same values as `object` and keys generated by running each own enumerable
  34734. * string keyed property of `object` thru `iteratee`. The iteratee is invoked
  34735. * with three arguments: (value, key, object).
  34736. *
  34737. * @static
  34738. * @memberOf _
  34739. * @since 3.8.0
  34740. * @category Object
  34741. * @param {Object} object The object to iterate over.
  34742. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  34743. * @returns {Object} Returns the new mapped object.
  34744. * @see _.mapValues
  34745. * @example
  34746. *
  34747. * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
  34748. * return key + value;
  34749. * });
  34750. * // => { 'a1': 1, 'b2': 2 }
  34751. */
  34752. function mapKeys(object, iteratee) {
  34753. var result = {};
  34754. iteratee = getIteratee(iteratee, 3);
  34755. baseForOwn(object, function(value, key, object) {
  34756. baseAssignValue(result, iteratee(value, key, object), value);
  34757. });
  34758. return result;
  34759. }
  34760. /**
  34761. * Creates an object with the same keys as `object` and values generated
  34762. * by running each own enumerable string keyed property of `object` thru
  34763. * `iteratee`. The iteratee is invoked with three arguments:
  34764. * (value, key, object).
  34765. *
  34766. * @static
  34767. * @memberOf _
  34768. * @since 2.4.0
  34769. * @category Object
  34770. * @param {Object} object The object to iterate over.
  34771. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  34772. * @returns {Object} Returns the new mapped object.
  34773. * @see _.mapKeys
  34774. * @example
  34775. *
  34776. * var users = {
  34777. * 'fred': { 'user': 'fred', 'age': 40 },
  34778. * 'pebbles': { 'user': 'pebbles', 'age': 1 }
  34779. * };
  34780. *
  34781. * _.mapValues(users, function(o) { return o.age; });
  34782. * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
  34783. *
  34784. * // The `_.property` iteratee shorthand.
  34785. * _.mapValues(users, 'age');
  34786. * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
  34787. */
  34788. function mapValues(object, iteratee) {
  34789. var result = {};
  34790. iteratee = getIteratee(iteratee, 3);
  34791. baseForOwn(object, function(value, key, object) {
  34792. baseAssignValue(result, key, iteratee(value, key, object));
  34793. });
  34794. return result;
  34795. }
  34796. /**
  34797. * This method is like `_.assign` except that it recursively merges own and
  34798. * inherited enumerable string keyed properties of source objects into the
  34799. * destination object. Source properties that resolve to `undefined` are
  34800. * skipped if a destination value exists. Array and plain object properties
  34801. * are merged recursively. Other objects and value types are overridden by
  34802. * assignment. Source objects are applied from left to right. Subsequent
  34803. * sources overwrite property assignments of previous sources.
  34804. *
  34805. * **Note:** This method mutates `object`.
  34806. *
  34807. * @static
  34808. * @memberOf _
  34809. * @since 0.5.0
  34810. * @category Object
  34811. * @param {Object} object The destination object.
  34812. * @param {...Object} [sources] The source objects.
  34813. * @returns {Object} Returns `object`.
  34814. * @example
  34815. *
  34816. * var object = {
  34817. * 'a': [{ 'b': 2 }, { 'd': 4 }]
  34818. * };
  34819. *
  34820. * var other = {
  34821. * 'a': [{ 'c': 3 }, { 'e': 5 }]
  34822. * };
  34823. *
  34824. * _.merge(object, other);
  34825. * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
  34826. */
  34827. var merge = createAssigner(function(object, source, srcIndex) {
  34828. baseMerge(object, source, srcIndex);
  34829. });
  34830. /**
  34831. * This method is like `_.merge` except that it accepts `customizer` which
  34832. * is invoked to produce the merged values of the destination and source
  34833. * properties. If `customizer` returns `undefined`, merging is handled by the
  34834. * method instead. The `customizer` is invoked with six arguments:
  34835. * (objValue, srcValue, key, object, source, stack).
  34836. *
  34837. * **Note:** This method mutates `object`.
  34838. *
  34839. * @static
  34840. * @memberOf _
  34841. * @since 4.0.0
  34842. * @category Object
  34843. * @param {Object} object The destination object.
  34844. * @param {...Object} sources The source objects.
  34845. * @param {Function} customizer The function to customize assigned values.
  34846. * @returns {Object} Returns `object`.
  34847. * @example
  34848. *
  34849. * function customizer(objValue, srcValue) {
  34850. * if (_.isArray(objValue)) {
  34851. * return objValue.concat(srcValue);
  34852. * }
  34853. * }
  34854. *
  34855. * var object = { 'a': [1], 'b': [2] };
  34856. * var other = { 'a': [3], 'b': [4] };
  34857. *
  34858. * _.mergeWith(object, other, customizer);
  34859. * // => { 'a': [1, 3], 'b': [2, 4] }
  34860. */
  34861. var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
  34862. baseMerge(object, source, srcIndex, customizer);
  34863. });
  34864. /**
  34865. * The opposite of `_.pick`; this method creates an object composed of the
  34866. * own and inherited enumerable property paths of `object` that are not omitted.
  34867. *
  34868. * **Note:** This method is considerably slower than `_.pick`.
  34869. *
  34870. * @static
  34871. * @since 0.1.0
  34872. * @memberOf _
  34873. * @category Object
  34874. * @param {Object} object The source object.
  34875. * @param {...(string|string[])} [paths] The property paths to omit.
  34876. * @returns {Object} Returns the new object.
  34877. * @example
  34878. *
  34879. * var object = { 'a': 1, 'b': '2', 'c': 3 };
  34880. *
  34881. * _.omit(object, ['a', 'c']);
  34882. * // => { 'b': '2' }
  34883. */
  34884. var omit = flatRest(function(object, paths) {
  34885. var result = {};
  34886. if (object == null) {
  34887. return result;
  34888. }
  34889. var isDeep = false;
  34890. paths = arrayMap(paths, function(path) {
  34891. path = castPath(path, object);
  34892. isDeep || (isDeep = path.length > 1);
  34893. return path;
  34894. });
  34895. copyObject(object, getAllKeysIn(object), result);
  34896. if (isDeep) {
  34897. result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
  34898. }
  34899. var length = paths.length;
  34900. while (length--) {
  34901. baseUnset(result, paths[length]);
  34902. }
  34903. return result;
  34904. });
  34905. /**
  34906. * The opposite of `_.pickBy`; this method creates an object composed of
  34907. * the own and inherited enumerable string keyed properties of `object` that
  34908. * `predicate` doesn't return truthy for. The predicate is invoked with two
  34909. * arguments: (value, key).
  34910. *
  34911. * @static
  34912. * @memberOf _
  34913. * @since 4.0.0
  34914. * @category Object
  34915. * @param {Object} object The source object.
  34916. * @param {Function} [predicate=_.identity] The function invoked per property.
  34917. * @returns {Object} Returns the new object.
  34918. * @example
  34919. *
  34920. * var object = { 'a': 1, 'b': '2', 'c': 3 };
  34921. *
  34922. * _.omitBy(object, _.isNumber);
  34923. * // => { 'b': '2' }
  34924. */
  34925. function omitBy(object, predicate) {
  34926. return pickBy(object, negate(getIteratee(predicate)));
  34927. }
  34928. /**
  34929. * Creates an object composed of the picked `object` properties.
  34930. *
  34931. * @static
  34932. * @since 0.1.0
  34933. * @memberOf _
  34934. * @category Object
  34935. * @param {Object} object The source object.
  34936. * @param {...(string|string[])} [paths] The property paths to pick.
  34937. * @returns {Object} Returns the new object.
  34938. * @example
  34939. *
  34940. * var object = { 'a': 1, 'b': '2', 'c': 3 };
  34941. *
  34942. * _.pick(object, ['a', 'c']);
  34943. * // => { 'a': 1, 'c': 3 }
  34944. */
  34945. var pick = flatRest(function(object, paths) {
  34946. return object == null ? {} : basePick(object, paths);
  34947. });
  34948. /**
  34949. * Creates an object composed of the `object` properties `predicate` returns
  34950. * truthy for. The predicate is invoked with two arguments: (value, key).
  34951. *
  34952. * @static
  34953. * @memberOf _
  34954. * @since 4.0.0
  34955. * @category Object
  34956. * @param {Object} object The source object.
  34957. * @param {Function} [predicate=_.identity] The function invoked per property.
  34958. * @returns {Object} Returns the new object.
  34959. * @example
  34960. *
  34961. * var object = { 'a': 1, 'b': '2', 'c': 3 };
  34962. *
  34963. * _.pickBy(object, _.isNumber);
  34964. * // => { 'a': 1, 'c': 3 }
  34965. */
  34966. function pickBy(object, predicate) {
  34967. if (object == null) {
  34968. return {};
  34969. }
  34970. var props = arrayMap(getAllKeysIn(object), function(prop) {
  34971. return [prop];
  34972. });
  34973. predicate = getIteratee(predicate);
  34974. return basePickBy(object, props, function(value, path) {
  34975. return predicate(value, path[0]);
  34976. });
  34977. }
  34978. /**
  34979. * This method is like `_.get` except that if the resolved value is a
  34980. * function it's invoked with the `this` binding of its parent object and
  34981. * its result is returned.
  34982. *
  34983. * @static
  34984. * @since 0.1.0
  34985. * @memberOf _
  34986. * @category Object
  34987. * @param {Object} object The object to query.
  34988. * @param {Array|string} path The path of the property to resolve.
  34989. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  34990. * @returns {*} Returns the resolved value.
  34991. * @example
  34992. *
  34993. * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
  34994. *
  34995. * _.result(object, 'a[0].b.c1');
  34996. * // => 3
  34997. *
  34998. * _.result(object, 'a[0].b.c2');
  34999. * // => 4
  35000. *
  35001. * _.result(object, 'a[0].b.c3', 'default');
  35002. * // => 'default'
  35003. *
  35004. * _.result(object, 'a[0].b.c3', _.constant('default'));
  35005. * // => 'default'
  35006. */
  35007. function result(object, path, defaultValue) {
  35008. path = castPath(path, object);
  35009. var index = -1,
  35010. length = path.length;
  35011. // Ensure the loop is entered when path is empty.
  35012. if (!length) {
  35013. length = 1;
  35014. object = undefined;
  35015. }
  35016. while (++index < length) {
  35017. var value = object == null ? undefined : object[toKey(path[index])];
  35018. if (value === undefined) {
  35019. index = length;
  35020. value = defaultValue;
  35021. }
  35022. object = isFunction(value) ? value.call(object) : value;
  35023. }
  35024. return object;
  35025. }
  35026. /**
  35027. * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
  35028. * it's created. Arrays are created for missing index properties while objects
  35029. * are created for all other missing properties. Use `_.setWith` to customize
  35030. * `path` creation.
  35031. *
  35032. * **Note:** This method mutates `object`.
  35033. *
  35034. * @static
  35035. * @memberOf _
  35036. * @since 3.7.0
  35037. * @category Object
  35038. * @param {Object} object The object to modify.
  35039. * @param {Array|string} path The path of the property to set.
  35040. * @param {*} value The value to set.
  35041. * @returns {Object} Returns `object`.
  35042. * @example
  35043. *
  35044. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  35045. *
  35046. * _.set(object, 'a[0].b.c', 4);
  35047. * console.log(object.a[0].b.c);
  35048. * // => 4
  35049. *
  35050. * _.set(object, ['x', '0', 'y', 'z'], 5);
  35051. * console.log(object.x[0].y.z);
  35052. * // => 5
  35053. */
  35054. function set(object, path, value) {
  35055. return object == null ? object : baseSet(object, path, value);
  35056. }
  35057. /**
  35058. * This method is like `_.set` except that it accepts `customizer` which is
  35059. * invoked to produce the objects of `path`. If `customizer` returns `undefined`
  35060. * path creation is handled by the method instead. The `customizer` is invoked
  35061. * with three arguments: (nsValue, key, nsObject).
  35062. *
  35063. * **Note:** This method mutates `object`.
  35064. *
  35065. * @static
  35066. * @memberOf _
  35067. * @since 4.0.0
  35068. * @category Object
  35069. * @param {Object} object The object to modify.
  35070. * @param {Array|string} path The path of the property to set.
  35071. * @param {*} value The value to set.
  35072. * @param {Function} [customizer] The function to customize assigned values.
  35073. * @returns {Object} Returns `object`.
  35074. * @example
  35075. *
  35076. * var object = {};
  35077. *
  35078. * _.setWith(object, '[0][1]', 'a', Object);
  35079. * // => { '0': { '1': 'a' } }
  35080. */
  35081. function setWith(object, path, value, customizer) {
  35082. customizer = typeof customizer == 'function' ? customizer : undefined;
  35083. return object == null ? object : baseSet(object, path, value, customizer);
  35084. }
  35085. /**
  35086. * Creates an array of own enumerable string keyed-value pairs for `object`
  35087. * which can be consumed by `_.fromPairs`. If `object` is a map or set, its
  35088. * entries are returned.
  35089. *
  35090. * @static
  35091. * @memberOf _
  35092. * @since 4.0.0
  35093. * @alias entries
  35094. * @category Object
  35095. * @param {Object} object The object to query.
  35096. * @returns {Array} Returns the key-value pairs.
  35097. * @example
  35098. *
  35099. * function Foo() {
  35100. * this.a = 1;
  35101. * this.b = 2;
  35102. * }
  35103. *
  35104. * Foo.prototype.c = 3;
  35105. *
  35106. * _.toPairs(new Foo);
  35107. * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
  35108. */
  35109. var toPairs = createToPairs(keys);
  35110. /**
  35111. * Creates an array of own and inherited enumerable string keyed-value pairs
  35112. * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
  35113. * or set, its entries are returned.
  35114. *
  35115. * @static
  35116. * @memberOf _
  35117. * @since 4.0.0
  35118. * @alias entriesIn
  35119. * @category Object
  35120. * @param {Object} object The object to query.
  35121. * @returns {Array} Returns the key-value pairs.
  35122. * @example
  35123. *
  35124. * function Foo() {
  35125. * this.a = 1;
  35126. * this.b = 2;
  35127. * }
  35128. *
  35129. * Foo.prototype.c = 3;
  35130. *
  35131. * _.toPairsIn(new Foo);
  35132. * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
  35133. */
  35134. var toPairsIn = createToPairs(keysIn);
  35135. /**
  35136. * An alternative to `_.reduce`; this method transforms `object` to a new
  35137. * `accumulator` object which is the result of running each of its own
  35138. * enumerable string keyed properties thru `iteratee`, with each invocation
  35139. * potentially mutating the `accumulator` object. If `accumulator` is not
  35140. * provided, a new object with the same `[[Prototype]]` will be used. The
  35141. * iteratee is invoked with four arguments: (accumulator, value, key, object).
  35142. * Iteratee functions may exit iteration early by explicitly returning `false`.
  35143. *
  35144. * @static
  35145. * @memberOf _
  35146. * @since 1.3.0
  35147. * @category Object
  35148. * @param {Object} object The object to iterate over.
  35149. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  35150. * @param {*} [accumulator] The custom accumulator value.
  35151. * @returns {*} Returns the accumulated value.
  35152. * @example
  35153. *
  35154. * _.transform([2, 3, 4], function(result, n) {
  35155. * result.push(n *= n);
  35156. * return n % 2 == 0;
  35157. * }, []);
  35158. * // => [4, 9]
  35159. *
  35160. * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  35161. * (result[value] || (result[value] = [])).push(key);
  35162. * }, {});
  35163. * // => { '1': ['a', 'c'], '2': ['b'] }
  35164. */
  35165. function transform(object, iteratee, accumulator) {
  35166. var isArr = isArray(object),
  35167. isArrLike = isArr || isBuffer(object) || isTypedArray(object);
  35168. iteratee = getIteratee(iteratee, 4);
  35169. if (accumulator == null) {
  35170. var Ctor = object && object.constructor;
  35171. if (isArrLike) {
  35172. accumulator = isArr ? new Ctor : [];
  35173. }
  35174. else if (isObject(object)) {
  35175. accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
  35176. }
  35177. else {
  35178. accumulator = {};
  35179. }
  35180. }
  35181. (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
  35182. return iteratee(accumulator, value, index, object);
  35183. });
  35184. return accumulator;
  35185. }
  35186. /**
  35187. * Removes the property at `path` of `object`.
  35188. *
  35189. * **Note:** This method mutates `object`.
  35190. *
  35191. * @static
  35192. * @memberOf _
  35193. * @since 4.0.0
  35194. * @category Object
  35195. * @param {Object} object The object to modify.
  35196. * @param {Array|string} path The path of the property to unset.
  35197. * @returns {boolean} Returns `true` if the property is deleted, else `false`.
  35198. * @example
  35199. *
  35200. * var object = { 'a': [{ 'b': { 'c': 7 } }] };
  35201. * _.unset(object, 'a[0].b.c');
  35202. * // => true
  35203. *
  35204. * console.log(object);
  35205. * // => { 'a': [{ 'b': {} }] };
  35206. *
  35207. * _.unset(object, ['a', '0', 'b', 'c']);
  35208. * // => true
  35209. *
  35210. * console.log(object);
  35211. * // => { 'a': [{ 'b': {} }] };
  35212. */
  35213. function unset(object, path) {
  35214. return object == null ? true : baseUnset(object, path);
  35215. }
  35216. /**
  35217. * This method is like `_.set` except that accepts `updater` to produce the
  35218. * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
  35219. * is invoked with one argument: (value).
  35220. *
  35221. * **Note:** This method mutates `object`.
  35222. *
  35223. * @static
  35224. * @memberOf _
  35225. * @since 4.6.0
  35226. * @category Object
  35227. * @param {Object} object The object to modify.
  35228. * @param {Array|string} path The path of the property to set.
  35229. * @param {Function} updater The function to produce the updated value.
  35230. * @returns {Object} Returns `object`.
  35231. * @example
  35232. *
  35233. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  35234. *
  35235. * _.update(object, 'a[0].b.c', function(n) { return n * n; });
  35236. * console.log(object.a[0].b.c);
  35237. * // => 9
  35238. *
  35239. * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
  35240. * console.log(object.x[0].y.z);
  35241. * // => 0
  35242. */
  35243. function update(object, path, updater) {
  35244. return object == null ? object : baseUpdate(object, path, castFunction(updater));
  35245. }
  35246. /**
  35247. * This method is like `_.update` except that it accepts `customizer` which is
  35248. * invoked to produce the objects of `path`. If `customizer` returns `undefined`
  35249. * path creation is handled by the method instead. The `customizer` is invoked
  35250. * with three arguments: (nsValue, key, nsObject).
  35251. *
  35252. * **Note:** This method mutates `object`.
  35253. *
  35254. * @static
  35255. * @memberOf _
  35256. * @since 4.6.0
  35257. * @category Object
  35258. * @param {Object} object The object to modify.
  35259. * @param {Array|string} path The path of the property to set.
  35260. * @param {Function} updater The function to produce the updated value.
  35261. * @param {Function} [customizer] The function to customize assigned values.
  35262. * @returns {Object} Returns `object`.
  35263. * @example
  35264. *
  35265. * var object = {};
  35266. *
  35267. * _.updateWith(object, '[0][1]', _.constant('a'), Object);
  35268. * // => { '0': { '1': 'a' } }
  35269. */
  35270. function updateWith(object, path, updater, customizer) {
  35271. customizer = typeof customizer == 'function' ? customizer : undefined;
  35272. return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
  35273. }
  35274. /**
  35275. * Creates an array of the own enumerable string keyed property values of `object`.
  35276. *
  35277. * **Note:** Non-object values are coerced to objects.
  35278. *
  35279. * @static
  35280. * @since 0.1.0
  35281. * @memberOf _
  35282. * @category Object
  35283. * @param {Object} object The object to query.
  35284. * @returns {Array} Returns the array of property values.
  35285. * @example
  35286. *
  35287. * function Foo() {
  35288. * this.a = 1;
  35289. * this.b = 2;
  35290. * }
  35291. *
  35292. * Foo.prototype.c = 3;
  35293. *
  35294. * _.values(new Foo);
  35295. * // => [1, 2] (iteration order is not guaranteed)
  35296. *
  35297. * _.values('hi');
  35298. * // => ['h', 'i']
  35299. */
  35300. function values(object) {
  35301. return object == null ? [] : baseValues(object, keys(object));
  35302. }
  35303. /**
  35304. * Creates an array of the own and inherited enumerable string keyed property
  35305. * values of `object`.
  35306. *
  35307. * **Note:** Non-object values are coerced to objects.
  35308. *
  35309. * @static
  35310. * @memberOf _
  35311. * @since 3.0.0
  35312. * @category Object
  35313. * @param {Object} object The object to query.
  35314. * @returns {Array} Returns the array of property values.
  35315. * @example
  35316. *
  35317. * function Foo() {
  35318. * this.a = 1;
  35319. * this.b = 2;
  35320. * }
  35321. *
  35322. * Foo.prototype.c = 3;
  35323. *
  35324. * _.valuesIn(new Foo);
  35325. * // => [1, 2, 3] (iteration order is not guaranteed)
  35326. */
  35327. function valuesIn(object) {
  35328. return object == null ? [] : baseValues(object, keysIn(object));
  35329. }
  35330. /*------------------------------------------------------------------------*/
  35331. /**
  35332. * Clamps `number` within the inclusive `lower` and `upper` bounds.
  35333. *
  35334. * @static
  35335. * @memberOf _
  35336. * @since 4.0.0
  35337. * @category Number
  35338. * @param {number} number The number to clamp.
  35339. * @param {number} [lower] The lower bound.
  35340. * @param {number} upper The upper bound.
  35341. * @returns {number} Returns the clamped number.
  35342. * @example
  35343. *
  35344. * _.clamp(-10, -5, 5);
  35345. * // => -5
  35346. *
  35347. * _.clamp(10, -5, 5);
  35348. * // => 5
  35349. */
  35350. function clamp(number, lower, upper) {
  35351. if (upper === undefined) {
  35352. upper = lower;
  35353. lower = undefined;
  35354. }
  35355. if (upper !== undefined) {
  35356. upper = toNumber(upper);
  35357. upper = upper === upper ? upper : 0;
  35358. }
  35359. if (lower !== undefined) {
  35360. lower = toNumber(lower);
  35361. lower = lower === lower ? lower : 0;
  35362. }
  35363. return baseClamp(toNumber(number), lower, upper);
  35364. }
  35365. /**
  35366. * Checks if `n` is between `start` and up to, but not including, `end`. If
  35367. * `end` is not specified, it's set to `start` with `start` then set to `0`.
  35368. * If `start` is greater than `end` the params are swapped to support
  35369. * negative ranges.
  35370. *
  35371. * @static
  35372. * @memberOf _
  35373. * @since 3.3.0
  35374. * @category Number
  35375. * @param {number} number The number to check.
  35376. * @param {number} [start=0] The start of the range.
  35377. * @param {number} end The end of the range.
  35378. * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
  35379. * @see _.range, _.rangeRight
  35380. * @example
  35381. *
  35382. * _.inRange(3, 2, 4);
  35383. * // => true
  35384. *
  35385. * _.inRange(4, 8);
  35386. * // => true
  35387. *
  35388. * _.inRange(4, 2);
  35389. * // => false
  35390. *
  35391. * _.inRange(2, 2);
  35392. * // => false
  35393. *
  35394. * _.inRange(1.2, 2);
  35395. * // => true
  35396. *
  35397. * _.inRange(5.2, 4);
  35398. * // => false
  35399. *
  35400. * _.inRange(-3, -2, -6);
  35401. * // => true
  35402. */
  35403. function inRange(number, start, end) {
  35404. start = toFinite(start);
  35405. if (end === undefined) {
  35406. end = start;
  35407. start = 0;
  35408. } else {
  35409. end = toFinite(end);
  35410. }
  35411. number = toNumber(number);
  35412. return baseInRange(number, start, end);
  35413. }
  35414. /**
  35415. * Produces a random number between the inclusive `lower` and `upper` bounds.
  35416. * If only one argument is provided a number between `0` and the given number
  35417. * is returned. If `floating` is `true`, or either `lower` or `upper` are
  35418. * floats, a floating-point number is returned instead of an integer.
  35419. *
  35420. * **Note:** JavaScript follows the IEEE-754 standard for resolving
  35421. * floating-point values which can produce unexpected results.
  35422. *
  35423. * @static
  35424. * @memberOf _
  35425. * @since 0.7.0
  35426. * @category Number
  35427. * @param {number} [lower=0] The lower bound.
  35428. * @param {number} [upper=1] The upper bound.
  35429. * @param {boolean} [floating] Specify returning a floating-point number.
  35430. * @returns {number} Returns the random number.
  35431. * @example
  35432. *
  35433. * _.random(0, 5);
  35434. * // => an integer between 0 and 5
  35435. *
  35436. * _.random(5);
  35437. * // => also an integer between 0 and 5
  35438. *
  35439. * _.random(5, true);
  35440. * // => a floating-point number between 0 and 5
  35441. *
  35442. * _.random(1.2, 5.2);
  35443. * // => a floating-point number between 1.2 and 5.2
  35444. */
  35445. function random(lower, upper, floating) {
  35446. if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
  35447. upper = floating = undefined;
  35448. }
  35449. if (floating === undefined) {
  35450. if (typeof upper == 'boolean') {
  35451. floating = upper;
  35452. upper = undefined;
  35453. }
  35454. else if (typeof lower == 'boolean') {
  35455. floating = lower;
  35456. lower = undefined;
  35457. }
  35458. }
  35459. if (lower === undefined && upper === undefined) {
  35460. lower = 0;
  35461. upper = 1;
  35462. }
  35463. else {
  35464. lower = toFinite(lower);
  35465. if (upper === undefined) {
  35466. upper = lower;
  35467. lower = 0;
  35468. } else {
  35469. upper = toFinite(upper);
  35470. }
  35471. }
  35472. if (lower > upper) {
  35473. var temp = lower;
  35474. lower = upper;
  35475. upper = temp;
  35476. }
  35477. if (floating || lower % 1 || upper % 1) {
  35478. var rand = nativeRandom();
  35479. return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
  35480. }
  35481. return baseRandom(lower, upper);
  35482. }
  35483. /*------------------------------------------------------------------------*/
  35484. /**
  35485. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  35486. *
  35487. * @static
  35488. * @memberOf _
  35489. * @since 3.0.0
  35490. * @category String
  35491. * @param {string} [string=''] The string to convert.
  35492. * @returns {string} Returns the camel cased string.
  35493. * @example
  35494. *
  35495. * _.camelCase('Foo Bar');
  35496. * // => 'fooBar'
  35497. *
  35498. * _.camelCase('--foo-bar--');
  35499. * // => 'fooBar'
  35500. *
  35501. * _.camelCase('__FOO_BAR__');
  35502. * // => 'fooBar'
  35503. */
  35504. var camelCase = createCompounder(function(result, word, index) {
  35505. word = word.toLowerCase();
  35506. return result + (index ? capitalize(word) : word);
  35507. });
  35508. /**
  35509. * Converts the first character of `string` to upper case and the remaining
  35510. * to lower case.
  35511. *
  35512. * @static
  35513. * @memberOf _
  35514. * @since 3.0.0
  35515. * @category String
  35516. * @param {string} [string=''] The string to capitalize.
  35517. * @returns {string} Returns the capitalized string.
  35518. * @example
  35519. *
  35520. * _.capitalize('FRED');
  35521. * // => 'Fred'
  35522. */
  35523. function capitalize(string) {
  35524. return upperFirst(toString(string).toLowerCase());
  35525. }
  35526. /**
  35527. * Deburrs `string` by converting
  35528. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  35529. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  35530. * letters to basic Latin letters and removing
  35531. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  35532. *
  35533. * @static
  35534. * @memberOf _
  35535. * @since 3.0.0
  35536. * @category String
  35537. * @param {string} [string=''] The string to deburr.
  35538. * @returns {string} Returns the deburred string.
  35539. * @example
  35540. *
  35541. * _.deburr('déjà vu');
  35542. * // => 'deja vu'
  35543. */
  35544. function deburr(string) {
  35545. string = toString(string);
  35546. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  35547. }
  35548. /**
  35549. * Checks if `string` ends with the given target string.
  35550. *
  35551. * @static
  35552. * @memberOf _
  35553. * @since 3.0.0
  35554. * @category String
  35555. * @param {string} [string=''] The string to inspect.
  35556. * @param {string} [target] The string to search for.
  35557. * @param {number} [position=string.length] The position to search up to.
  35558. * @returns {boolean} Returns `true` if `string` ends with `target`,
  35559. * else `false`.
  35560. * @example
  35561. *
  35562. * _.endsWith('abc', 'c');
  35563. * // => true
  35564. *
  35565. * _.endsWith('abc', 'b');
  35566. * // => false
  35567. *
  35568. * _.endsWith('abc', 'b', 2);
  35569. * // => true
  35570. */
  35571. function endsWith(string, target, position) {
  35572. string = toString(string);
  35573. target = baseToString(target);
  35574. var length = string.length;
  35575. position = position === undefined
  35576. ? length
  35577. : baseClamp(toInteger(position), 0, length);
  35578. var end = position;
  35579. position -= target.length;
  35580. return position >= 0 && string.slice(position, end) == target;
  35581. }
  35582. /**
  35583. * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
  35584. * corresponding HTML entities.
  35585. *
  35586. * **Note:** No other characters are escaped. To escape additional
  35587. * characters use a third-party library like [_he_](https://mths.be/he).
  35588. *
  35589. * Though the ">" character is escaped for symmetry, characters like
  35590. * ">" and "/" don't need escaping in HTML and have no special meaning
  35591. * unless they're part of a tag or unquoted attribute value. See
  35592. * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
  35593. * (under "semi-related fun fact") for more details.
  35594. *
  35595. * When working with HTML you should always
  35596. * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
  35597. * XSS vectors.
  35598. *
  35599. * @static
  35600. * @since 0.1.0
  35601. * @memberOf _
  35602. * @category String
  35603. * @param {string} [string=''] The string to escape.
  35604. * @returns {string} Returns the escaped string.
  35605. * @example
  35606. *
  35607. * _.escape('fred, barney, & pebbles');
  35608. * // => 'fred, barney, &amp; pebbles'
  35609. */
  35610. function escape(string) {
  35611. string = toString(string);
  35612. return (string && reHasUnescapedHtml.test(string))
  35613. ? string.replace(reUnescapedHtml, escapeHtmlChar)
  35614. : string;
  35615. }
  35616. /**
  35617. * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
  35618. * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
  35619. *
  35620. * @static
  35621. * @memberOf _
  35622. * @since 3.0.0
  35623. * @category String
  35624. * @param {string} [string=''] The string to escape.
  35625. * @returns {string} Returns the escaped string.
  35626. * @example
  35627. *
  35628. * _.escapeRegExp('[lodash](https://lodash.com/)');
  35629. * // => '\[lodash\]\(https://lodash\.com/\)'
  35630. */
  35631. function escapeRegExp(string) {
  35632. string = toString(string);
  35633. return (string && reHasRegExpChar.test(string))
  35634. ? string.replace(reRegExpChar, '\\$&')
  35635. : string;
  35636. }
  35637. /**
  35638. * Converts `string` to
  35639. * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
  35640. *
  35641. * @static
  35642. * @memberOf _
  35643. * @since 3.0.0
  35644. * @category String
  35645. * @param {string} [string=''] The string to convert.
  35646. * @returns {string} Returns the kebab cased string.
  35647. * @example
  35648. *
  35649. * _.kebabCase('Foo Bar');
  35650. * // => 'foo-bar'
  35651. *
  35652. * _.kebabCase('fooBar');
  35653. * // => 'foo-bar'
  35654. *
  35655. * _.kebabCase('__FOO_BAR__');
  35656. * // => 'foo-bar'
  35657. */
  35658. var kebabCase = createCompounder(function(result, word, index) {
  35659. return result + (index ? '-' : '') + word.toLowerCase();
  35660. });
  35661. /**
  35662. * Converts `string`, as space separated words, to lower case.
  35663. *
  35664. * @static
  35665. * @memberOf _
  35666. * @since 4.0.0
  35667. * @category String
  35668. * @param {string} [string=''] The string to convert.
  35669. * @returns {string} Returns the lower cased string.
  35670. * @example
  35671. *
  35672. * _.lowerCase('--Foo-Bar--');
  35673. * // => 'foo bar'
  35674. *
  35675. * _.lowerCase('fooBar');
  35676. * // => 'foo bar'
  35677. *
  35678. * _.lowerCase('__FOO_BAR__');
  35679. * // => 'foo bar'
  35680. */
  35681. var lowerCase = createCompounder(function(result, word, index) {
  35682. return result + (index ? ' ' : '') + word.toLowerCase();
  35683. });
  35684. /**
  35685. * Converts the first character of `string` to lower case.
  35686. *
  35687. * @static
  35688. * @memberOf _
  35689. * @since 4.0.0
  35690. * @category String
  35691. * @param {string} [string=''] The string to convert.
  35692. * @returns {string} Returns the converted string.
  35693. * @example
  35694. *
  35695. * _.lowerFirst('Fred');
  35696. * // => 'fred'
  35697. *
  35698. * _.lowerFirst('FRED');
  35699. * // => 'fRED'
  35700. */
  35701. var lowerFirst = createCaseFirst('toLowerCase');
  35702. /**
  35703. * Pads `string` on the left and right sides if it's shorter than `length`.
  35704. * Padding characters are truncated if they can't be evenly divided by `length`.
  35705. *
  35706. * @static
  35707. * @memberOf _
  35708. * @since 3.0.0
  35709. * @category String
  35710. * @param {string} [string=''] The string to pad.
  35711. * @param {number} [length=0] The padding length.
  35712. * @param {string} [chars=' '] The string used as padding.
  35713. * @returns {string} Returns the padded string.
  35714. * @example
  35715. *
  35716. * _.pad('abc', 8);
  35717. * // => ' abc '
  35718. *
  35719. * _.pad('abc', 8, '_-');
  35720. * // => '_-abc_-_'
  35721. *
  35722. * _.pad('abc', 3);
  35723. * // => 'abc'
  35724. */
  35725. function pad(string, length, chars) {
  35726. string = toString(string);
  35727. length = toInteger(length);
  35728. var strLength = length ? stringSize(string) : 0;
  35729. if (!length || strLength >= length) {
  35730. return string;
  35731. }
  35732. var mid = (length - strLength) / 2;
  35733. return (
  35734. createPadding(nativeFloor(mid), chars) +
  35735. string +
  35736. createPadding(nativeCeil(mid), chars)
  35737. );
  35738. }
  35739. /**
  35740. * Pads `string` on the right side if it's shorter than `length`. Padding
  35741. * characters are truncated if they exceed `length`.
  35742. *
  35743. * @static
  35744. * @memberOf _
  35745. * @since 4.0.0
  35746. * @category String
  35747. * @param {string} [string=''] The string to pad.
  35748. * @param {number} [length=0] The padding length.
  35749. * @param {string} [chars=' '] The string used as padding.
  35750. * @returns {string} Returns the padded string.
  35751. * @example
  35752. *
  35753. * _.padEnd('abc', 6);
  35754. * // => 'abc '
  35755. *
  35756. * _.padEnd('abc', 6, '_-');
  35757. * // => 'abc_-_'
  35758. *
  35759. * _.padEnd('abc', 3);
  35760. * // => 'abc'
  35761. */
  35762. function padEnd(string, length, chars) {
  35763. string = toString(string);
  35764. length = toInteger(length);
  35765. var strLength = length ? stringSize(string) : 0;
  35766. return (length && strLength < length)
  35767. ? (string + createPadding(length - strLength, chars))
  35768. : string;
  35769. }
  35770. /**
  35771. * Pads `string` on the left side if it's shorter than `length`. Padding
  35772. * characters are truncated if they exceed `length`.
  35773. *
  35774. * @static
  35775. * @memberOf _
  35776. * @since 4.0.0
  35777. * @category String
  35778. * @param {string} [string=''] The string to pad.
  35779. * @param {number} [length=0] The padding length.
  35780. * @param {string} [chars=' '] The string used as padding.
  35781. * @returns {string} Returns the padded string.
  35782. * @example
  35783. *
  35784. * _.padStart('abc', 6);
  35785. * // => ' abc'
  35786. *
  35787. * _.padStart('abc', 6, '_-');
  35788. * // => '_-_abc'
  35789. *
  35790. * _.padStart('abc', 3);
  35791. * // => 'abc'
  35792. */
  35793. function padStart(string, length, chars) {
  35794. string = toString(string);
  35795. length = toInteger(length);
  35796. var strLength = length ? stringSize(string) : 0;
  35797. return (length && strLength < length)
  35798. ? (createPadding(length - strLength, chars) + string)
  35799. : string;
  35800. }
  35801. /**
  35802. * Converts `string` to an integer of the specified radix. If `radix` is
  35803. * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
  35804. * hexadecimal, in which case a `radix` of `16` is used.
  35805. *
  35806. * **Note:** This method aligns with the
  35807. * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
  35808. *
  35809. * @static
  35810. * @memberOf _
  35811. * @since 1.1.0
  35812. * @category String
  35813. * @param {string} string The string to convert.
  35814. * @param {number} [radix=10] The radix to interpret `value` by.
  35815. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  35816. * @returns {number} Returns the converted integer.
  35817. * @example
  35818. *
  35819. * _.parseInt('08');
  35820. * // => 8
  35821. *
  35822. * _.map(['6', '08', '10'], _.parseInt);
  35823. * // => [6, 8, 10]
  35824. */
  35825. function parseInt(string, radix, guard) {
  35826. if (guard || radix == null) {
  35827. radix = 0;
  35828. } else if (radix) {
  35829. radix = +radix;
  35830. }
  35831. return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
  35832. }
  35833. /**
  35834. * Repeats the given string `n` times.
  35835. *
  35836. * @static
  35837. * @memberOf _
  35838. * @since 3.0.0
  35839. * @category String
  35840. * @param {string} [string=''] The string to repeat.
  35841. * @param {number} [n=1] The number of times to repeat the string.
  35842. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  35843. * @returns {string} Returns the repeated string.
  35844. * @example
  35845. *
  35846. * _.repeat('*', 3);
  35847. * // => '***'
  35848. *
  35849. * _.repeat('abc', 2);
  35850. * // => 'abcabc'
  35851. *
  35852. * _.repeat('abc', 0);
  35853. * // => ''
  35854. */
  35855. function repeat(string, n, guard) {
  35856. if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
  35857. n = 1;
  35858. } else {
  35859. n = toInteger(n);
  35860. }
  35861. return baseRepeat(toString(string), n);
  35862. }
  35863. /**
  35864. * Replaces matches for `pattern` in `string` with `replacement`.
  35865. *
  35866. * **Note:** This method is based on
  35867. * [`String#replace`](https://mdn.io/String/replace).
  35868. *
  35869. * @static
  35870. * @memberOf _
  35871. * @since 4.0.0
  35872. * @category String
  35873. * @param {string} [string=''] The string to modify.
  35874. * @param {RegExp|string} pattern The pattern to replace.
  35875. * @param {Function|string} replacement The match replacement.
  35876. * @returns {string} Returns the modified string.
  35877. * @example
  35878. *
  35879. * _.replace('Hi Fred', 'Fred', 'Barney');
  35880. * // => 'Hi Barney'
  35881. */
  35882. function replace() {
  35883. var args = arguments,
  35884. string = toString(args[0]);
  35885. return args.length < 3 ? string : string.replace(args[1], args[2]);
  35886. }
  35887. /**
  35888. * Converts `string` to
  35889. * [snake case](https://en.wikipedia.org/wiki/Snake_case).
  35890. *
  35891. * @static
  35892. * @memberOf _
  35893. * @since 3.0.0
  35894. * @category String
  35895. * @param {string} [string=''] The string to convert.
  35896. * @returns {string} Returns the snake cased string.
  35897. * @example
  35898. *
  35899. * _.snakeCase('Foo Bar');
  35900. * // => 'foo_bar'
  35901. *
  35902. * _.snakeCase('fooBar');
  35903. * // => 'foo_bar'
  35904. *
  35905. * _.snakeCase('--FOO-BAR--');
  35906. * // => 'foo_bar'
  35907. */
  35908. var snakeCase = createCompounder(function(result, word, index) {
  35909. return result + (index ? '_' : '') + word.toLowerCase();
  35910. });
  35911. /**
  35912. * Splits `string` by `separator`.
  35913. *
  35914. * **Note:** This method is based on
  35915. * [`String#split`](https://mdn.io/String/split).
  35916. *
  35917. * @static
  35918. * @memberOf _
  35919. * @since 4.0.0
  35920. * @category String
  35921. * @param {string} [string=''] The string to split.
  35922. * @param {RegExp|string} separator The separator pattern to split by.
  35923. * @param {number} [limit] The length to truncate results to.
  35924. * @returns {Array} Returns the string segments.
  35925. * @example
  35926. *
  35927. * _.split('a-b-c', '-', 2);
  35928. * // => ['a', 'b']
  35929. */
  35930. function split(string, separator, limit) {
  35931. if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
  35932. separator = limit = undefined;
  35933. }
  35934. limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
  35935. if (!limit) {
  35936. return [];
  35937. }
  35938. string = toString(string);
  35939. if (string && (
  35940. typeof separator == 'string' ||
  35941. (separator != null && !isRegExp(separator))
  35942. )) {
  35943. separator = baseToString(separator);
  35944. if (!separator && hasUnicode(string)) {
  35945. return castSlice(stringToArray(string), 0, limit);
  35946. }
  35947. }
  35948. return string.split(separator, limit);
  35949. }
  35950. /**
  35951. * Converts `string` to
  35952. * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
  35953. *
  35954. * @static
  35955. * @memberOf _
  35956. * @since 3.1.0
  35957. * @category String
  35958. * @param {string} [string=''] The string to convert.
  35959. * @returns {string} Returns the start cased string.
  35960. * @example
  35961. *
  35962. * _.startCase('--foo-bar--');
  35963. * // => 'Foo Bar'
  35964. *
  35965. * _.startCase('fooBar');
  35966. * // => 'Foo Bar'
  35967. *
  35968. * _.startCase('__FOO_BAR__');
  35969. * // => 'FOO BAR'
  35970. */
  35971. var startCase = createCompounder(function(result, word, index) {
  35972. return result + (index ? ' ' : '') + upperFirst(word);
  35973. });
  35974. /**
  35975. * Checks if `string` starts with the given target string.
  35976. *
  35977. * @static
  35978. * @memberOf _
  35979. * @since 3.0.0
  35980. * @category String
  35981. * @param {string} [string=''] The string to inspect.
  35982. * @param {string} [target] The string to search for.
  35983. * @param {number} [position=0] The position to search from.
  35984. * @returns {boolean} Returns `true` if `string` starts with `target`,
  35985. * else `false`.
  35986. * @example
  35987. *
  35988. * _.startsWith('abc', 'a');
  35989. * // => true
  35990. *
  35991. * _.startsWith('abc', 'b');
  35992. * // => false
  35993. *
  35994. * _.startsWith('abc', 'b', 1);
  35995. * // => true
  35996. */
  35997. function startsWith(string, target, position) {
  35998. string = toString(string);
  35999. position = position == null
  36000. ? 0
  36001. : baseClamp(toInteger(position), 0, string.length);
  36002. target = baseToString(target);
  36003. return string.slice(position, position + target.length) == target;
  36004. }
  36005. /**
  36006. * Creates a compiled template function that can interpolate data properties
  36007. * in "interpolate" delimiters, HTML-escape interpolated data properties in
  36008. * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
  36009. * properties may be accessed as free variables in the template. If a setting
  36010. * object is given, it takes precedence over `_.templateSettings` values.
  36011. *
  36012. * **Note:** In the development build `_.template` utilizes
  36013. * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
  36014. * for easier debugging.
  36015. *
  36016. * For more information on precompiling templates see
  36017. * [lodash's custom builds documentation](https://lodash.com/custom-builds).
  36018. *
  36019. * For more information on Chrome extension sandboxes see
  36020. * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
  36021. *
  36022. * @static
  36023. * @since 0.1.0
  36024. * @memberOf _
  36025. * @category String
  36026. * @param {string} [string=''] The template string.
  36027. * @param {Object} [options={}] The options object.
  36028. * @param {RegExp} [options.escape=_.templateSettings.escape]
  36029. * The HTML "escape" delimiter.
  36030. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
  36031. * The "evaluate" delimiter.
  36032. * @param {Object} [options.imports=_.templateSettings.imports]
  36033. * An object to import into the template as free variables.
  36034. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
  36035. * The "interpolate" delimiter.
  36036. * @param {string} [options.sourceURL='lodash.templateSources[n]']
  36037. * The sourceURL of the compiled template.
  36038. * @param {string} [options.variable='obj']
  36039. * The data object variable name.
  36040. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  36041. * @returns {Function} Returns the compiled template function.
  36042. * @example
  36043. *
  36044. * // Use the "interpolate" delimiter to create a compiled template.
  36045. * var compiled = _.template('hello <%= user %>!');
  36046. * compiled({ 'user': 'fred' });
  36047. * // => 'hello fred!'
  36048. *
  36049. * // Use the HTML "escape" delimiter to escape data property values.
  36050. * var compiled = _.template('<b><%- value %></b>');
  36051. * compiled({ 'value': '<script>' });
  36052. * // => '<b>&lt;script&gt;</b>'
  36053. *
  36054. * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
  36055. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
  36056. * compiled({ 'users': ['fred', 'barney'] });
  36057. * // => '<li>fred</li><li>barney</li>'
  36058. *
  36059. * // Use the internal `print` function in "evaluate" delimiters.
  36060. * var compiled = _.template('<% print("hello " + user); %>!');
  36061. * compiled({ 'user': 'barney' });
  36062. * // => 'hello barney!'
  36063. *
  36064. * // Use the ES template literal delimiter as an "interpolate" delimiter.
  36065. * // Disable support by replacing the "interpolate" delimiter.
  36066. * var compiled = _.template('hello ${ user }!');
  36067. * compiled({ 'user': 'pebbles' });
  36068. * // => 'hello pebbles!'
  36069. *
  36070. * // Use backslashes to treat delimiters as plain text.
  36071. * var compiled = _.template('<%= "\\<%- value %\\>" %>');
  36072. * compiled({ 'value': 'ignored' });
  36073. * // => '<%- value %>'
  36074. *
  36075. * // Use the `imports` option to import `jQuery` as `jq`.
  36076. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
  36077. * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
  36078. * compiled({ 'users': ['fred', 'barney'] });
  36079. * // => '<li>fred</li><li>barney</li>'
  36080. *
  36081. * // Use the `sourceURL` option to specify a custom sourceURL for the template.
  36082. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
  36083. * compiled(data);
  36084. * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
  36085. *
  36086. * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
  36087. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
  36088. * compiled.source;
  36089. * // => function(data) {
  36090. * // var __t, __p = '';
  36091. * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
  36092. * // return __p;
  36093. * // }
  36094. *
  36095. * // Use custom template delimiters.
  36096. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
  36097. * var compiled = _.template('hello {{ user }}!');
  36098. * compiled({ 'user': 'mustache' });
  36099. * // => 'hello mustache!'
  36100. *
  36101. * // Use the `source` property to inline compiled templates for meaningful
  36102. * // line numbers in error messages and stack traces.
  36103. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
  36104. * var JST = {\
  36105. * "main": ' + _.template(mainText).source + '\
  36106. * };\
  36107. * ');
  36108. */
  36109. function template(string, options, guard) {
  36110. // Based on John Resig's `tmpl` implementation
  36111. // (http://ejohn.org/blog/javascript-micro-templating/)
  36112. // and Laura Doktorova's doT.js (https://github.com/olado/doT).
  36113. var settings = lodash.templateSettings;
  36114. if (guard && isIterateeCall(string, options, guard)) {
  36115. options = undefined;
  36116. }
  36117. string = toString(string);
  36118. options = assignInWith({}, options, settings, customDefaultsAssignIn);
  36119. var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
  36120. importsKeys = keys(imports),
  36121. importsValues = baseValues(imports, importsKeys);
  36122. var isEscaping,
  36123. isEvaluating,
  36124. index = 0,
  36125. interpolate = options.interpolate || reNoMatch,
  36126. source = "__p += '";
  36127. // Compile the regexp to match each delimiter.
  36128. var reDelimiters = RegExp(
  36129. (options.escape || reNoMatch).source + '|' +
  36130. interpolate.source + '|' +
  36131. (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
  36132. (options.evaluate || reNoMatch).source + '|$'
  36133. , 'g');
  36134. // Use a sourceURL for easier debugging.
  36135. var sourceURL = '//# sourceURL=' +
  36136. ('sourceURL' in options
  36137. ? options.sourceURL
  36138. : ('lodash.templateSources[' + (++templateCounter) + ']')
  36139. ) + '\n';
  36140. string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
  36141. interpolateValue || (interpolateValue = esTemplateValue);
  36142. // Escape characters that can't be included in string literals.
  36143. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
  36144. // Replace delimiters with snippets.
  36145. if (escapeValue) {
  36146. isEscaping = true;
  36147. source += "' +\n__e(" + escapeValue + ") +\n'";
  36148. }
  36149. if (evaluateValue) {
  36150. isEvaluating = true;
  36151. source += "';\n" + evaluateValue + ";\n__p += '";
  36152. }
  36153. if (interpolateValue) {
  36154. source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
  36155. }
  36156. index = offset + match.length;
  36157. // The JS engine embedded in Adobe products needs `match` returned in
  36158. // order to produce the correct `offset` value.
  36159. return match;
  36160. });
  36161. source += "';\n";
  36162. // If `variable` is not specified wrap a with-statement around the generated
  36163. // code to add the data object to the top of the scope chain.
  36164. var variable = options.variable;
  36165. if (!variable) {
  36166. source = 'with (obj) {\n' + source + '\n}\n';
  36167. }
  36168. // Cleanup code by stripping empty strings.
  36169. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
  36170. .replace(reEmptyStringMiddle, '$1')
  36171. .replace(reEmptyStringTrailing, '$1;');
  36172. // Frame code as the function body.
  36173. source = 'function(' + (variable || 'obj') + ') {\n' +
  36174. (variable
  36175. ? ''
  36176. : 'obj || (obj = {});\n'
  36177. ) +
  36178. "var __t, __p = ''" +
  36179. (isEscaping
  36180. ? ', __e = _.escape'
  36181. : ''
  36182. ) +
  36183. (isEvaluating
  36184. ? ', __j = Array.prototype.join;\n' +
  36185. "function print() { __p += __j.call(arguments, '') }\n"
  36186. : ';\n'
  36187. ) +
  36188. source +
  36189. 'return __p\n}';
  36190. var result = attempt(function() {
  36191. return Function(importsKeys, sourceURL + 'return ' + source)
  36192. .apply(undefined, importsValues);
  36193. });
  36194. // Provide the compiled function's source by its `toString` method or
  36195. // the `source` property as a convenience for inlining compiled templates.
  36196. result.source = source;
  36197. if (isError(result)) {
  36198. throw result;
  36199. }
  36200. return result;
  36201. }
  36202. /**
  36203. * Converts `string`, as a whole, to lower case just like
  36204. * [String#toLowerCase](https://mdn.io/toLowerCase).
  36205. *
  36206. * @static
  36207. * @memberOf _
  36208. * @since 4.0.0
  36209. * @category String
  36210. * @param {string} [string=''] The string to convert.
  36211. * @returns {string} Returns the lower cased string.
  36212. * @example
  36213. *
  36214. * _.toLower('--Foo-Bar--');
  36215. * // => '--foo-bar--'
  36216. *
  36217. * _.toLower('fooBar');
  36218. * // => 'foobar'
  36219. *
  36220. * _.toLower('__FOO_BAR__');
  36221. * // => '__foo_bar__'
  36222. */
  36223. function toLower(value) {
  36224. return toString(value).toLowerCase();
  36225. }
  36226. /**
  36227. * Converts `string`, as a whole, to upper case just like
  36228. * [String#toUpperCase](https://mdn.io/toUpperCase).
  36229. *
  36230. * @static
  36231. * @memberOf _
  36232. * @since 4.0.0
  36233. * @category String
  36234. * @param {string} [string=''] The string to convert.
  36235. * @returns {string} Returns the upper cased string.
  36236. * @example
  36237. *
  36238. * _.toUpper('--foo-bar--');
  36239. * // => '--FOO-BAR--'
  36240. *
  36241. * _.toUpper('fooBar');
  36242. * // => 'FOOBAR'
  36243. *
  36244. * _.toUpper('__foo_bar__');
  36245. * // => '__FOO_BAR__'
  36246. */
  36247. function toUpper(value) {
  36248. return toString(value).toUpperCase();
  36249. }
  36250. /**
  36251. * Removes leading and trailing whitespace or specified characters from `string`.
  36252. *
  36253. * @static
  36254. * @memberOf _
  36255. * @since 3.0.0
  36256. * @category String
  36257. * @param {string} [string=''] The string to trim.
  36258. * @param {string} [chars=whitespace] The characters to trim.
  36259. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  36260. * @returns {string} Returns the trimmed string.
  36261. * @example
  36262. *
  36263. * _.trim(' abc ');
  36264. * // => 'abc'
  36265. *
  36266. * _.trim('-_-abc-_-', '_-');
  36267. * // => 'abc'
  36268. *
  36269. * _.map([' foo ', ' bar '], _.trim);
  36270. * // => ['foo', 'bar']
  36271. */
  36272. function trim(string, chars, guard) {
  36273. string = toString(string);
  36274. if (string && (guard || chars === undefined)) {
  36275. return string.replace(reTrim, '');
  36276. }
  36277. if (!string || !(chars = baseToString(chars))) {
  36278. return string;
  36279. }
  36280. var strSymbols = stringToArray(string),
  36281. chrSymbols = stringToArray(chars),
  36282. start = charsStartIndex(strSymbols, chrSymbols),
  36283. end = charsEndIndex(strSymbols, chrSymbols) + 1;
  36284. return castSlice(strSymbols, start, end).join('');
  36285. }
  36286. /**
  36287. * Removes trailing whitespace or specified characters from `string`.
  36288. *
  36289. * @static
  36290. * @memberOf _
  36291. * @since 4.0.0
  36292. * @category String
  36293. * @param {string} [string=''] The string to trim.
  36294. * @param {string} [chars=whitespace] The characters to trim.
  36295. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  36296. * @returns {string} Returns the trimmed string.
  36297. * @example
  36298. *
  36299. * _.trimEnd(' abc ');
  36300. * // => ' abc'
  36301. *
  36302. * _.trimEnd('-_-abc-_-', '_-');
  36303. * // => '-_-abc'
  36304. */
  36305. function trimEnd(string, chars, guard) {
  36306. string = toString(string);
  36307. if (string && (guard || chars === undefined)) {
  36308. return string.replace(reTrimEnd, '');
  36309. }
  36310. if (!string || !(chars = baseToString(chars))) {
  36311. return string;
  36312. }
  36313. var strSymbols = stringToArray(string),
  36314. end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
  36315. return castSlice(strSymbols, 0, end).join('');
  36316. }
  36317. /**
  36318. * Removes leading whitespace or specified characters from `string`.
  36319. *
  36320. * @static
  36321. * @memberOf _
  36322. * @since 4.0.0
  36323. * @category String
  36324. * @param {string} [string=''] The string to trim.
  36325. * @param {string} [chars=whitespace] The characters to trim.
  36326. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  36327. * @returns {string} Returns the trimmed string.
  36328. * @example
  36329. *
  36330. * _.trimStart(' abc ');
  36331. * // => 'abc '
  36332. *
  36333. * _.trimStart('-_-abc-_-', '_-');
  36334. * // => 'abc-_-'
  36335. */
  36336. function trimStart(string, chars, guard) {
  36337. string = toString(string);
  36338. if (string && (guard || chars === undefined)) {
  36339. return string.replace(reTrimStart, '');
  36340. }
  36341. if (!string || !(chars = baseToString(chars))) {
  36342. return string;
  36343. }
  36344. var strSymbols = stringToArray(string),
  36345. start = charsStartIndex(strSymbols, stringToArray(chars));
  36346. return castSlice(strSymbols, start).join('');
  36347. }
  36348. /**
  36349. * Truncates `string` if it's longer than the given maximum string length.
  36350. * The last characters of the truncated string are replaced with the omission
  36351. * string which defaults to "...".
  36352. *
  36353. * @static
  36354. * @memberOf _
  36355. * @since 4.0.0
  36356. * @category String
  36357. * @param {string} [string=''] The string to truncate.
  36358. * @param {Object} [options={}] The options object.
  36359. * @param {number} [options.length=30] The maximum string length.
  36360. * @param {string} [options.omission='...'] The string to indicate text is omitted.
  36361. * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
  36362. * @returns {string} Returns the truncated string.
  36363. * @example
  36364. *
  36365. * _.truncate('hi-diddly-ho there, neighborino');
  36366. * // => 'hi-diddly-ho there, neighbo...'
  36367. *
  36368. * _.truncate('hi-diddly-ho there, neighborino', {
  36369. * 'length': 24,
  36370. * 'separator': ' '
  36371. * });
  36372. * // => 'hi-diddly-ho there,...'
  36373. *
  36374. * _.truncate('hi-diddly-ho there, neighborino', {
  36375. * 'length': 24,
  36376. * 'separator': /,? +/
  36377. * });
  36378. * // => 'hi-diddly-ho there...'
  36379. *
  36380. * _.truncate('hi-diddly-ho there, neighborino', {
  36381. * 'omission': ' [...]'
  36382. * });
  36383. * // => 'hi-diddly-ho there, neig [...]'
  36384. */
  36385. function truncate(string, options) {
  36386. var length = DEFAULT_TRUNC_LENGTH,
  36387. omission = DEFAULT_TRUNC_OMISSION;
  36388. if (isObject(options)) {
  36389. var separator = 'separator' in options ? options.separator : separator;
  36390. length = 'length' in options ? toInteger(options.length) : length;
  36391. omission = 'omission' in options ? baseToString(options.omission) : omission;
  36392. }
  36393. string = toString(string);
  36394. var strLength = string.length;
  36395. if (hasUnicode(string)) {
  36396. var strSymbols = stringToArray(string);
  36397. strLength = strSymbols.length;
  36398. }
  36399. if (length >= strLength) {
  36400. return string;
  36401. }
  36402. var end = length - stringSize(omission);
  36403. if (end < 1) {
  36404. return omission;
  36405. }
  36406. var result = strSymbols
  36407. ? castSlice(strSymbols, 0, end).join('')
  36408. : string.slice(0, end);
  36409. if (separator === undefined) {
  36410. return result + omission;
  36411. }
  36412. if (strSymbols) {
  36413. end += (result.length - end);
  36414. }
  36415. if (isRegExp(separator)) {
  36416. if (string.slice(end).search(separator)) {
  36417. var match,
  36418. substring = result;
  36419. if (!separator.global) {
  36420. separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
  36421. }
  36422. separator.lastIndex = 0;
  36423. while ((match = separator.exec(substring))) {
  36424. var newEnd = match.index;
  36425. }
  36426. result = result.slice(0, newEnd === undefined ? end : newEnd);
  36427. }
  36428. } else if (string.indexOf(baseToString(separator), end) != end) {
  36429. var index = result.lastIndexOf(separator);
  36430. if (index > -1) {
  36431. result = result.slice(0, index);
  36432. }
  36433. }
  36434. return result + omission;
  36435. }
  36436. /**
  36437. * The inverse of `_.escape`; this method converts the HTML entities
  36438. * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to
  36439. * their corresponding characters.
  36440. *
  36441. * **Note:** No other HTML entities are unescaped. To unescape additional
  36442. * HTML entities use a third-party library like [_he_](https://mths.be/he).
  36443. *
  36444. * @static
  36445. * @memberOf _
  36446. * @since 0.6.0
  36447. * @category String
  36448. * @param {string} [string=''] The string to unescape.
  36449. * @returns {string} Returns the unescaped string.
  36450. * @example
  36451. *
  36452. * _.unescape('fred, barney, &amp; pebbles');
  36453. * // => 'fred, barney, & pebbles'
  36454. */
  36455. function unescape(string) {
  36456. string = toString(string);
  36457. return (string && reHasEscapedHtml.test(string))
  36458. ? string.replace(reEscapedHtml, unescapeHtmlChar)
  36459. : string;
  36460. }
  36461. /**
  36462. * Converts `string`, as space separated words, to upper case.
  36463. *
  36464. * @static
  36465. * @memberOf _
  36466. * @since 4.0.0
  36467. * @category String
  36468. * @param {string} [string=''] The string to convert.
  36469. * @returns {string} Returns the upper cased string.
  36470. * @example
  36471. *
  36472. * _.upperCase('--foo-bar');
  36473. * // => 'FOO BAR'
  36474. *
  36475. * _.upperCase('fooBar');
  36476. * // => 'FOO BAR'
  36477. *
  36478. * _.upperCase('__foo_bar__');
  36479. * // => 'FOO BAR'
  36480. */
  36481. var upperCase = createCompounder(function(result, word, index) {
  36482. return result + (index ? ' ' : '') + word.toUpperCase();
  36483. });
  36484. /**
  36485. * Converts the first character of `string` to upper case.
  36486. *
  36487. * @static
  36488. * @memberOf _
  36489. * @since 4.0.0
  36490. * @category String
  36491. * @param {string} [string=''] The string to convert.
  36492. * @returns {string} Returns the converted string.
  36493. * @example
  36494. *
  36495. * _.upperFirst('fred');
  36496. * // => 'Fred'
  36497. *
  36498. * _.upperFirst('FRED');
  36499. * // => 'FRED'
  36500. */
  36501. var upperFirst = createCaseFirst('toUpperCase');
  36502. /**
  36503. * Splits `string` into an array of its words.
  36504. *
  36505. * @static
  36506. * @memberOf _
  36507. * @since 3.0.0
  36508. * @category String
  36509. * @param {string} [string=''] The string to inspect.
  36510. * @param {RegExp|string} [pattern] The pattern to match words.
  36511. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  36512. * @returns {Array} Returns the words of `string`.
  36513. * @example
  36514. *
  36515. * _.words('fred, barney, & pebbles');
  36516. * // => ['fred', 'barney', 'pebbles']
  36517. *
  36518. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  36519. * // => ['fred', 'barney', '&', 'pebbles']
  36520. */
  36521. function words(string, pattern, guard) {
  36522. string = toString(string);
  36523. pattern = guard ? undefined : pattern;
  36524. if (pattern === undefined) {
  36525. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  36526. }
  36527. return string.match(pattern) || [];
  36528. }
  36529. /*------------------------------------------------------------------------*/
  36530. /**
  36531. * Attempts to invoke `func`, returning either the result or the caught error
  36532. * object. Any additional arguments are provided to `func` when it's invoked.
  36533. *
  36534. * @static
  36535. * @memberOf _
  36536. * @since 3.0.0
  36537. * @category Util
  36538. * @param {Function} func The function to attempt.
  36539. * @param {...*} [args] The arguments to invoke `func` with.
  36540. * @returns {*} Returns the `func` result or error object.
  36541. * @example
  36542. *
  36543. * // Avoid throwing errors for invalid selectors.
  36544. * var elements = _.attempt(function(selector) {
  36545. * return document.querySelectorAll(selector);
  36546. * }, '>_>');
  36547. *
  36548. * if (_.isError(elements)) {
  36549. * elements = [];
  36550. * }
  36551. */
  36552. var attempt = baseRest(function(func, args) {
  36553. try {
  36554. return apply(func, undefined, args);
  36555. } catch (e) {
  36556. return isError(e) ? e : new Error(e);
  36557. }
  36558. });
  36559. /**
  36560. * Binds methods of an object to the object itself, overwriting the existing
  36561. * method.
  36562. *
  36563. * **Note:** This method doesn't set the "length" property of bound functions.
  36564. *
  36565. * @static
  36566. * @since 0.1.0
  36567. * @memberOf _
  36568. * @category Util
  36569. * @param {Object} object The object to bind and assign the bound methods to.
  36570. * @param {...(string|string[])} methodNames The object method names to bind.
  36571. * @returns {Object} Returns `object`.
  36572. * @example
  36573. *
  36574. * var view = {
  36575. * 'label': 'docs',
  36576. * 'click': function() {
  36577. * console.log('clicked ' + this.label);
  36578. * }
  36579. * };
  36580. *
  36581. * _.bindAll(view, ['click']);
  36582. * jQuery(element).on('click', view.click);
  36583. * // => Logs 'clicked docs' when clicked.
  36584. */
  36585. var bindAll = flatRest(function(object, methodNames) {
  36586. arrayEach(methodNames, function(key) {
  36587. key = toKey(key);
  36588. baseAssignValue(object, key, bind(object[key], object));
  36589. });
  36590. return object;
  36591. });
  36592. /**
  36593. * Creates a function that iterates over `pairs` and invokes the corresponding
  36594. * function of the first predicate to return truthy. The predicate-function
  36595. * pairs are invoked with the `this` binding and arguments of the created
  36596. * function.
  36597. *
  36598. * @static
  36599. * @memberOf _
  36600. * @since 4.0.0
  36601. * @category Util
  36602. * @param {Array} pairs The predicate-function pairs.
  36603. * @returns {Function} Returns the new composite function.
  36604. * @example
  36605. *
  36606. * var func = _.cond([
  36607. * [_.matches({ 'a': 1 }), _.constant('matches A')],
  36608. * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
  36609. * [_.stubTrue, _.constant('no match')]
  36610. * ]);
  36611. *
  36612. * func({ 'a': 1, 'b': 2 });
  36613. * // => 'matches A'
  36614. *
  36615. * func({ 'a': 0, 'b': 1 });
  36616. * // => 'matches B'
  36617. *
  36618. * func({ 'a': '1', 'b': '2' });
  36619. * // => 'no match'
  36620. */
  36621. function cond(pairs) {
  36622. var length = pairs == null ? 0 : pairs.length,
  36623. toIteratee = getIteratee();
  36624. pairs = !length ? [] : arrayMap(pairs, function(pair) {
  36625. if (typeof pair[1] != 'function') {
  36626. throw new TypeError(FUNC_ERROR_TEXT);
  36627. }
  36628. return [toIteratee(pair[0]), pair[1]];
  36629. });
  36630. return baseRest(function(args) {
  36631. var index = -1;
  36632. while (++index < length) {
  36633. var pair = pairs[index];
  36634. if (apply(pair[0], this, args)) {
  36635. return apply(pair[1], this, args);
  36636. }
  36637. }
  36638. });
  36639. }
  36640. /**
  36641. * Creates a function that invokes the predicate properties of `source` with
  36642. * the corresponding property values of a given object, returning `true` if
  36643. * all predicates return truthy, else `false`.
  36644. *
  36645. * **Note:** The created function is equivalent to `_.conformsTo` with
  36646. * `source` partially applied.
  36647. *
  36648. * @static
  36649. * @memberOf _
  36650. * @since 4.0.0
  36651. * @category Util
  36652. * @param {Object} source The object of property predicates to conform to.
  36653. * @returns {Function} Returns the new spec function.
  36654. * @example
  36655. *
  36656. * var objects = [
  36657. * { 'a': 2, 'b': 1 },
  36658. * { 'a': 1, 'b': 2 }
  36659. * ];
  36660. *
  36661. * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
  36662. * // => [{ 'a': 1, 'b': 2 }]
  36663. */
  36664. function conforms(source) {
  36665. return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
  36666. }
  36667. /**
  36668. * Creates a function that returns `value`.
  36669. *
  36670. * @static
  36671. * @memberOf _
  36672. * @since 2.4.0
  36673. * @category Util
  36674. * @param {*} value The value to return from the new function.
  36675. * @returns {Function} Returns the new constant function.
  36676. * @example
  36677. *
  36678. * var objects = _.times(2, _.constant({ 'a': 1 }));
  36679. *
  36680. * console.log(objects);
  36681. * // => [{ 'a': 1 }, { 'a': 1 }]
  36682. *
  36683. * console.log(objects[0] === objects[1]);
  36684. * // => true
  36685. */
  36686. function constant(value) {
  36687. return function() {
  36688. return value;
  36689. };
  36690. }
  36691. /**
  36692. * Checks `value` to determine whether a default value should be returned in
  36693. * its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
  36694. * or `undefined`.
  36695. *
  36696. * @static
  36697. * @memberOf _
  36698. * @since 4.14.0
  36699. * @category Util
  36700. * @param {*} value The value to check.
  36701. * @param {*} defaultValue The default value.
  36702. * @returns {*} Returns the resolved value.
  36703. * @example
  36704. *
  36705. * _.defaultTo(1, 10);
  36706. * // => 1
  36707. *
  36708. * _.defaultTo(undefined, 10);
  36709. * // => 10
  36710. */
  36711. function defaultTo(value, defaultValue) {
  36712. return (value == null || value !== value) ? defaultValue : value;
  36713. }
  36714. /**
  36715. * Creates a function that returns the result of invoking the given functions
  36716. * with the `this` binding of the created function, where each successive
  36717. * invocation is supplied the return value of the previous.
  36718. *
  36719. * @static
  36720. * @memberOf _
  36721. * @since 3.0.0
  36722. * @category Util
  36723. * @param {...(Function|Function[])} [funcs] The functions to invoke.
  36724. * @returns {Function} Returns the new composite function.
  36725. * @see _.flowRight
  36726. * @example
  36727. *
  36728. * function square(n) {
  36729. * return n * n;
  36730. * }
  36731. *
  36732. * var addSquare = _.flow([_.add, square]);
  36733. * addSquare(1, 2);
  36734. * // => 9
  36735. */
  36736. var flow = createFlow();
  36737. /**
  36738. * This method is like `_.flow` except that it creates a function that
  36739. * invokes the given functions from right to left.
  36740. *
  36741. * @static
  36742. * @since 3.0.0
  36743. * @memberOf _
  36744. * @category Util
  36745. * @param {...(Function|Function[])} [funcs] The functions to invoke.
  36746. * @returns {Function} Returns the new composite function.
  36747. * @see _.flow
  36748. * @example
  36749. *
  36750. * function square(n) {
  36751. * return n * n;
  36752. * }
  36753. *
  36754. * var addSquare = _.flowRight([square, _.add]);
  36755. * addSquare(1, 2);
  36756. * // => 9
  36757. */
  36758. var flowRight = createFlow(true);
  36759. /**
  36760. * This method returns the first argument it receives.
  36761. *
  36762. * @static
  36763. * @since 0.1.0
  36764. * @memberOf _
  36765. * @category Util
  36766. * @param {*} value Any value.
  36767. * @returns {*} Returns `value`.
  36768. * @example
  36769. *
  36770. * var object = { 'a': 1 };
  36771. *
  36772. * console.log(_.identity(object) === object);
  36773. * // => true
  36774. */
  36775. function identity(value) {
  36776. return value;
  36777. }
  36778. /**
  36779. * Creates a function that invokes `func` with the arguments of the created
  36780. * function. If `func` is a property name, the created function returns the
  36781. * property value for a given element. If `func` is an array or object, the
  36782. * created function returns `true` for elements that contain the equivalent
  36783. * source properties, otherwise it returns `false`.
  36784. *
  36785. * @static
  36786. * @since 4.0.0
  36787. * @memberOf _
  36788. * @category Util
  36789. * @param {*} [func=_.identity] The value to convert to a callback.
  36790. * @returns {Function} Returns the callback.
  36791. * @example
  36792. *
  36793. * var users = [
  36794. * { 'user': 'barney', 'age': 36, 'active': true },
  36795. * { 'user': 'fred', 'age': 40, 'active': false }
  36796. * ];
  36797. *
  36798. * // The `_.matches` iteratee shorthand.
  36799. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
  36800. * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
  36801. *
  36802. * // The `_.matchesProperty` iteratee shorthand.
  36803. * _.filter(users, _.iteratee(['user', 'fred']));
  36804. * // => [{ 'user': 'fred', 'age': 40 }]
  36805. *
  36806. * // The `_.property` iteratee shorthand.
  36807. * _.map(users, _.iteratee('user'));
  36808. * // => ['barney', 'fred']
  36809. *
  36810. * // Create custom iteratee shorthands.
  36811. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
  36812. * return !_.isRegExp(func) ? iteratee(func) : function(string) {
  36813. * return func.test(string);
  36814. * };
  36815. * });
  36816. *
  36817. * _.filter(['abc', 'def'], /ef/);
  36818. * // => ['def']
  36819. */
  36820. function iteratee(func) {
  36821. return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
  36822. }
  36823. /**
  36824. * Creates a function that performs a partial deep comparison between a given
  36825. * object and `source`, returning `true` if the given object has equivalent
  36826. * property values, else `false`.
  36827. *
  36828. * **Note:** The created function is equivalent to `_.isMatch` with `source`
  36829. * partially applied.
  36830. *
  36831. * Partial comparisons will match empty array and empty object `source`
  36832. * values against any array or object value, respectively. See `_.isEqual`
  36833. * for a list of supported value comparisons.
  36834. *
  36835. * @static
  36836. * @memberOf _
  36837. * @since 3.0.0
  36838. * @category Util
  36839. * @param {Object} source The object of property values to match.
  36840. * @returns {Function} Returns the new spec function.
  36841. * @example
  36842. *
  36843. * var objects = [
  36844. * { 'a': 1, 'b': 2, 'c': 3 },
  36845. * { 'a': 4, 'b': 5, 'c': 6 }
  36846. * ];
  36847. *
  36848. * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
  36849. * // => [{ 'a': 4, 'b': 5, 'c': 6 }]
  36850. */
  36851. function matches(source) {
  36852. return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
  36853. }
  36854. /**
  36855. * Creates a function that performs a partial deep comparison between the
  36856. * value at `path` of a given object to `srcValue`, returning `true` if the
  36857. * object value is equivalent, else `false`.
  36858. *
  36859. * **Note:** Partial comparisons will match empty array and empty object
  36860. * `srcValue` values against any array or object value, respectively. See
  36861. * `_.isEqual` for a list of supported value comparisons.
  36862. *
  36863. * @static
  36864. * @memberOf _
  36865. * @since 3.2.0
  36866. * @category Util
  36867. * @param {Array|string} path The path of the property to get.
  36868. * @param {*} srcValue The value to match.
  36869. * @returns {Function} Returns the new spec function.
  36870. * @example
  36871. *
  36872. * var objects = [
  36873. * { 'a': 1, 'b': 2, 'c': 3 },
  36874. * { 'a': 4, 'b': 5, 'c': 6 }
  36875. * ];
  36876. *
  36877. * _.find(objects, _.matchesProperty('a', 4));
  36878. * // => { 'a': 4, 'b': 5, 'c': 6 }
  36879. */
  36880. function matchesProperty(path, srcValue) {
  36881. return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
  36882. }
  36883. /**
  36884. * Creates a function that invokes the method at `path` of a given object.
  36885. * Any additional arguments are provided to the invoked method.
  36886. *
  36887. * @static
  36888. * @memberOf _
  36889. * @since 3.7.0
  36890. * @category Util
  36891. * @param {Array|string} path The path of the method to invoke.
  36892. * @param {...*} [args] The arguments to invoke the method with.
  36893. * @returns {Function} Returns the new invoker function.
  36894. * @example
  36895. *
  36896. * var objects = [
  36897. * { 'a': { 'b': _.constant(2) } },
  36898. * { 'a': { 'b': _.constant(1) } }
  36899. * ];
  36900. *
  36901. * _.map(objects, _.method('a.b'));
  36902. * // => [2, 1]
  36903. *
  36904. * _.map(objects, _.method(['a', 'b']));
  36905. * // => [2, 1]
  36906. */
  36907. var method = baseRest(function(path, args) {
  36908. return function(object) {
  36909. return baseInvoke(object, path, args);
  36910. };
  36911. });
  36912. /**
  36913. * The opposite of `_.method`; this method creates a function that invokes
  36914. * the method at a given path of `object`. Any additional arguments are
  36915. * provided to the invoked method.
  36916. *
  36917. * @static
  36918. * @memberOf _
  36919. * @since 3.7.0
  36920. * @category Util
  36921. * @param {Object} object The object to query.
  36922. * @param {...*} [args] The arguments to invoke the method with.
  36923. * @returns {Function} Returns the new invoker function.
  36924. * @example
  36925. *
  36926. * var array = _.times(3, _.constant),
  36927. * object = { 'a': array, 'b': array, 'c': array };
  36928. *
  36929. * _.map(['a[2]', 'c[0]'], _.methodOf(object));
  36930. * // => [2, 0]
  36931. *
  36932. * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
  36933. * // => [2, 0]
  36934. */
  36935. var methodOf = baseRest(function(object, args) {
  36936. return function(path) {
  36937. return baseInvoke(object, path, args);
  36938. };
  36939. });
  36940. /**
  36941. * Adds all own enumerable string keyed function properties of a source
  36942. * object to the destination object. If `object` is a function, then methods
  36943. * are added to its prototype as well.
  36944. *
  36945. * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
  36946. * avoid conflicts caused by modifying the original.
  36947. *
  36948. * @static
  36949. * @since 0.1.0
  36950. * @memberOf _
  36951. * @category Util
  36952. * @param {Function|Object} [object=lodash] The destination object.
  36953. * @param {Object} source The object of functions to add.
  36954. * @param {Object} [options={}] The options object.
  36955. * @param {boolean} [options.chain=true] Specify whether mixins are chainable.
  36956. * @returns {Function|Object} Returns `object`.
  36957. * @example
  36958. *
  36959. * function vowels(string) {
  36960. * return _.filter(string, function(v) {
  36961. * return /[aeiou]/i.test(v);
  36962. * });
  36963. * }
  36964. *
  36965. * _.mixin({ 'vowels': vowels });
  36966. * _.vowels('fred');
  36967. * // => ['e']
  36968. *
  36969. * _('fred').vowels().value();
  36970. * // => ['e']
  36971. *
  36972. * _.mixin({ 'vowels': vowels }, { 'chain': false });
  36973. * _('fred').vowels();
  36974. * // => ['e']
  36975. */
  36976. function mixin(object, source, options) {
  36977. var props = keys(source),
  36978. methodNames = baseFunctions(source, props);
  36979. if (options == null &&
  36980. !(isObject(source) && (methodNames.length || !props.length))) {
  36981. options = source;
  36982. source = object;
  36983. object = this;
  36984. methodNames = baseFunctions(source, keys(source));
  36985. }
  36986. var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
  36987. isFunc = isFunction(object);
  36988. arrayEach(methodNames, function(methodName) {
  36989. var func = source[methodName];
  36990. object[methodName] = func;
  36991. if (isFunc) {
  36992. object.prototype[methodName] = function() {
  36993. var chainAll = this.__chain__;
  36994. if (chain || chainAll) {
  36995. var result = object(this.__wrapped__),
  36996. actions = result.__actions__ = copyArray(this.__actions__);
  36997. actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
  36998. result.__chain__ = chainAll;
  36999. return result;
  37000. }
  37001. return func.apply(object, arrayPush([this.value()], arguments));
  37002. };
  37003. }
  37004. });
  37005. return object;
  37006. }
  37007. /**
  37008. * Reverts the `_` variable to its previous value and returns a reference to
  37009. * the `lodash` function.
  37010. *
  37011. * @static
  37012. * @since 0.1.0
  37013. * @memberOf _
  37014. * @category Util
  37015. * @returns {Function} Returns the `lodash` function.
  37016. * @example
  37017. *
  37018. * var lodash = _.noConflict();
  37019. */
  37020. function noConflict() {
  37021. if (root._ === this) {
  37022. root._ = oldDash;
  37023. }
  37024. return this;
  37025. }
  37026. /**
  37027. * This method returns `undefined`.
  37028. *
  37029. * @static
  37030. * @memberOf _
  37031. * @since 2.3.0
  37032. * @category Util
  37033. * @example
  37034. *
  37035. * _.times(2, _.noop);
  37036. * // => [undefined, undefined]
  37037. */
  37038. function noop() {
  37039. // No operation performed.
  37040. }
  37041. /**
  37042. * Creates a function that gets the argument at index `n`. If `n` is negative,
  37043. * the nth argument from the end is returned.
  37044. *
  37045. * @static
  37046. * @memberOf _
  37047. * @since 4.0.0
  37048. * @category Util
  37049. * @param {number} [n=0] The index of the argument to return.
  37050. * @returns {Function} Returns the new pass-thru function.
  37051. * @example
  37052. *
  37053. * var func = _.nthArg(1);
  37054. * func('a', 'b', 'c', 'd');
  37055. * // => 'b'
  37056. *
  37057. * var func = _.nthArg(-2);
  37058. * func('a', 'b', 'c', 'd');
  37059. * // => 'c'
  37060. */
  37061. function nthArg(n) {
  37062. n = toInteger(n);
  37063. return baseRest(function(args) {
  37064. return baseNth(args, n);
  37065. });
  37066. }
  37067. /**
  37068. * Creates a function that invokes `iteratees` with the arguments it receives
  37069. * and returns their results.
  37070. *
  37071. * @static
  37072. * @memberOf _
  37073. * @since 4.0.0
  37074. * @category Util
  37075. * @param {...(Function|Function[])} [iteratees=[_.identity]]
  37076. * The iteratees to invoke.
  37077. * @returns {Function} Returns the new function.
  37078. * @example
  37079. *
  37080. * var func = _.over([Math.max, Math.min]);
  37081. *
  37082. * func(1, 2, 3, 4);
  37083. * // => [4, 1]
  37084. */
  37085. var over = createOver(arrayMap);
  37086. /**
  37087. * Creates a function that checks if **all** of the `predicates` return
  37088. * truthy when invoked with the arguments it receives.
  37089. *
  37090. * @static
  37091. * @memberOf _
  37092. * @since 4.0.0
  37093. * @category Util
  37094. * @param {...(Function|Function[])} [predicates=[_.identity]]
  37095. * The predicates to check.
  37096. * @returns {Function} Returns the new function.
  37097. * @example
  37098. *
  37099. * var func = _.overEvery([Boolean, isFinite]);
  37100. *
  37101. * func('1');
  37102. * // => true
  37103. *
  37104. * func(null);
  37105. * // => false
  37106. *
  37107. * func(NaN);
  37108. * // => false
  37109. */
  37110. var overEvery = createOver(arrayEvery);
  37111. /**
  37112. * Creates a function that checks if **any** of the `predicates` return
  37113. * truthy when invoked with the arguments it receives.
  37114. *
  37115. * @static
  37116. * @memberOf _
  37117. * @since 4.0.0
  37118. * @category Util
  37119. * @param {...(Function|Function[])} [predicates=[_.identity]]
  37120. * The predicates to check.
  37121. * @returns {Function} Returns the new function.
  37122. * @example
  37123. *
  37124. * var func = _.overSome([Boolean, isFinite]);
  37125. *
  37126. * func('1');
  37127. * // => true
  37128. *
  37129. * func(null);
  37130. * // => true
  37131. *
  37132. * func(NaN);
  37133. * // => false
  37134. */
  37135. var overSome = createOver(arraySome);
  37136. /**
  37137. * Creates a function that returns the value at `path` of a given object.
  37138. *
  37139. * @static
  37140. * @memberOf _
  37141. * @since 2.4.0
  37142. * @category Util
  37143. * @param {Array|string} path The path of the property to get.
  37144. * @returns {Function} Returns the new accessor function.
  37145. * @example
  37146. *
  37147. * var objects = [
  37148. * { 'a': { 'b': 2 } },
  37149. * { 'a': { 'b': 1 } }
  37150. * ];
  37151. *
  37152. * _.map(objects, _.property('a.b'));
  37153. * // => [2, 1]
  37154. *
  37155. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  37156. * // => [1, 2]
  37157. */
  37158. function property(path) {
  37159. return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
  37160. }
  37161. /**
  37162. * The opposite of `_.property`; this method creates a function that returns
  37163. * the value at a given path of `object`.
  37164. *
  37165. * @static
  37166. * @memberOf _
  37167. * @since 3.0.0
  37168. * @category Util
  37169. * @param {Object} object The object to query.
  37170. * @returns {Function} Returns the new accessor function.
  37171. * @example
  37172. *
  37173. * var array = [0, 1, 2],
  37174. * object = { 'a': array, 'b': array, 'c': array };
  37175. *
  37176. * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
  37177. * // => [2, 0]
  37178. *
  37179. * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
  37180. * // => [2, 0]
  37181. */
  37182. function propertyOf(object) {
  37183. return function(path) {
  37184. return object == null ? undefined : baseGet(object, path);
  37185. };
  37186. }
  37187. /**
  37188. * Creates an array of numbers (positive and/or negative) progressing from
  37189. * `start` up to, but not including, `end`. A step of `-1` is used if a negative
  37190. * `start` is specified without an `end` or `step`. If `end` is not specified,
  37191. * it's set to `start` with `start` then set to `0`.
  37192. *
  37193. * **Note:** JavaScript follows the IEEE-754 standard for resolving
  37194. * floating-point values which can produce unexpected results.
  37195. *
  37196. * @static
  37197. * @since 0.1.0
  37198. * @memberOf _
  37199. * @category Util
  37200. * @param {number} [start=0] The start of the range.
  37201. * @param {number} end The end of the range.
  37202. * @param {number} [step=1] The value to increment or decrement by.
  37203. * @returns {Array} Returns the range of numbers.
  37204. * @see _.inRange, _.rangeRight
  37205. * @example
  37206. *
  37207. * _.range(4);
  37208. * // => [0, 1, 2, 3]
  37209. *
  37210. * _.range(-4);
  37211. * // => [0, -1, -2, -3]
  37212. *
  37213. * _.range(1, 5);
  37214. * // => [1, 2, 3, 4]
  37215. *
  37216. * _.range(0, 20, 5);
  37217. * // => [0, 5, 10, 15]
  37218. *
  37219. * _.range(0, -4, -1);
  37220. * // => [0, -1, -2, -3]
  37221. *
  37222. * _.range(1, 4, 0);
  37223. * // => [1, 1, 1]
  37224. *
  37225. * _.range(0);
  37226. * // => []
  37227. */
  37228. var range = createRange();
  37229. /**
  37230. * This method is like `_.range` except that it populates values in
  37231. * descending order.
  37232. *
  37233. * @static
  37234. * @memberOf _
  37235. * @since 4.0.0
  37236. * @category Util
  37237. * @param {number} [start=0] The start of the range.
  37238. * @param {number} end The end of the range.
  37239. * @param {number} [step=1] The value to increment or decrement by.
  37240. * @returns {Array} Returns the range of numbers.
  37241. * @see _.inRange, _.range
  37242. * @example
  37243. *
  37244. * _.rangeRight(4);
  37245. * // => [3, 2, 1, 0]
  37246. *
  37247. * _.rangeRight(-4);
  37248. * // => [-3, -2, -1, 0]
  37249. *
  37250. * _.rangeRight(1, 5);
  37251. * // => [4, 3, 2, 1]
  37252. *
  37253. * _.rangeRight(0, 20, 5);
  37254. * // => [15, 10, 5, 0]
  37255. *
  37256. * _.rangeRight(0, -4, -1);
  37257. * // => [-3, -2, -1, 0]
  37258. *
  37259. * _.rangeRight(1, 4, 0);
  37260. * // => [1, 1, 1]
  37261. *
  37262. * _.rangeRight(0);
  37263. * // => []
  37264. */
  37265. var rangeRight = createRange(true);
  37266. /**
  37267. * This method returns a new empty array.
  37268. *
  37269. * @static
  37270. * @memberOf _
  37271. * @since 4.13.0
  37272. * @category Util
  37273. * @returns {Array} Returns the new empty array.
  37274. * @example
  37275. *
  37276. * var arrays = _.times(2, _.stubArray);
  37277. *
  37278. * console.log(arrays);
  37279. * // => [[], []]
  37280. *
  37281. * console.log(arrays[0] === arrays[1]);
  37282. * // => false
  37283. */
  37284. function stubArray() {
  37285. return [];
  37286. }
  37287. /**
  37288. * This method returns `false`.
  37289. *
  37290. * @static
  37291. * @memberOf _
  37292. * @since 4.13.0
  37293. * @category Util
  37294. * @returns {boolean} Returns `false`.
  37295. * @example
  37296. *
  37297. * _.times(2, _.stubFalse);
  37298. * // => [false, false]
  37299. */
  37300. function stubFalse() {
  37301. return false;
  37302. }
  37303. /**
  37304. * This method returns a new empty object.
  37305. *
  37306. * @static
  37307. * @memberOf _
  37308. * @since 4.13.0
  37309. * @category Util
  37310. * @returns {Object} Returns the new empty object.
  37311. * @example
  37312. *
  37313. * var objects = _.times(2, _.stubObject);
  37314. *
  37315. * console.log(objects);
  37316. * // => [{}, {}]
  37317. *
  37318. * console.log(objects[0] === objects[1]);
  37319. * // => false
  37320. */
  37321. function stubObject() {
  37322. return {};
  37323. }
  37324. /**
  37325. * This method returns an empty string.
  37326. *
  37327. * @static
  37328. * @memberOf _
  37329. * @since 4.13.0
  37330. * @category Util
  37331. * @returns {string} Returns the empty string.
  37332. * @example
  37333. *
  37334. * _.times(2, _.stubString);
  37335. * // => ['', '']
  37336. */
  37337. function stubString() {
  37338. return '';
  37339. }
  37340. /**
  37341. * This method returns `true`.
  37342. *
  37343. * @static
  37344. * @memberOf _
  37345. * @since 4.13.0
  37346. * @category Util
  37347. * @returns {boolean} Returns `true`.
  37348. * @example
  37349. *
  37350. * _.times(2, _.stubTrue);
  37351. * // => [true, true]
  37352. */
  37353. function stubTrue() {
  37354. return true;
  37355. }
  37356. /**
  37357. * Invokes the iteratee `n` times, returning an array of the results of
  37358. * each invocation. The iteratee is invoked with one argument; (index).
  37359. *
  37360. * @static
  37361. * @since 0.1.0
  37362. * @memberOf _
  37363. * @category Util
  37364. * @param {number} n The number of times to invoke `iteratee`.
  37365. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  37366. * @returns {Array} Returns the array of results.
  37367. * @example
  37368. *
  37369. * _.times(3, String);
  37370. * // => ['0', '1', '2']
  37371. *
  37372. * _.times(4, _.constant(0));
  37373. * // => [0, 0, 0, 0]
  37374. */
  37375. function times(n, iteratee) {
  37376. n = toInteger(n);
  37377. if (n < 1 || n > MAX_SAFE_INTEGER) {
  37378. return [];
  37379. }
  37380. var index = MAX_ARRAY_LENGTH,
  37381. length = nativeMin(n, MAX_ARRAY_LENGTH);
  37382. iteratee = getIteratee(iteratee);
  37383. n -= MAX_ARRAY_LENGTH;
  37384. var result = baseTimes(length, iteratee);
  37385. while (++index < n) {
  37386. iteratee(index);
  37387. }
  37388. return result;
  37389. }
  37390. /**
  37391. * Converts `value` to a property path array.
  37392. *
  37393. * @static
  37394. * @memberOf _
  37395. * @since 4.0.0
  37396. * @category Util
  37397. * @param {*} value The value to convert.
  37398. * @returns {Array} Returns the new property path array.
  37399. * @example
  37400. *
  37401. * _.toPath('a.b.c');
  37402. * // => ['a', 'b', 'c']
  37403. *
  37404. * _.toPath('a[0].b.c');
  37405. * // => ['a', '0', 'b', 'c']
  37406. */
  37407. function toPath(value) {
  37408. if (isArray(value)) {
  37409. return arrayMap(value, toKey);
  37410. }
  37411. return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
  37412. }
  37413. /**
  37414. * Generates a unique ID. If `prefix` is given, the ID is appended to it.
  37415. *
  37416. * @static
  37417. * @since 0.1.0
  37418. * @memberOf _
  37419. * @category Util
  37420. * @param {string} [prefix=''] The value to prefix the ID with.
  37421. * @returns {string} Returns the unique ID.
  37422. * @example
  37423. *
  37424. * _.uniqueId('contact_');
  37425. * // => 'contact_104'
  37426. *
  37427. * _.uniqueId();
  37428. * // => '105'
  37429. */
  37430. function uniqueId(prefix) {
  37431. var id = ++idCounter;
  37432. return toString(prefix) + id;
  37433. }
  37434. /*------------------------------------------------------------------------*/
  37435. /**
  37436. * Adds two numbers.
  37437. *
  37438. * @static
  37439. * @memberOf _
  37440. * @since 3.4.0
  37441. * @category Math
  37442. * @param {number} augend The first number in an addition.
  37443. * @param {number} addend The second number in an addition.
  37444. * @returns {number} Returns the total.
  37445. * @example
  37446. *
  37447. * _.add(6, 4);
  37448. * // => 10
  37449. */
  37450. var add = createMathOperation(function(augend, addend) {
  37451. return augend + addend;
  37452. }, 0);
  37453. /**
  37454. * Computes `number` rounded up to `precision`.
  37455. *
  37456. * @static
  37457. * @memberOf _
  37458. * @since 3.10.0
  37459. * @category Math
  37460. * @param {number} number The number to round up.
  37461. * @param {number} [precision=0] The precision to round up to.
  37462. * @returns {number} Returns the rounded up number.
  37463. * @example
  37464. *
  37465. * _.ceil(4.006);
  37466. * // => 5
  37467. *
  37468. * _.ceil(6.004, 2);
  37469. * // => 6.01
  37470. *
  37471. * _.ceil(6040, -2);
  37472. * // => 6100
  37473. */
  37474. var ceil = createRound('ceil');
  37475. /**
  37476. * Divide two numbers.
  37477. *
  37478. * @static
  37479. * @memberOf _
  37480. * @since 4.7.0
  37481. * @category Math
  37482. * @param {number} dividend The first number in a division.
  37483. * @param {number} divisor The second number in a division.
  37484. * @returns {number} Returns the quotient.
  37485. * @example
  37486. *
  37487. * _.divide(6, 4);
  37488. * // => 1.5
  37489. */
  37490. var divide = createMathOperation(function(dividend, divisor) {
  37491. return dividend / divisor;
  37492. }, 1);
  37493. /**
  37494. * Computes `number` rounded down to `precision`.
  37495. *
  37496. * @static
  37497. * @memberOf _
  37498. * @since 3.10.0
  37499. * @category Math
  37500. * @param {number} number The number to round down.
  37501. * @param {number} [precision=0] The precision to round down to.
  37502. * @returns {number} Returns the rounded down number.
  37503. * @example
  37504. *
  37505. * _.floor(4.006);
  37506. * // => 4
  37507. *
  37508. * _.floor(0.046, 2);
  37509. * // => 0.04
  37510. *
  37511. * _.floor(4060, -2);
  37512. * // => 4000
  37513. */
  37514. var floor = createRound('floor');
  37515. /**
  37516. * Computes the maximum value of `array`. If `array` is empty or falsey,
  37517. * `undefined` is returned.
  37518. *
  37519. * @static
  37520. * @since 0.1.0
  37521. * @memberOf _
  37522. * @category Math
  37523. * @param {Array} array The array to iterate over.
  37524. * @returns {*} Returns the maximum value.
  37525. * @example
  37526. *
  37527. * _.max([4, 2, 8, 6]);
  37528. * // => 8
  37529. *
  37530. * _.max([]);
  37531. * // => undefined
  37532. */
  37533. function max(array) {
  37534. return (array && array.length)
  37535. ? baseExtremum(array, identity, baseGt)
  37536. : undefined;
  37537. }
  37538. /**
  37539. * This method is like `_.max` except that it accepts `iteratee` which is
  37540. * invoked for each element in `array` to generate the criterion by which
  37541. * the value is ranked. The iteratee is invoked with one argument: (value).
  37542. *
  37543. * @static
  37544. * @memberOf _
  37545. * @since 4.0.0
  37546. * @category Math
  37547. * @param {Array} array The array to iterate over.
  37548. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  37549. * @returns {*} Returns the maximum value.
  37550. * @example
  37551. *
  37552. * var objects = [{ 'n': 1 }, { 'n': 2 }];
  37553. *
  37554. * _.maxBy(objects, function(o) { return o.n; });
  37555. * // => { 'n': 2 }
  37556. *
  37557. * // The `_.property` iteratee shorthand.
  37558. * _.maxBy(objects, 'n');
  37559. * // => { 'n': 2 }
  37560. */
  37561. function maxBy(array, iteratee) {
  37562. return (array && array.length)
  37563. ? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
  37564. : undefined;
  37565. }
  37566. /**
  37567. * Computes the mean of the values in `array`.
  37568. *
  37569. * @static
  37570. * @memberOf _
  37571. * @since 4.0.0
  37572. * @category Math
  37573. * @param {Array} array The array to iterate over.
  37574. * @returns {number} Returns the mean.
  37575. * @example
  37576. *
  37577. * _.mean([4, 2, 8, 6]);
  37578. * // => 5
  37579. */
  37580. function mean(array) {
  37581. return baseMean(array, identity);
  37582. }
  37583. /**
  37584. * This method is like `_.mean` except that it accepts `iteratee` which is
  37585. * invoked for each element in `array` to generate the value to be averaged.
  37586. * The iteratee is invoked with one argument: (value).
  37587. *
  37588. * @static
  37589. * @memberOf _
  37590. * @since 4.7.0
  37591. * @category Math
  37592. * @param {Array} array The array to iterate over.
  37593. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  37594. * @returns {number} Returns the mean.
  37595. * @example
  37596. *
  37597. * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
  37598. *
  37599. * _.meanBy(objects, function(o) { return o.n; });
  37600. * // => 5
  37601. *
  37602. * // The `_.property` iteratee shorthand.
  37603. * _.meanBy(objects, 'n');
  37604. * // => 5
  37605. */
  37606. function meanBy(array, iteratee) {
  37607. return baseMean(array, getIteratee(iteratee, 2));
  37608. }
  37609. /**
  37610. * Computes the minimum value of `array`. If `array` is empty or falsey,
  37611. * `undefined` is returned.
  37612. *
  37613. * @static
  37614. * @since 0.1.0
  37615. * @memberOf _
  37616. * @category Math
  37617. * @param {Array} array The array to iterate over.
  37618. * @returns {*} Returns the minimum value.
  37619. * @example
  37620. *
  37621. * _.min([4, 2, 8, 6]);
  37622. * // => 2
  37623. *
  37624. * _.min([]);
  37625. * // => undefined
  37626. */
  37627. function min(array) {
  37628. return (array && array.length)
  37629. ? baseExtremum(array, identity, baseLt)
  37630. : undefined;
  37631. }
  37632. /**
  37633. * This method is like `_.min` except that it accepts `iteratee` which is
  37634. * invoked for each element in `array` to generate the criterion by which
  37635. * the value is ranked. The iteratee is invoked with one argument: (value).
  37636. *
  37637. * @static
  37638. * @memberOf _
  37639. * @since 4.0.0
  37640. * @category Math
  37641. * @param {Array} array The array to iterate over.
  37642. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  37643. * @returns {*} Returns the minimum value.
  37644. * @example
  37645. *
  37646. * var objects = [{ 'n': 1 }, { 'n': 2 }];
  37647. *
  37648. * _.minBy(objects, function(o) { return o.n; });
  37649. * // => { 'n': 1 }
  37650. *
  37651. * // The `_.property` iteratee shorthand.
  37652. * _.minBy(objects, 'n');
  37653. * // => { 'n': 1 }
  37654. */
  37655. function minBy(array, iteratee) {
  37656. return (array && array.length)
  37657. ? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
  37658. : undefined;
  37659. }
  37660. /**
  37661. * Multiply two numbers.
  37662. *
  37663. * @static
  37664. * @memberOf _
  37665. * @since 4.7.0
  37666. * @category Math
  37667. * @param {number} multiplier The first number in a multiplication.
  37668. * @param {number} multiplicand The second number in a multiplication.
  37669. * @returns {number} Returns the product.
  37670. * @example
  37671. *
  37672. * _.multiply(6, 4);
  37673. * // => 24
  37674. */
  37675. var multiply = createMathOperation(function(multiplier, multiplicand) {
  37676. return multiplier * multiplicand;
  37677. }, 1);
  37678. /**
  37679. * Computes `number` rounded to `precision`.
  37680. *
  37681. * @static
  37682. * @memberOf _
  37683. * @since 3.10.0
  37684. * @category Math
  37685. * @param {number} number The number to round.
  37686. * @param {number} [precision=0] The precision to round to.
  37687. * @returns {number} Returns the rounded number.
  37688. * @example
  37689. *
  37690. * _.round(4.006);
  37691. * // => 4
  37692. *
  37693. * _.round(4.006, 2);
  37694. * // => 4.01
  37695. *
  37696. * _.round(4060, -2);
  37697. * // => 4100
  37698. */
  37699. var round = createRound('round');
  37700. /**
  37701. * Subtract two numbers.
  37702. *
  37703. * @static
  37704. * @memberOf _
  37705. * @since 4.0.0
  37706. * @category Math
  37707. * @param {number} minuend The first number in a subtraction.
  37708. * @param {number} subtrahend The second number in a subtraction.
  37709. * @returns {number} Returns the difference.
  37710. * @example
  37711. *
  37712. * _.subtract(6, 4);
  37713. * // => 2
  37714. */
  37715. var subtract = createMathOperation(function(minuend, subtrahend) {
  37716. return minuend - subtrahend;
  37717. }, 0);
  37718. /**
  37719. * Computes the sum of the values in `array`.
  37720. *
  37721. * @static
  37722. * @memberOf _
  37723. * @since 3.4.0
  37724. * @category Math
  37725. * @param {Array} array The array to iterate over.
  37726. * @returns {number} Returns the sum.
  37727. * @example
  37728. *
  37729. * _.sum([4, 2, 8, 6]);
  37730. * // => 20
  37731. */
  37732. function sum(array) {
  37733. return (array && array.length)
  37734. ? baseSum(array, identity)
  37735. : 0;
  37736. }
  37737. /**
  37738. * This method is like `_.sum` except that it accepts `iteratee` which is
  37739. * invoked for each element in `array` to generate the value to be summed.
  37740. * The iteratee is invoked with one argument: (value).
  37741. *
  37742. * @static
  37743. * @memberOf _
  37744. * @since 4.0.0
  37745. * @category Math
  37746. * @param {Array} array The array to iterate over.
  37747. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  37748. * @returns {number} Returns the sum.
  37749. * @example
  37750. *
  37751. * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
  37752. *
  37753. * _.sumBy(objects, function(o) { return o.n; });
  37754. * // => 20
  37755. *
  37756. * // The `_.property` iteratee shorthand.
  37757. * _.sumBy(objects, 'n');
  37758. * // => 20
  37759. */
  37760. function sumBy(array, iteratee) {
  37761. return (array && array.length)
  37762. ? baseSum(array, getIteratee(iteratee, 2))
  37763. : 0;
  37764. }
  37765. /*------------------------------------------------------------------------*/
  37766. // Add methods that return wrapped values in chain sequences.
  37767. lodash.after = after;
  37768. lodash.ary = ary;
  37769. lodash.assign = assign;
  37770. lodash.assignIn = assignIn;
  37771. lodash.assignInWith = assignInWith;
  37772. lodash.assignWith = assignWith;
  37773. lodash.at = at;
  37774. lodash.before = before;
  37775. lodash.bind = bind;
  37776. lodash.bindAll = bindAll;
  37777. lodash.bindKey = bindKey;
  37778. lodash.castArray = castArray;
  37779. lodash.chain = chain;
  37780. lodash.chunk = chunk;
  37781. lodash.compact = compact;
  37782. lodash.concat = concat;
  37783. lodash.cond = cond;
  37784. lodash.conforms = conforms;
  37785. lodash.constant = constant;
  37786. lodash.countBy = countBy;
  37787. lodash.create = create;
  37788. lodash.curry = curry;
  37789. lodash.curryRight = curryRight;
  37790. lodash.debounce = debounce;
  37791. lodash.defaults = defaults;
  37792. lodash.defaultsDeep = defaultsDeep;
  37793. lodash.defer = defer;
  37794. lodash.delay = delay;
  37795. lodash.difference = difference;
  37796. lodash.differenceBy = differenceBy;
  37797. lodash.differenceWith = differenceWith;
  37798. lodash.drop = drop;
  37799. lodash.dropRight = dropRight;
  37800. lodash.dropRightWhile = dropRightWhile;
  37801. lodash.dropWhile = dropWhile;
  37802. lodash.fill = fill;
  37803. lodash.filter = filter;
  37804. lodash.flatMap = flatMap;
  37805. lodash.flatMapDeep = flatMapDeep;
  37806. lodash.flatMapDepth = flatMapDepth;
  37807. lodash.flatten = flatten;
  37808. lodash.flattenDeep = flattenDeep;
  37809. lodash.flattenDepth = flattenDepth;
  37810. lodash.flip = flip;
  37811. lodash.flow = flow;
  37812. lodash.flowRight = flowRight;
  37813. lodash.fromPairs = fromPairs;
  37814. lodash.functions = functions;
  37815. lodash.functionsIn = functionsIn;
  37816. lodash.groupBy = groupBy;
  37817. lodash.initial = initial;
  37818. lodash.intersection = intersection;
  37819. lodash.intersectionBy = intersectionBy;
  37820. lodash.intersectionWith = intersectionWith;
  37821. lodash.invert = invert;
  37822. lodash.invertBy = invertBy;
  37823. lodash.invokeMap = invokeMap;
  37824. lodash.iteratee = iteratee;
  37825. lodash.keyBy = keyBy;
  37826. lodash.keys = keys;
  37827. lodash.keysIn = keysIn;
  37828. lodash.map = map;
  37829. lodash.mapKeys = mapKeys;
  37830. lodash.mapValues = mapValues;
  37831. lodash.matches = matches;
  37832. lodash.matchesProperty = matchesProperty;
  37833. lodash.memoize = memoize;
  37834. lodash.merge = merge;
  37835. lodash.mergeWith = mergeWith;
  37836. lodash.method = method;
  37837. lodash.methodOf = methodOf;
  37838. lodash.mixin = mixin;
  37839. lodash.negate = negate;
  37840. lodash.nthArg = nthArg;
  37841. lodash.omit = omit;
  37842. lodash.omitBy = omitBy;
  37843. lodash.once = once;
  37844. lodash.orderBy = orderBy;
  37845. lodash.over = over;
  37846. lodash.overArgs = overArgs;
  37847. lodash.overEvery = overEvery;
  37848. lodash.overSome = overSome;
  37849. lodash.partial = partial;
  37850. lodash.partialRight = partialRight;
  37851. lodash.partition = partition;
  37852. lodash.pick = pick;
  37853. lodash.pickBy = pickBy;
  37854. lodash.property = property;
  37855. lodash.propertyOf = propertyOf;
  37856. lodash.pull = pull;
  37857. lodash.pullAll = pullAll;
  37858. lodash.pullAllBy = pullAllBy;
  37859. lodash.pullAllWith = pullAllWith;
  37860. lodash.pullAt = pullAt;
  37861. lodash.range = range;
  37862. lodash.rangeRight = rangeRight;
  37863. lodash.rearg = rearg;
  37864. lodash.reject = reject;
  37865. lodash.remove = remove;
  37866. lodash.rest = rest;
  37867. lodash.reverse = reverse;
  37868. lodash.sampleSize = sampleSize;
  37869. lodash.set = set;
  37870. lodash.setWith = setWith;
  37871. lodash.shuffle = shuffle;
  37872. lodash.slice = slice;
  37873. lodash.sortBy = sortBy;
  37874. lodash.sortedUniq = sortedUniq;
  37875. lodash.sortedUniqBy = sortedUniqBy;
  37876. lodash.split = split;
  37877. lodash.spread = spread;
  37878. lodash.tail = tail;
  37879. lodash.take = take;
  37880. lodash.takeRight = takeRight;
  37881. lodash.takeRightWhile = takeRightWhile;
  37882. lodash.takeWhile = takeWhile;
  37883. lodash.tap = tap;
  37884. lodash.throttle = throttle;
  37885. lodash.thru = thru;
  37886. lodash.toArray = toArray;
  37887. lodash.toPairs = toPairs;
  37888. lodash.toPairsIn = toPairsIn;
  37889. lodash.toPath = toPath;
  37890. lodash.toPlainObject = toPlainObject;
  37891. lodash.transform = transform;
  37892. lodash.unary = unary;
  37893. lodash.union = union;
  37894. lodash.unionBy = unionBy;
  37895. lodash.unionWith = unionWith;
  37896. lodash.uniq = uniq;
  37897. lodash.uniqBy = uniqBy;
  37898. lodash.uniqWith = uniqWith;
  37899. lodash.unset = unset;
  37900. lodash.unzip = unzip;
  37901. lodash.unzipWith = unzipWith;
  37902. lodash.update = update;
  37903. lodash.updateWith = updateWith;
  37904. lodash.values = values;
  37905. lodash.valuesIn = valuesIn;
  37906. lodash.without = without;
  37907. lodash.words = words;
  37908. lodash.wrap = wrap;
  37909. lodash.xor = xor;
  37910. lodash.xorBy = xorBy;
  37911. lodash.xorWith = xorWith;
  37912. lodash.zip = zip;
  37913. lodash.zipObject = zipObject;
  37914. lodash.zipObjectDeep = zipObjectDeep;
  37915. lodash.zipWith = zipWith;
  37916. // Add aliases.
  37917. lodash.entries = toPairs;
  37918. lodash.entriesIn = toPairsIn;
  37919. lodash.extend = assignIn;
  37920. lodash.extendWith = assignInWith;
  37921. // Add methods to `lodash.prototype`.
  37922. mixin(lodash, lodash);
  37923. /*------------------------------------------------------------------------*/
  37924. // Add methods that return unwrapped values in chain sequences.
  37925. lodash.add = add;
  37926. lodash.attempt = attempt;
  37927. lodash.camelCase = camelCase;
  37928. lodash.capitalize = capitalize;
  37929. lodash.ceil = ceil;
  37930. lodash.clamp = clamp;
  37931. lodash.clone = clone;
  37932. lodash.cloneDeep = cloneDeep;
  37933. lodash.cloneDeepWith = cloneDeepWith;
  37934. lodash.cloneWith = cloneWith;
  37935. lodash.conformsTo = conformsTo;
  37936. lodash.deburr = deburr;
  37937. lodash.defaultTo = defaultTo;
  37938. lodash.divide = divide;
  37939. lodash.endsWith = endsWith;
  37940. lodash.eq = eq;
  37941. lodash.escape = escape;
  37942. lodash.escapeRegExp = escapeRegExp;
  37943. lodash.every = every;
  37944. lodash.find = find;
  37945. lodash.findIndex = findIndex;
  37946. lodash.findKey = findKey;
  37947. lodash.findLast = findLast;
  37948. lodash.findLastIndex = findLastIndex;
  37949. lodash.findLastKey = findLastKey;
  37950. lodash.floor = floor;
  37951. lodash.forEach = forEach;
  37952. lodash.forEachRight = forEachRight;
  37953. lodash.forIn = forIn;
  37954. lodash.forInRight = forInRight;
  37955. lodash.forOwn = forOwn;
  37956. lodash.forOwnRight = forOwnRight;
  37957. lodash.get = get;
  37958. lodash.gt = gt;
  37959. lodash.gte = gte;
  37960. lodash.has = has;
  37961. lodash.hasIn = hasIn;
  37962. lodash.head = head;
  37963. lodash.identity = identity;
  37964. lodash.includes = includes;
  37965. lodash.indexOf = indexOf;
  37966. lodash.inRange = inRange;
  37967. lodash.invoke = invoke;
  37968. lodash.isArguments = isArguments;
  37969. lodash.isArray = isArray;
  37970. lodash.isArrayBuffer = isArrayBuffer;
  37971. lodash.isArrayLike = isArrayLike;
  37972. lodash.isArrayLikeObject = isArrayLikeObject;
  37973. lodash.isBoolean = isBoolean;
  37974. lodash.isBuffer = isBuffer;
  37975. lodash.isDate = isDate;
  37976. lodash.isElement = isElement;
  37977. lodash.isEmpty = isEmpty;
  37978. lodash.isEqual = isEqual;
  37979. lodash.isEqualWith = isEqualWith;
  37980. lodash.isError = isError;
  37981. lodash.isFinite = isFinite;
  37982. lodash.isFunction = isFunction;
  37983. lodash.isInteger = isInteger;
  37984. lodash.isLength = isLength;
  37985. lodash.isMap = isMap;
  37986. lodash.isMatch = isMatch;
  37987. lodash.isMatchWith = isMatchWith;
  37988. lodash.isNaN = isNaN;
  37989. lodash.isNative = isNative;
  37990. lodash.isNil = isNil;
  37991. lodash.isNull = isNull;
  37992. lodash.isNumber = isNumber;
  37993. lodash.isObject = isObject;
  37994. lodash.isObjectLike = isObjectLike;
  37995. lodash.isPlainObject = isPlainObject;
  37996. lodash.isRegExp = isRegExp;
  37997. lodash.isSafeInteger = isSafeInteger;
  37998. lodash.isSet = isSet;
  37999. lodash.isString = isString;
  38000. lodash.isSymbol = isSymbol;
  38001. lodash.isTypedArray = isTypedArray;
  38002. lodash.isUndefined = isUndefined;
  38003. lodash.isWeakMap = isWeakMap;
  38004. lodash.isWeakSet = isWeakSet;
  38005. lodash.join = join;
  38006. lodash.kebabCase = kebabCase;
  38007. lodash.last = last;
  38008. lodash.lastIndexOf = lastIndexOf;
  38009. lodash.lowerCase = lowerCase;
  38010. lodash.lowerFirst = lowerFirst;
  38011. lodash.lt = lt;
  38012. lodash.lte = lte;
  38013. lodash.max = max;
  38014. lodash.maxBy = maxBy;
  38015. lodash.mean = mean;
  38016. lodash.meanBy = meanBy;
  38017. lodash.min = min;
  38018. lodash.minBy = minBy;
  38019. lodash.stubArray = stubArray;
  38020. lodash.stubFalse = stubFalse;
  38021. lodash.stubObject = stubObject;
  38022. lodash.stubString = stubString;
  38023. lodash.stubTrue = stubTrue;
  38024. lodash.multiply = multiply;
  38025. lodash.nth = nth;
  38026. lodash.noConflict = noConflict;
  38027. lodash.noop = noop;
  38028. lodash.now = now;
  38029. lodash.pad = pad;
  38030. lodash.padEnd = padEnd;
  38031. lodash.padStart = padStart;
  38032. lodash.parseInt = parseInt;
  38033. lodash.random = random;
  38034. lodash.reduce = reduce;
  38035. lodash.reduceRight = reduceRight;
  38036. lodash.repeat = repeat;
  38037. lodash.replace = replace;
  38038. lodash.result = result;
  38039. lodash.round = round;
  38040. lodash.runInContext = runInContext;
  38041. lodash.sample = sample;
  38042. lodash.size = size;
  38043. lodash.snakeCase = snakeCase;
  38044. lodash.some = some;
  38045. lodash.sortedIndex = sortedIndex;
  38046. lodash.sortedIndexBy = sortedIndexBy;
  38047. lodash.sortedIndexOf = sortedIndexOf;
  38048. lodash.sortedLastIndex = sortedLastIndex;
  38049. lodash.sortedLastIndexBy = sortedLastIndexBy;
  38050. lodash.sortedLastIndexOf = sortedLastIndexOf;
  38051. lodash.startCase = startCase;
  38052. lodash.startsWith = startsWith;
  38053. lodash.subtract = subtract;
  38054. lodash.sum = sum;
  38055. lodash.sumBy = sumBy;
  38056. lodash.template = template;
  38057. lodash.times = times;
  38058. lodash.toFinite = toFinite;
  38059. lodash.toInteger = toInteger;
  38060. lodash.toLength = toLength;
  38061. lodash.toLower = toLower;
  38062. lodash.toNumber = toNumber;
  38063. lodash.toSafeInteger = toSafeInteger;
  38064. lodash.toString = toString;
  38065. lodash.toUpper = toUpper;
  38066. lodash.trim = trim;
  38067. lodash.trimEnd = trimEnd;
  38068. lodash.trimStart = trimStart;
  38069. lodash.truncate = truncate;
  38070. lodash.unescape = unescape;
  38071. lodash.uniqueId = uniqueId;
  38072. lodash.upperCase = upperCase;
  38073. lodash.upperFirst = upperFirst;
  38074. // Add aliases.
  38075. lodash.each = forEach;
  38076. lodash.eachRight = forEachRight;
  38077. lodash.first = head;
  38078. mixin(lodash, (function() {
  38079. var source = {};
  38080. baseForOwn(lodash, function(func, methodName) {
  38081. if (!hasOwnProperty.call(lodash.prototype, methodName)) {
  38082. source[methodName] = func;
  38083. }
  38084. });
  38085. return source;
  38086. }()), { 'chain': false });
  38087. /*------------------------------------------------------------------------*/
  38088. /**
  38089. * The semantic version number.
  38090. *
  38091. * @static
  38092. * @memberOf _
  38093. * @type {string}
  38094. */
  38095. lodash.VERSION = VERSION;
  38096. // Assign default placeholders.
  38097. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
  38098. lodash[methodName].placeholder = lodash;
  38099. });
  38100. // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
  38101. arrayEach(['drop', 'take'], function(methodName, index) {
  38102. LazyWrapper.prototype[methodName] = function(n) {
  38103. n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
  38104. var result = (this.__filtered__ && !index)
  38105. ? new LazyWrapper(this)
  38106. : this.clone();
  38107. if (result.__filtered__) {
  38108. result.__takeCount__ = nativeMin(n, result.__takeCount__);
  38109. } else {
  38110. result.__views__.push({
  38111. 'size': nativeMin(n, MAX_ARRAY_LENGTH),
  38112. 'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
  38113. });
  38114. }
  38115. return result;
  38116. };
  38117. LazyWrapper.prototype[methodName + 'Right'] = function(n) {
  38118. return this.reverse()[methodName](n).reverse();
  38119. };
  38120. });
  38121. // Add `LazyWrapper` methods that accept an `iteratee` value.
  38122. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
  38123. var type = index + 1,
  38124. isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
  38125. LazyWrapper.prototype[methodName] = function(iteratee) {
  38126. var result = this.clone();
  38127. result.__iteratees__.push({
  38128. 'iteratee': getIteratee(iteratee, 3),
  38129. 'type': type
  38130. });
  38131. result.__filtered__ = result.__filtered__ || isFilter;
  38132. return result;
  38133. };
  38134. });
  38135. // Add `LazyWrapper` methods for `_.head` and `_.last`.
  38136. arrayEach(['head', 'last'], function(methodName, index) {
  38137. var takeName = 'take' + (index ? 'Right' : '');
  38138. LazyWrapper.prototype[methodName] = function() {
  38139. return this[takeName](1).value()[0];
  38140. };
  38141. });
  38142. // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
  38143. arrayEach(['initial', 'tail'], function(methodName, index) {
  38144. var dropName = 'drop' + (index ? '' : 'Right');
  38145. LazyWrapper.prototype[methodName] = function() {
  38146. return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
  38147. };
  38148. });
  38149. LazyWrapper.prototype.compact = function() {
  38150. return this.filter(identity);
  38151. };
  38152. LazyWrapper.prototype.find = function(predicate) {
  38153. return this.filter(predicate).head();
  38154. };
  38155. LazyWrapper.prototype.findLast = function(predicate) {
  38156. return this.reverse().find(predicate);
  38157. };
  38158. LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
  38159. if (typeof path == 'function') {
  38160. return new LazyWrapper(this);
  38161. }
  38162. return this.map(function(value) {
  38163. return baseInvoke(value, path, args);
  38164. });
  38165. });
  38166. LazyWrapper.prototype.reject = function(predicate) {
  38167. return this.filter(negate(getIteratee(predicate)));
  38168. };
  38169. LazyWrapper.prototype.slice = function(start, end) {
  38170. start = toInteger(start);
  38171. var result = this;
  38172. if (result.__filtered__ && (start > 0 || end < 0)) {
  38173. return new LazyWrapper(result);
  38174. }
  38175. if (start < 0) {
  38176. result = result.takeRight(-start);
  38177. } else if (start) {
  38178. result = result.drop(start);
  38179. }
  38180. if (end !== undefined) {
  38181. end = toInteger(end);
  38182. result = end < 0 ? result.dropRight(-end) : result.take(end - start);
  38183. }
  38184. return result;
  38185. };
  38186. LazyWrapper.prototype.takeRightWhile = function(predicate) {
  38187. return this.reverse().takeWhile(predicate).reverse();
  38188. };
  38189. LazyWrapper.prototype.toArray = function() {
  38190. return this.take(MAX_ARRAY_LENGTH);
  38191. };
  38192. // Add `LazyWrapper` methods to `lodash.prototype`.
  38193. baseForOwn(LazyWrapper.prototype, function(func, methodName) {
  38194. var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
  38195. isTaker = /^(?:head|last)$/.test(methodName),
  38196. lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
  38197. retUnwrapped = isTaker || /^find/.test(methodName);
  38198. if (!lodashFunc) {
  38199. return;
  38200. }
  38201. lodash.prototype[methodName] = function() {
  38202. var value = this.__wrapped__,
  38203. args = isTaker ? [1] : arguments,
  38204. isLazy = value instanceof LazyWrapper,
  38205. iteratee = args[0],
  38206. useLazy = isLazy || isArray(value);
  38207. var interceptor = function(value) {
  38208. var result = lodashFunc.apply(lodash, arrayPush([value], args));
  38209. return (isTaker && chainAll) ? result[0] : result;
  38210. };
  38211. if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
  38212. // Avoid lazy use if the iteratee has a "length" value other than `1`.
  38213. isLazy = useLazy = false;
  38214. }
  38215. var chainAll = this.__chain__,
  38216. isHybrid = !!this.__actions__.length,
  38217. isUnwrapped = retUnwrapped && !chainAll,
  38218. onlyLazy = isLazy && !isHybrid;
  38219. if (!retUnwrapped && useLazy) {
  38220. value = onlyLazy ? value : new LazyWrapper(this);
  38221. var result = func.apply(value, args);
  38222. result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
  38223. return new LodashWrapper(result, chainAll);
  38224. }
  38225. if (isUnwrapped && onlyLazy) {
  38226. return func.apply(this, args);
  38227. }
  38228. result = this.thru(interceptor);
  38229. return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
  38230. };
  38231. });
  38232. // Add `Array` methods to `lodash.prototype`.
  38233. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
  38234. var func = arrayProto[methodName],
  38235. chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
  38236. retUnwrapped = /^(?:pop|shift)$/.test(methodName);
  38237. lodash.prototype[methodName] = function() {
  38238. var args = arguments;
  38239. if (retUnwrapped && !this.__chain__) {
  38240. var value = this.value();
  38241. return func.apply(isArray(value) ? value : [], args);
  38242. }
  38243. return this[chainName](function(value) {
  38244. return func.apply(isArray(value) ? value : [], args);
  38245. });
  38246. };
  38247. });
  38248. // Map minified method names to their real names.
  38249. baseForOwn(LazyWrapper.prototype, function(func, methodName) {
  38250. var lodashFunc = lodash[methodName];
  38251. if (lodashFunc) {
  38252. var key = (lodashFunc.name + ''),
  38253. names = realNames[key] || (realNames[key] = []);
  38254. names.push({ 'name': methodName, 'func': lodashFunc });
  38255. }
  38256. });
  38257. realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{
  38258. 'name': 'wrapper',
  38259. 'func': undefined
  38260. }];
  38261. // Add methods to `LazyWrapper`.
  38262. LazyWrapper.prototype.clone = lazyClone;
  38263. LazyWrapper.prototype.reverse = lazyReverse;
  38264. LazyWrapper.prototype.value = lazyValue;
  38265. // Add chain sequence methods to the `lodash` wrapper.
  38266. lodash.prototype.at = wrapperAt;
  38267. lodash.prototype.chain = wrapperChain;
  38268. lodash.prototype.commit = wrapperCommit;
  38269. lodash.prototype.next = wrapperNext;
  38270. lodash.prototype.plant = wrapperPlant;
  38271. lodash.prototype.reverse = wrapperReverse;
  38272. lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
  38273. // Add lazy aliases.
  38274. lodash.prototype.first = lodash.prototype.head;
  38275. if (symIterator) {
  38276. lodash.prototype[symIterator] = wrapperToIterator;
  38277. }
  38278. return lodash;
  38279. });
  38280. /*--------------------------------------------------------------------------*/
  38281. // Export lodash.
  38282. var _ = runInContext();
  38283. // Some AMD build optimizers, like r.js, check for condition patterns like:
  38284. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  38285. // Expose Lodash on the global object to prevent errors when Lodash is
  38286. // loaded by a script tag in the presence of an AMD loader.
  38287. // See http://requirejs.org/docs/errors.html#mismatch for more details.
  38288. // Use `_.noConflict` to remove Lodash from the global object.
  38289. root._ = _;
  38290. // Define as an anonymous module so, through path mapping, it can be
  38291. // referenced as the "underscore" module.
  38292. define(function() {
  38293. return _;
  38294. });
  38295. }
  38296. // Check for `exports` after `define` in case a build optimizer adds it.
  38297. else if (freeModule) {
  38298. // Export for Node.js.
  38299. (freeModule.exports = _)._ = _;
  38300. // Export for CommonJS support.
  38301. freeExports._ = _;
  38302. }
  38303. else {
  38304. // Export to the global object.
  38305. root._ = _;
  38306. }
  38307. }.call(this));
  38308. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  38309. },{}],124:[function(require,module,exports){
  38310. (function (process){
  38311. 'use strict';
  38312. if (!process.version ||
  38313. process.version.indexOf('v0.') === 0 ||
  38314. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  38315. module.exports = nextTick;
  38316. } else {
  38317. module.exports = process.nextTick;
  38318. }
  38319. function nextTick(fn, arg1, arg2, arg3) {
  38320. if (typeof fn !== 'function') {
  38321. throw new TypeError('"callback" argument must be a function');
  38322. }
  38323. var len = arguments.length;
  38324. var args, i;
  38325. switch (len) {
  38326. case 0:
  38327. case 1:
  38328. return process.nextTick(fn);
  38329. case 2:
  38330. return process.nextTick(function afterTickOne() {
  38331. fn.call(null, arg1);
  38332. });
  38333. case 3:
  38334. return process.nextTick(function afterTickTwo() {
  38335. fn.call(null, arg1, arg2);
  38336. });
  38337. case 4:
  38338. return process.nextTick(function afterTickThree() {
  38339. fn.call(null, arg1, arg2, arg3);
  38340. });
  38341. default:
  38342. args = new Array(len - 1);
  38343. i = 0;
  38344. while (i < args.length) {
  38345. args[i++] = arguments[i];
  38346. }
  38347. return process.nextTick(function afterTick() {
  38348. fn.apply(null, args);
  38349. });
  38350. }
  38351. }
  38352. }).call(this,require('_process'))
  38353. },{"_process":125}],125:[function(require,module,exports){
  38354. // shim for using process in browser
  38355. var process = module.exports = {};
  38356. // cached from whatever global is present so that test runners that stub it
  38357. // don't break things. But we need to wrap it in a try catch in case it is
  38358. // wrapped in strict mode code which doesn't define any globals. It's inside a
  38359. // function because try/catches deoptimize in certain engines.
  38360. var cachedSetTimeout;
  38361. var cachedClearTimeout;
  38362. function defaultSetTimout() {
  38363. throw new Error('setTimeout has not been defined');
  38364. }
  38365. function defaultClearTimeout () {
  38366. throw new Error('clearTimeout has not been defined');
  38367. }
  38368. (function () {
  38369. try {
  38370. if (typeof setTimeout === 'function') {
  38371. cachedSetTimeout = setTimeout;
  38372. } else {
  38373. cachedSetTimeout = defaultSetTimout;
  38374. }
  38375. } catch (e) {
  38376. cachedSetTimeout = defaultSetTimout;
  38377. }
  38378. try {
  38379. if (typeof clearTimeout === 'function') {
  38380. cachedClearTimeout = clearTimeout;
  38381. } else {
  38382. cachedClearTimeout = defaultClearTimeout;
  38383. }
  38384. } catch (e) {
  38385. cachedClearTimeout = defaultClearTimeout;
  38386. }
  38387. } ())
  38388. function runTimeout(fun) {
  38389. if (cachedSetTimeout === setTimeout) {
  38390. //normal enviroments in sane situations
  38391. return setTimeout(fun, 0);
  38392. }
  38393. // if setTimeout wasn't available but was latter defined
  38394. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  38395. cachedSetTimeout = setTimeout;
  38396. return setTimeout(fun, 0);
  38397. }
  38398. try {
  38399. // when when somebody has screwed with setTimeout but no I.E. maddness
  38400. return cachedSetTimeout(fun, 0);
  38401. } catch(e){
  38402. try {
  38403. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  38404. return cachedSetTimeout.call(null, fun, 0);
  38405. } catch(e){
  38406. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  38407. return cachedSetTimeout.call(this, fun, 0);
  38408. }
  38409. }
  38410. }
  38411. function runClearTimeout(marker) {
  38412. if (cachedClearTimeout === clearTimeout) {
  38413. //normal enviroments in sane situations
  38414. return clearTimeout(marker);
  38415. }
  38416. // if clearTimeout wasn't available but was latter defined
  38417. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  38418. cachedClearTimeout = clearTimeout;
  38419. return clearTimeout(marker);
  38420. }
  38421. try {
  38422. // when when somebody has screwed with setTimeout but no I.E. maddness
  38423. return cachedClearTimeout(marker);
  38424. } catch (e){
  38425. try {
  38426. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  38427. return cachedClearTimeout.call(null, marker);
  38428. } catch (e){
  38429. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  38430. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  38431. return cachedClearTimeout.call(this, marker);
  38432. }
  38433. }
  38434. }
  38435. var queue = [];
  38436. var draining = false;
  38437. var currentQueue;
  38438. var queueIndex = -1;
  38439. function cleanUpNextTick() {
  38440. if (!draining || !currentQueue) {
  38441. return;
  38442. }
  38443. draining = false;
  38444. if (currentQueue.length) {
  38445. queue = currentQueue.concat(queue);
  38446. } else {
  38447. queueIndex = -1;
  38448. }
  38449. if (queue.length) {
  38450. drainQueue();
  38451. }
  38452. }
  38453. function drainQueue() {
  38454. if (draining) {
  38455. return;
  38456. }
  38457. var timeout = runTimeout(cleanUpNextTick);
  38458. draining = true;
  38459. var len = queue.length;
  38460. while(len) {
  38461. currentQueue = queue;
  38462. queue = [];
  38463. while (++queueIndex < len) {
  38464. if (currentQueue) {
  38465. currentQueue[queueIndex].run();
  38466. }
  38467. }
  38468. queueIndex = -1;
  38469. len = queue.length;
  38470. }
  38471. currentQueue = null;
  38472. draining = false;
  38473. runClearTimeout(timeout);
  38474. }
  38475. process.nextTick = function (fun) {
  38476. var args = new Array(arguments.length - 1);
  38477. if (arguments.length > 1) {
  38478. for (var i = 1; i < arguments.length; i++) {
  38479. args[i - 1] = arguments[i];
  38480. }
  38481. }
  38482. queue.push(new Item(fun, args));
  38483. if (queue.length === 1 && !draining) {
  38484. runTimeout(drainQueue);
  38485. }
  38486. };
  38487. // v8 likes predictible objects
  38488. function Item(fun, array) {
  38489. this.fun = fun;
  38490. this.array = array;
  38491. }
  38492. Item.prototype.run = function () {
  38493. this.fun.apply(null, this.array);
  38494. };
  38495. process.title = 'browser';
  38496. process.browser = true;
  38497. process.env = {};
  38498. process.argv = [];
  38499. process.version = ''; // empty string to avoid regexp issues
  38500. process.versions = {};
  38501. function noop() {}
  38502. process.on = noop;
  38503. process.addListener = noop;
  38504. process.once = noop;
  38505. process.off = noop;
  38506. process.removeListener = noop;
  38507. process.removeAllListeners = noop;
  38508. process.emit = noop;
  38509. process.prependListener = noop;
  38510. process.prependOnceListener = noop;
  38511. process.listeners = function (name) { return [] }
  38512. process.binding = function (name) {
  38513. throw new Error('process.binding is not supported');
  38514. };
  38515. process.cwd = function () { return '/' };
  38516. process.chdir = function (dir) {
  38517. throw new Error('process.chdir is not supported');
  38518. };
  38519. process.umask = function() { return 0; };
  38520. },{}],126:[function(require,module,exports){
  38521. (function (global){
  38522. /*! https://mths.be/punycode v1.4.1 by @mathias */
  38523. ;(function(root) {
  38524. /** Detect free variables */
  38525. var freeExports = typeof exports == 'object' && exports &&
  38526. !exports.nodeType && exports;
  38527. var freeModule = typeof module == 'object' && module &&
  38528. !module.nodeType && module;
  38529. var freeGlobal = typeof global == 'object' && global;
  38530. if (
  38531. freeGlobal.global === freeGlobal ||
  38532. freeGlobal.window === freeGlobal ||
  38533. freeGlobal.self === freeGlobal
  38534. ) {
  38535. root = freeGlobal;
  38536. }
  38537. /**
  38538. * The `punycode` object.
  38539. * @name punycode
  38540. * @type Object
  38541. */
  38542. var punycode,
  38543. /** Highest positive signed 32-bit float value */
  38544. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  38545. /** Bootstring parameters */
  38546. base = 36,
  38547. tMin = 1,
  38548. tMax = 26,
  38549. skew = 38,
  38550. damp = 700,
  38551. initialBias = 72,
  38552. initialN = 128, // 0x80
  38553. delimiter = '-', // '\x2D'
  38554. /** Regular expressions */
  38555. regexPunycode = /^xn--/,
  38556. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  38557. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  38558. /** Error messages */
  38559. errors = {
  38560. 'overflow': 'Overflow: input needs wider integers to process',
  38561. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  38562. 'invalid-input': 'Invalid input'
  38563. },
  38564. /** Convenience shortcuts */
  38565. baseMinusTMin = base - tMin,
  38566. floor = Math.floor,
  38567. stringFromCharCode = String.fromCharCode,
  38568. /** Temporary variable */
  38569. key;
  38570. /*--------------------------------------------------------------------------*/
  38571. /**
  38572. * A generic error utility function.
  38573. * @private
  38574. * @param {String} type The error type.
  38575. * @returns {Error} Throws a `RangeError` with the applicable error message.
  38576. */
  38577. function error(type) {
  38578. throw new RangeError(errors[type]);
  38579. }
  38580. /**
  38581. * A generic `Array#map` utility function.
  38582. * @private
  38583. * @param {Array} array The array to iterate over.
  38584. * @param {Function} callback The function that gets called for every array
  38585. * item.
  38586. * @returns {Array} A new array of values returned by the callback function.
  38587. */
  38588. function map(array, fn) {
  38589. var length = array.length;
  38590. var result = [];
  38591. while (length--) {
  38592. result[length] = fn(array[length]);
  38593. }
  38594. return result;
  38595. }
  38596. /**
  38597. * A simple `Array#map`-like wrapper to work with domain name strings or email
  38598. * addresses.
  38599. * @private
  38600. * @param {String} domain The domain name or email address.
  38601. * @param {Function} callback The function that gets called for every
  38602. * character.
  38603. * @returns {Array} A new string of characters returned by the callback
  38604. * function.
  38605. */
  38606. function mapDomain(string, fn) {
  38607. var parts = string.split('@');
  38608. var result = '';
  38609. if (parts.length > 1) {
  38610. // In email addresses, only the domain name should be punycoded. Leave
  38611. // the local part (i.e. everything up to `@`) intact.
  38612. result = parts[0] + '@';
  38613. string = parts[1];
  38614. }
  38615. // Avoid `split(regex)` for IE8 compatibility. See #17.
  38616. string = string.replace(regexSeparators, '\x2E');
  38617. var labels = string.split('.');
  38618. var encoded = map(labels, fn).join('.');
  38619. return result + encoded;
  38620. }
  38621. /**
  38622. * Creates an array containing the numeric code points of each Unicode
  38623. * character in the string. While JavaScript uses UCS-2 internally,
  38624. * this function will convert a pair of surrogate halves (each of which
  38625. * UCS-2 exposes as separate characters) into a single code point,
  38626. * matching UTF-16.
  38627. * @see `punycode.ucs2.encode`
  38628. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  38629. * @memberOf punycode.ucs2
  38630. * @name decode
  38631. * @param {String} string The Unicode input string (UCS-2).
  38632. * @returns {Array} The new array of code points.
  38633. */
  38634. function ucs2decode(string) {
  38635. var output = [],
  38636. counter = 0,
  38637. length = string.length,
  38638. value,
  38639. extra;
  38640. while (counter < length) {
  38641. value = string.charCodeAt(counter++);
  38642. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  38643. // high surrogate, and there is a next character
  38644. extra = string.charCodeAt(counter++);
  38645. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  38646. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  38647. } else {
  38648. // unmatched surrogate; only append this code unit, in case the next
  38649. // code unit is the high surrogate of a surrogate pair
  38650. output.push(value);
  38651. counter--;
  38652. }
  38653. } else {
  38654. output.push(value);
  38655. }
  38656. }
  38657. return output;
  38658. }
  38659. /**
  38660. * Creates a string based on an array of numeric code points.
  38661. * @see `punycode.ucs2.decode`
  38662. * @memberOf punycode.ucs2
  38663. * @name encode
  38664. * @param {Array} codePoints The array of numeric code points.
  38665. * @returns {String} The new Unicode string (UCS-2).
  38666. */
  38667. function ucs2encode(array) {
  38668. return map(array, function(value) {
  38669. var output = '';
  38670. if (value > 0xFFFF) {
  38671. value -= 0x10000;
  38672. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  38673. value = 0xDC00 | value & 0x3FF;
  38674. }
  38675. output += stringFromCharCode(value);
  38676. return output;
  38677. }).join('');
  38678. }
  38679. /**
  38680. * Converts a basic code point into a digit/integer.
  38681. * @see `digitToBasic()`
  38682. * @private
  38683. * @param {Number} codePoint The basic numeric code point value.
  38684. * @returns {Number} The numeric value of a basic code point (for use in
  38685. * representing integers) in the range `0` to `base - 1`, or `base` if
  38686. * the code point does not represent a value.
  38687. */
  38688. function basicToDigit(codePoint) {
  38689. if (codePoint - 48 < 10) {
  38690. return codePoint - 22;
  38691. }
  38692. if (codePoint - 65 < 26) {
  38693. return codePoint - 65;
  38694. }
  38695. if (codePoint - 97 < 26) {
  38696. return codePoint - 97;
  38697. }
  38698. return base;
  38699. }
  38700. /**
  38701. * Converts a digit/integer into a basic code point.
  38702. * @see `basicToDigit()`
  38703. * @private
  38704. * @param {Number} digit The numeric value of a basic code point.
  38705. * @returns {Number} The basic code point whose value (when used for
  38706. * representing integers) is `digit`, which needs to be in the range
  38707. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  38708. * used; else, the lowercase form is used. The behavior is undefined
  38709. * if `flag` is non-zero and `digit` has no uppercase form.
  38710. */
  38711. function digitToBasic(digit, flag) {
  38712. // 0..25 map to ASCII a..z or A..Z
  38713. // 26..35 map to ASCII 0..9
  38714. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  38715. }
  38716. /**
  38717. * Bias adaptation function as per section 3.4 of RFC 3492.
  38718. * https://tools.ietf.org/html/rfc3492#section-3.4
  38719. * @private
  38720. */
  38721. function adapt(delta, numPoints, firstTime) {
  38722. var k = 0;
  38723. delta = firstTime ? floor(delta / damp) : delta >> 1;
  38724. delta += floor(delta / numPoints);
  38725. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  38726. delta = floor(delta / baseMinusTMin);
  38727. }
  38728. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  38729. }
  38730. /**
  38731. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  38732. * symbols.
  38733. * @memberOf punycode
  38734. * @param {String} input The Punycode string of ASCII-only symbols.
  38735. * @returns {String} The resulting string of Unicode symbols.
  38736. */
  38737. function decode(input) {
  38738. // Don't use UCS-2
  38739. var output = [],
  38740. inputLength = input.length,
  38741. out,
  38742. i = 0,
  38743. n = initialN,
  38744. bias = initialBias,
  38745. basic,
  38746. j,
  38747. index,
  38748. oldi,
  38749. w,
  38750. k,
  38751. digit,
  38752. t,
  38753. /** Cached calculation results */
  38754. baseMinusT;
  38755. // Handle the basic code points: let `basic` be the number of input code
  38756. // points before the last delimiter, or `0` if there is none, then copy
  38757. // the first basic code points to the output.
  38758. basic = input.lastIndexOf(delimiter);
  38759. if (basic < 0) {
  38760. basic = 0;
  38761. }
  38762. for (j = 0; j < basic; ++j) {
  38763. // if it's not a basic code point
  38764. if (input.charCodeAt(j) >= 0x80) {
  38765. error('not-basic');
  38766. }
  38767. output.push(input.charCodeAt(j));
  38768. }
  38769. // Main decoding loop: start just after the last delimiter if any basic code
  38770. // points were copied; start at the beginning otherwise.
  38771. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  38772. // `index` is the index of the next character to be consumed.
  38773. // Decode a generalized variable-length integer into `delta`,
  38774. // which gets added to `i`. The overflow checking is easier
  38775. // if we increase `i` as we go, then subtract off its starting
  38776. // value at the end to obtain `delta`.
  38777. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  38778. if (index >= inputLength) {
  38779. error('invalid-input');
  38780. }
  38781. digit = basicToDigit(input.charCodeAt(index++));
  38782. if (digit >= base || digit > floor((maxInt - i) / w)) {
  38783. error('overflow');
  38784. }
  38785. i += digit * w;
  38786. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  38787. if (digit < t) {
  38788. break;
  38789. }
  38790. baseMinusT = base - t;
  38791. if (w > floor(maxInt / baseMinusT)) {
  38792. error('overflow');
  38793. }
  38794. w *= baseMinusT;
  38795. }
  38796. out = output.length + 1;
  38797. bias = adapt(i - oldi, out, oldi == 0);
  38798. // `i` was supposed to wrap around from `out` to `0`,
  38799. // incrementing `n` each time, so we'll fix that now:
  38800. if (floor(i / out) > maxInt - n) {
  38801. error('overflow');
  38802. }
  38803. n += floor(i / out);
  38804. i %= out;
  38805. // Insert `n` at position `i` of the output
  38806. output.splice(i++, 0, n);
  38807. }
  38808. return ucs2encode(output);
  38809. }
  38810. /**
  38811. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  38812. * Punycode string of ASCII-only symbols.
  38813. * @memberOf punycode
  38814. * @param {String} input The string of Unicode symbols.
  38815. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  38816. */
  38817. function encode(input) {
  38818. var n,
  38819. delta,
  38820. handledCPCount,
  38821. basicLength,
  38822. bias,
  38823. j,
  38824. m,
  38825. q,
  38826. k,
  38827. t,
  38828. currentValue,
  38829. output = [],
  38830. /** `inputLength` will hold the number of code points in `input`. */
  38831. inputLength,
  38832. /** Cached calculation results */
  38833. handledCPCountPlusOne,
  38834. baseMinusT,
  38835. qMinusT;
  38836. // Convert the input in UCS-2 to Unicode
  38837. input = ucs2decode(input);
  38838. // Cache the length
  38839. inputLength = input.length;
  38840. // Initialize the state
  38841. n = initialN;
  38842. delta = 0;
  38843. bias = initialBias;
  38844. // Handle the basic code points
  38845. for (j = 0; j < inputLength; ++j) {
  38846. currentValue = input[j];
  38847. if (currentValue < 0x80) {
  38848. output.push(stringFromCharCode(currentValue));
  38849. }
  38850. }
  38851. handledCPCount = basicLength = output.length;
  38852. // `handledCPCount` is the number of code points that have been handled;
  38853. // `basicLength` is the number of basic code points.
  38854. // Finish the basic string - if it is not empty - with a delimiter
  38855. if (basicLength) {
  38856. output.push(delimiter);
  38857. }
  38858. // Main encoding loop:
  38859. while (handledCPCount < inputLength) {
  38860. // All non-basic code points < n have been handled already. Find the next
  38861. // larger one:
  38862. for (m = maxInt, j = 0; j < inputLength; ++j) {
  38863. currentValue = input[j];
  38864. if (currentValue >= n && currentValue < m) {
  38865. m = currentValue;
  38866. }
  38867. }
  38868. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  38869. // but guard against overflow
  38870. handledCPCountPlusOne = handledCPCount + 1;
  38871. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  38872. error('overflow');
  38873. }
  38874. delta += (m - n) * handledCPCountPlusOne;
  38875. n = m;
  38876. for (j = 0; j < inputLength; ++j) {
  38877. currentValue = input[j];
  38878. if (currentValue < n && ++delta > maxInt) {
  38879. error('overflow');
  38880. }
  38881. if (currentValue == n) {
  38882. // Represent delta as a generalized variable-length integer
  38883. for (q = delta, k = base; /* no condition */; k += base) {
  38884. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  38885. if (q < t) {
  38886. break;
  38887. }
  38888. qMinusT = q - t;
  38889. baseMinusT = base - t;
  38890. output.push(
  38891. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  38892. );
  38893. q = floor(qMinusT / baseMinusT);
  38894. }
  38895. output.push(stringFromCharCode(digitToBasic(q, 0)));
  38896. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  38897. delta = 0;
  38898. ++handledCPCount;
  38899. }
  38900. }
  38901. ++delta;
  38902. ++n;
  38903. }
  38904. return output.join('');
  38905. }
  38906. /**
  38907. * Converts a Punycode string representing a domain name or an email address
  38908. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  38909. * it doesn't matter if you call it on a string that has already been
  38910. * converted to Unicode.
  38911. * @memberOf punycode
  38912. * @param {String} input The Punycoded domain name or email address to
  38913. * convert to Unicode.
  38914. * @returns {String} The Unicode representation of the given Punycode
  38915. * string.
  38916. */
  38917. function toUnicode(input) {
  38918. return mapDomain(input, function(string) {
  38919. return regexPunycode.test(string)
  38920. ? decode(string.slice(4).toLowerCase())
  38921. : string;
  38922. });
  38923. }
  38924. /**
  38925. * Converts a Unicode string representing a domain name or an email address to
  38926. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  38927. * i.e. it doesn't matter if you call it with a domain that's already in
  38928. * ASCII.
  38929. * @memberOf punycode
  38930. * @param {String} input The domain name or email address to convert, as a
  38931. * Unicode string.
  38932. * @returns {String} The Punycode representation of the given domain name or
  38933. * email address.
  38934. */
  38935. function toASCII(input) {
  38936. return mapDomain(input, function(string) {
  38937. return regexNonASCII.test(string)
  38938. ? 'xn--' + encode(string)
  38939. : string;
  38940. });
  38941. }
  38942. /*--------------------------------------------------------------------------*/
  38943. /** Define the public API */
  38944. punycode = {
  38945. /**
  38946. * A string representing the current Punycode.js version number.
  38947. * @memberOf punycode
  38948. * @type String
  38949. */
  38950. 'version': '1.4.1',
  38951. /**
  38952. * An object of methods to convert from JavaScript's internal character
  38953. * representation (UCS-2) to Unicode code points, and back.
  38954. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  38955. * @memberOf punycode
  38956. * @type Object
  38957. */
  38958. 'ucs2': {
  38959. 'decode': ucs2decode,
  38960. 'encode': ucs2encode
  38961. },
  38962. 'decode': decode,
  38963. 'encode': encode,
  38964. 'toASCII': toASCII,
  38965. 'toUnicode': toUnicode
  38966. };
  38967. /** Expose `punycode` */
  38968. // Some AMD build optimizers, like r.js, check for specific condition patterns
  38969. // like the following:
  38970. if (
  38971. typeof define == 'function' &&
  38972. typeof define.amd == 'object' &&
  38973. define.amd
  38974. ) {
  38975. define('punycode', function() {
  38976. return punycode;
  38977. });
  38978. } else if (freeExports && freeModule) {
  38979. if (module.exports == freeExports) {
  38980. // in Node.js, io.js, or RingoJS v0.8.0+
  38981. freeModule.exports = punycode;
  38982. } else {
  38983. // in Narwhal or RingoJS v0.7.0-
  38984. for (key in punycode) {
  38985. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  38986. }
  38987. }
  38988. } else {
  38989. // in Rhino or a web browser
  38990. root.punycode = punycode;
  38991. }
  38992. }(this));
  38993. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  38994. },{}],127:[function(require,module,exports){
  38995. // Copyright Joyent, Inc. and other Node contributors.
  38996. //
  38997. // Permission is hereby granted, free of charge, to any person obtaining a
  38998. // copy of this software and associated documentation files (the
  38999. // "Software"), to deal in the Software without restriction, including
  39000. // without limitation the rights to use, copy, modify, merge, publish,
  39001. // distribute, sublicense, and/or sell copies of the Software, and to permit
  39002. // persons to whom the Software is furnished to do so, subject to the
  39003. // following conditions:
  39004. //
  39005. // The above copyright notice and this permission notice shall be included
  39006. // in all copies or substantial portions of the Software.
  39007. //
  39008. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  39009. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  39010. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  39011. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  39012. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  39013. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  39014. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  39015. 'use strict';
  39016. // If obj.hasOwnProperty has been overridden, then calling
  39017. // obj.hasOwnProperty(prop) will break.
  39018. // See: https://github.com/joyent/node/issues/1707
  39019. function hasOwnProperty(obj, prop) {
  39020. return Object.prototype.hasOwnProperty.call(obj, prop);
  39021. }
  39022. module.exports = function(qs, sep, eq, options) {
  39023. sep = sep || '&';
  39024. eq = eq || '=';
  39025. var obj = {};
  39026. if (typeof qs !== 'string' || qs.length === 0) {
  39027. return obj;
  39028. }
  39029. var regexp = /\+/g;
  39030. qs = qs.split(sep);
  39031. var maxKeys = 1000;
  39032. if (options && typeof options.maxKeys === 'number') {
  39033. maxKeys = options.maxKeys;
  39034. }
  39035. var len = qs.length;
  39036. // maxKeys <= 0 means that we should not limit keys count
  39037. if (maxKeys > 0 && len > maxKeys) {
  39038. len = maxKeys;
  39039. }
  39040. for (var i = 0; i < len; ++i) {
  39041. var x = qs[i].replace(regexp, '%20'),
  39042. idx = x.indexOf(eq),
  39043. kstr, vstr, k, v;
  39044. if (idx >= 0) {
  39045. kstr = x.substr(0, idx);
  39046. vstr = x.substr(idx + 1);
  39047. } else {
  39048. kstr = x;
  39049. vstr = '';
  39050. }
  39051. k = decodeURIComponent(kstr);
  39052. v = decodeURIComponent(vstr);
  39053. if (!hasOwnProperty(obj, k)) {
  39054. obj[k] = v;
  39055. } else if (isArray(obj[k])) {
  39056. obj[k].push(v);
  39057. } else {
  39058. obj[k] = [obj[k], v];
  39059. }
  39060. }
  39061. return obj;
  39062. };
  39063. var isArray = Array.isArray || function (xs) {
  39064. return Object.prototype.toString.call(xs) === '[object Array]';
  39065. };
  39066. },{}],128:[function(require,module,exports){
  39067. // Copyright Joyent, Inc. and other Node contributors.
  39068. //
  39069. // Permission is hereby granted, free of charge, to any person obtaining a
  39070. // copy of this software and associated documentation files (the
  39071. // "Software"), to deal in the Software without restriction, including
  39072. // without limitation the rights to use, copy, modify, merge, publish,
  39073. // distribute, sublicense, and/or sell copies of the Software, and to permit
  39074. // persons to whom the Software is furnished to do so, subject to the
  39075. // following conditions:
  39076. //
  39077. // The above copyright notice and this permission notice shall be included
  39078. // in all copies or substantial portions of the Software.
  39079. //
  39080. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  39081. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  39082. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  39083. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  39084. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  39085. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  39086. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  39087. 'use strict';
  39088. var stringifyPrimitive = function(v) {
  39089. switch (typeof v) {
  39090. case 'string':
  39091. return v;
  39092. case 'boolean':
  39093. return v ? 'true' : 'false';
  39094. case 'number':
  39095. return isFinite(v) ? v : '';
  39096. default:
  39097. return '';
  39098. }
  39099. };
  39100. module.exports = function(obj, sep, eq, name) {
  39101. sep = sep || '&';
  39102. eq = eq || '=';
  39103. if (obj === null) {
  39104. obj = undefined;
  39105. }
  39106. if (typeof obj === 'object') {
  39107. return map(objectKeys(obj), function(k) {
  39108. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  39109. if (isArray(obj[k])) {
  39110. return map(obj[k], function(v) {
  39111. return ks + encodeURIComponent(stringifyPrimitive(v));
  39112. }).join(sep);
  39113. } else {
  39114. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  39115. }
  39116. }).join(sep);
  39117. }
  39118. if (!name) return '';
  39119. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  39120. encodeURIComponent(stringifyPrimitive(obj));
  39121. };
  39122. var isArray = Array.isArray || function (xs) {
  39123. return Object.prototype.toString.call(xs) === '[object Array]';
  39124. };
  39125. function map (xs, f) {
  39126. if (xs.map) return xs.map(f);
  39127. var res = [];
  39128. for (var i = 0; i < xs.length; i++) {
  39129. res.push(f(xs[i], i));
  39130. }
  39131. return res;
  39132. }
  39133. var objectKeys = Object.keys || function (obj) {
  39134. var res = [];
  39135. for (var key in obj) {
  39136. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  39137. }
  39138. return res;
  39139. };
  39140. },{}],129:[function(require,module,exports){
  39141. 'use strict';
  39142. exports.decode = exports.parse = require('./decode');
  39143. exports.encode = exports.stringify = require('./encode');
  39144. },{"./decode":127,"./encode":128}],130:[function(require,module,exports){
  39145. /* eslint-disable node/no-deprecated-api */
  39146. var buffer = require('buffer')
  39147. var Buffer = buffer.Buffer
  39148. // alternative to using Object.keys for old browsers
  39149. function copyProps (src, dst) {
  39150. for (var key in src) {
  39151. dst[key] = src[key]
  39152. }
  39153. }
  39154. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  39155. module.exports = buffer
  39156. } else {
  39157. // Copy properties from require('buffer')
  39158. copyProps(buffer, exports)
  39159. exports.Buffer = SafeBuffer
  39160. }
  39161. function SafeBuffer (arg, encodingOrOffset, length) {
  39162. return Buffer(arg, encodingOrOffset, length)
  39163. }
  39164. // Copy static methods from Buffer
  39165. copyProps(Buffer, SafeBuffer)
  39166. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  39167. if (typeof arg === 'number') {
  39168. throw new TypeError('Argument must not be a number')
  39169. }
  39170. return Buffer(arg, encodingOrOffset, length)
  39171. }
  39172. SafeBuffer.alloc = function (size, fill, encoding) {
  39173. if (typeof size !== 'number') {
  39174. throw new TypeError('Argument must be a number')
  39175. }
  39176. var buf = Buffer(size)
  39177. if (fill !== undefined) {
  39178. if (typeof encoding === 'string') {
  39179. buf.fill(fill, encoding)
  39180. } else {
  39181. buf.fill(fill)
  39182. }
  39183. } else {
  39184. buf.fill(0)
  39185. }
  39186. return buf
  39187. }
  39188. SafeBuffer.allocUnsafe = function (size) {
  39189. if (typeof size !== 'number') {
  39190. throw new TypeError('Argument must be a number')
  39191. }
  39192. return Buffer(size)
  39193. }
  39194. SafeBuffer.allocUnsafeSlow = function (size) {
  39195. if (typeof size !== 'number') {
  39196. throw new TypeError('Argument must be a number')
  39197. }
  39198. return buffer.SlowBuffer(size)
  39199. }
  39200. },{"buffer":32}],131:[function(require,module,exports){
  39201. (function (global){
  39202. var ClientRequest = require('./lib/request')
  39203. var extend = require('xtend')
  39204. var statusCodes = require('builtin-status-codes')
  39205. var url = require('url')
  39206. var http = exports
  39207. http.request = function (opts, cb) {
  39208. if (typeof opts === 'string')
  39209. opts = url.parse(opts)
  39210. else
  39211. opts = extend(opts)
  39212. // Normally, the page is loaded from http or https, so not specifying a protocol
  39213. // will result in a (valid) protocol-relative url. However, this won't work if
  39214. // the protocol is something else, like 'file:'
  39215. var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
  39216. var protocol = opts.protocol || defaultProtocol
  39217. var host = opts.hostname || opts.host
  39218. var port = opts.port
  39219. var path = opts.path || '/'
  39220. // Necessary for IPv6 addresses
  39221. if (host && host.indexOf(':') !== -1)
  39222. host = '[' + host + ']'
  39223. // This may be a relative url. The browser should always be able to interpret it correctly.
  39224. opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
  39225. opts.method = (opts.method || 'GET').toUpperCase()
  39226. opts.headers = opts.headers || {}
  39227. // Also valid opts.auth, opts.mode
  39228. var req = new ClientRequest(opts)
  39229. if (cb)
  39230. req.on('response', cb)
  39231. return req
  39232. }
  39233. http.get = function get (opts, cb) {
  39234. var req = http.request(opts, cb)
  39235. req.end()
  39236. return req
  39237. }
  39238. http.Agent = function () {}
  39239. http.Agent.defaultMaxSockets = 4
  39240. http.STATUS_CODES = statusCodes
  39241. http.METHODS = [
  39242. 'CHECKOUT',
  39243. 'CONNECT',
  39244. 'COPY',
  39245. 'DELETE',
  39246. 'GET',
  39247. 'HEAD',
  39248. 'LOCK',
  39249. 'M-SEARCH',
  39250. 'MERGE',
  39251. 'MKACTIVITY',
  39252. 'MKCOL',
  39253. 'MOVE',
  39254. 'NOTIFY',
  39255. 'OPTIONS',
  39256. 'PATCH',
  39257. 'POST',
  39258. 'PROPFIND',
  39259. 'PROPPATCH',
  39260. 'PURGE',
  39261. 'PUT',
  39262. 'REPORT',
  39263. 'SEARCH',
  39264. 'SUBSCRIBE',
  39265. 'TRACE',
  39266. 'UNLOCK',
  39267. 'UNSUBSCRIBE'
  39268. ]
  39269. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  39270. },{"./lib/request":133,"builtin-status-codes":37,"url":35,"xtend":149}],132:[function(require,module,exports){
  39271. (function (global){
  39272. exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
  39273. exports.blobConstructor = false
  39274. try {
  39275. new Blob([new ArrayBuffer(1)])
  39276. exports.blobConstructor = true
  39277. } catch (e) {}
  39278. // The xhr request to example.com may violate some restrictive CSP configurations,
  39279. // so if we're running in a browser that supports `fetch`, avoid calling getXHR()
  39280. // and assume support for certain features below.
  39281. var xhr
  39282. function getXHR () {
  39283. // Cache the xhr value
  39284. if (xhr !== undefined) return xhr
  39285. if (global.XMLHttpRequest) {
  39286. xhr = new global.XMLHttpRequest()
  39287. // If XDomainRequest is available (ie only, where xhr might not work
  39288. // cross domain), use the page location. Otherwise use example.com
  39289. // Note: this doesn't actually make an http request.
  39290. try {
  39291. xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
  39292. } catch(e) {
  39293. xhr = null
  39294. }
  39295. } else {
  39296. // Service workers don't have XHR
  39297. xhr = null
  39298. }
  39299. return xhr
  39300. }
  39301. function checkTypeSupport (type) {
  39302. var xhr = getXHR()
  39303. if (!xhr) return false
  39304. try {
  39305. xhr.responseType = type
  39306. return xhr.responseType === type
  39307. } catch (e) {}
  39308. return false
  39309. }
  39310. // For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
  39311. // Safari 7.1 appears to have fixed this bug.
  39312. var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined'
  39313. var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice)
  39314. // If fetch is supported, then arraybuffer will be supported too. Skip calling
  39315. // checkTypeSupport(), since that calls getXHR().
  39316. exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer'))
  39317. // These next two tests unavoidably show warnings in Chrome. Since fetch will always
  39318. // be used if it's available, just return false for these to avoid the warnings.
  39319. exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream')
  39320. exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer &&
  39321. checkTypeSupport('moz-chunked-arraybuffer')
  39322. // If fetch is supported, then overrideMimeType will be supported too. Skip calling
  39323. // getXHR().
  39324. exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
  39325. exports.vbArray = isFunction(global.VBArray)
  39326. function isFunction (value) {
  39327. return typeof value === 'function'
  39328. }
  39329. xhr = null // Help gc
  39330. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  39331. },{}],133:[function(require,module,exports){
  39332. (function (process,global,Buffer){
  39333. var capability = require('./capability')
  39334. var inherits = require('inherits')
  39335. var response = require('./response')
  39336. var stream = require('readable-stream')
  39337. var toArrayBuffer = require('to-arraybuffer')
  39338. var IncomingMessage = response.IncomingMessage
  39339. var rStates = response.readyStates
  39340. function decideMode (preferBinary, useFetch) {
  39341. if (capability.fetch && useFetch) {
  39342. return 'fetch'
  39343. } else if (capability.mozchunkedarraybuffer) {
  39344. return 'moz-chunked-arraybuffer'
  39345. } else if (capability.msstream) {
  39346. return 'ms-stream'
  39347. } else if (capability.arraybuffer && preferBinary) {
  39348. return 'arraybuffer'
  39349. } else if (capability.vbArray && preferBinary) {
  39350. return 'text:vbarray'
  39351. } else {
  39352. return 'text'
  39353. }
  39354. }
  39355. var ClientRequest = module.exports = function (opts) {
  39356. var self = this
  39357. stream.Writable.call(self)
  39358. self._opts = opts
  39359. self._body = []
  39360. self._headers = {}
  39361. if (opts.auth)
  39362. self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
  39363. Object.keys(opts.headers).forEach(function (name) {
  39364. self.setHeader(name, opts.headers[name])
  39365. })
  39366. var preferBinary
  39367. var useFetch = true
  39368. if (opts.mode === 'disable-fetch' || 'timeout' in opts) {
  39369. // If the use of XHR should be preferred and includes preserving the 'content-type' header.
  39370. // Force XHR to be used since the Fetch API does not yet support timeouts.
  39371. useFetch = false
  39372. preferBinary = true
  39373. } else if (opts.mode === 'prefer-streaming') {
  39374. // If streaming is a high priority but binary compatibility and
  39375. // the accuracy of the 'content-type' header aren't
  39376. preferBinary = false
  39377. } else if (opts.mode === 'allow-wrong-content-type') {
  39378. // If streaming is more important than preserving the 'content-type' header
  39379. preferBinary = !capability.overrideMimeType
  39380. } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
  39381. // Use binary if text streaming may corrupt data or the content-type header, or for speed
  39382. preferBinary = true
  39383. } else {
  39384. throw new Error('Invalid value for opts.mode')
  39385. }
  39386. self._mode = decideMode(preferBinary, useFetch)
  39387. self.on('finish', function () {
  39388. self._onFinish()
  39389. })
  39390. }
  39391. inherits(ClientRequest, stream.Writable)
  39392. ClientRequest.prototype.setHeader = function (name, value) {
  39393. var self = this
  39394. var lowerName = name.toLowerCase()
  39395. // This check is not necessary, but it prevents warnings from browsers about setting unsafe
  39396. // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
  39397. // http-browserify did it, so I will too.
  39398. if (unsafeHeaders.indexOf(lowerName) !== -1)
  39399. return
  39400. self._headers[lowerName] = {
  39401. name: name,
  39402. value: value
  39403. }
  39404. }
  39405. ClientRequest.prototype.getHeader = function (name) {
  39406. var header = this._headers[name.toLowerCase()]
  39407. if (header)
  39408. return header.value
  39409. return null
  39410. }
  39411. ClientRequest.prototype.removeHeader = function (name) {
  39412. var self = this
  39413. delete self._headers[name.toLowerCase()]
  39414. }
  39415. ClientRequest.prototype._onFinish = function () {
  39416. var self = this
  39417. if (self._destroyed)
  39418. return
  39419. var opts = self._opts
  39420. var headersObj = self._headers
  39421. var body = null
  39422. if (opts.method !== 'GET' && opts.method !== 'HEAD') {
  39423. if (capability.blobConstructor) {
  39424. body = new global.Blob(self._body.map(function (buffer) {
  39425. return toArrayBuffer(buffer)
  39426. }), {
  39427. type: (headersObj['content-type'] || {}).value || ''
  39428. })
  39429. } else {
  39430. // get utf8 string
  39431. body = Buffer.concat(self._body).toString()
  39432. }
  39433. }
  39434. // create flattened list of headers
  39435. var headersList = []
  39436. Object.keys(headersObj).forEach(function (keyName) {
  39437. var name = headersObj[keyName].name
  39438. var value = headersObj[keyName].value
  39439. if (Array.isArray(value)) {
  39440. value.forEach(function (v) {
  39441. headersList.push([name, v])
  39442. })
  39443. } else {
  39444. headersList.push([name, value])
  39445. }
  39446. })
  39447. if (self._mode === 'fetch') {
  39448. global.fetch(self._opts.url, {
  39449. method: self._opts.method,
  39450. headers: headersList,
  39451. body: body || undefined,
  39452. mode: 'cors',
  39453. credentials: opts.withCredentials ? 'include' : 'same-origin'
  39454. }).then(function (response) {
  39455. self._fetchResponse = response
  39456. self._connect()
  39457. }, function (reason) {
  39458. self.emit('error', reason)
  39459. })
  39460. } else {
  39461. var xhr = self._xhr = new global.XMLHttpRequest()
  39462. try {
  39463. xhr.open(self._opts.method, self._opts.url, true)
  39464. } catch (err) {
  39465. process.nextTick(function () {
  39466. self.emit('error', err)
  39467. })
  39468. return
  39469. }
  39470. // Can't set responseType on really old browsers
  39471. if ('responseType' in xhr)
  39472. xhr.responseType = self._mode.split(':')[0]
  39473. if ('withCredentials' in xhr)
  39474. xhr.withCredentials = !!opts.withCredentials
  39475. if (self._mode === 'text' && 'overrideMimeType' in xhr)
  39476. xhr.overrideMimeType('text/plain; charset=x-user-defined')
  39477. if ('timeout' in opts) {
  39478. xhr.timeout = opts.timeout
  39479. xhr.ontimeout = function () {
  39480. self.emit('timeout')
  39481. }
  39482. }
  39483. headersList.forEach(function (header) {
  39484. xhr.setRequestHeader(header[0], header[1])
  39485. })
  39486. self._response = null
  39487. xhr.onreadystatechange = function () {
  39488. switch (xhr.readyState) {
  39489. case rStates.LOADING:
  39490. case rStates.DONE:
  39491. self._onXHRProgress()
  39492. break
  39493. }
  39494. }
  39495. // Necessary for streaming in Firefox, since xhr.response is ONLY defined
  39496. // in onprogress, not in onreadystatechange with xhr.readyState = 3
  39497. if (self._mode === 'moz-chunked-arraybuffer') {
  39498. xhr.onprogress = function () {
  39499. self._onXHRProgress()
  39500. }
  39501. }
  39502. xhr.onerror = function () {
  39503. if (self._destroyed)
  39504. return
  39505. self.emit('error', new Error('XHR error'))
  39506. }
  39507. try {
  39508. xhr.send(body)
  39509. } catch (err) {
  39510. process.nextTick(function () {
  39511. self.emit('error', err)
  39512. })
  39513. return
  39514. }
  39515. }
  39516. }
  39517. /**
  39518. * Checks if xhr.status is readable and non-zero, indicating no error.
  39519. * Even though the spec says it should be available in readyState 3,
  39520. * accessing it throws an exception in IE8
  39521. */
  39522. function statusValid (xhr) {
  39523. try {
  39524. var status = xhr.status
  39525. return (status !== null && status !== 0)
  39526. } catch (e) {
  39527. return false
  39528. }
  39529. }
  39530. ClientRequest.prototype._onXHRProgress = function () {
  39531. var self = this
  39532. if (!statusValid(self._xhr) || self._destroyed)
  39533. return
  39534. if (!self._response)
  39535. self._connect()
  39536. self._response._onXHRProgress()
  39537. }
  39538. ClientRequest.prototype._connect = function () {
  39539. var self = this
  39540. if (self._destroyed)
  39541. return
  39542. self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
  39543. self._response.on('error', function(err) {
  39544. self.emit('error', err)
  39545. })
  39546. self.emit('response', self._response)
  39547. }
  39548. ClientRequest.prototype._write = function (chunk, encoding, cb) {
  39549. var self = this
  39550. self._body.push(chunk)
  39551. cb()
  39552. }
  39553. ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
  39554. var self = this
  39555. self._destroyed = true
  39556. if (self._response)
  39557. self._response._destroyed = true
  39558. if (self._xhr)
  39559. self._xhr.abort()
  39560. // Currently, there isn't a way to truly abort a fetch.
  39561. // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27
  39562. }
  39563. ClientRequest.prototype.end = function (data, encoding, cb) {
  39564. var self = this
  39565. if (typeof data === 'function') {
  39566. cb = data
  39567. data = undefined
  39568. }
  39569. stream.Writable.prototype.end.call(self, data, encoding, cb)
  39570. }
  39571. ClientRequest.prototype.flushHeaders = function () {}
  39572. ClientRequest.prototype.setTimeout = function () {}
  39573. ClientRequest.prototype.setNoDelay = function () {}
  39574. ClientRequest.prototype.setSocketKeepAlive = function () {}
  39575. // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
  39576. var unsafeHeaders = [
  39577. 'accept-charset',
  39578. 'accept-encoding',
  39579. 'access-control-request-headers',
  39580. 'access-control-request-method',
  39581. 'connection',
  39582. 'content-length',
  39583. 'cookie',
  39584. 'cookie2',
  39585. 'date',
  39586. 'dnt',
  39587. 'expect',
  39588. 'host',
  39589. 'keep-alive',
  39590. 'origin',
  39591. 'referer',
  39592. 'te',
  39593. 'trailer',
  39594. 'transfer-encoding',
  39595. 'upgrade',
  39596. 'user-agent',
  39597. 'via'
  39598. ]
  39599. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
  39600. },{"./capability":132,"./response":134,"_process":125,"buffer":32,"inherits":121,"readable-stream":144,"to-arraybuffer":146}],134:[function(require,module,exports){
  39601. (function (process,global,Buffer){
  39602. var capability = require('./capability')
  39603. var inherits = require('inherits')
  39604. var stream = require('readable-stream')
  39605. var rStates = exports.readyStates = {
  39606. UNSENT: 0,
  39607. OPENED: 1,
  39608. HEADERS_RECEIVED: 2,
  39609. LOADING: 3,
  39610. DONE: 4
  39611. }
  39612. var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) {
  39613. var self = this
  39614. stream.Readable.call(self)
  39615. self._mode = mode
  39616. self.headers = {}
  39617. self.rawHeaders = []
  39618. self.trailers = {}
  39619. self.rawTrailers = []
  39620. // Fake the 'close' event, but only once 'end' fires
  39621. self.on('end', function () {
  39622. // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
  39623. process.nextTick(function () {
  39624. self.emit('close')
  39625. })
  39626. })
  39627. if (mode === 'fetch') {
  39628. self._fetchResponse = response
  39629. self.url = response.url
  39630. self.statusCode = response.status
  39631. self.statusMessage = response.statusText
  39632. response.headers.forEach(function(header, key){
  39633. self.headers[key.toLowerCase()] = header
  39634. self.rawHeaders.push(key, header)
  39635. })
  39636. // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed
  39637. var reader = response.body.getReader()
  39638. function read () {
  39639. reader.read().then(function (result) {
  39640. if (self._destroyed)
  39641. return
  39642. if (result.done) {
  39643. self.push(null)
  39644. return
  39645. }
  39646. self.push(new Buffer(result.value))
  39647. read()
  39648. }).catch(function(err) {
  39649. self.emit('error', err)
  39650. })
  39651. }
  39652. read()
  39653. } else {
  39654. self._xhr = xhr
  39655. self._pos = 0
  39656. self.url = xhr.responseURL
  39657. self.statusCode = xhr.status
  39658. self.statusMessage = xhr.statusText
  39659. var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
  39660. headers.forEach(function (header) {
  39661. var matches = header.match(/^([^:]+):\s*(.*)/)
  39662. if (matches) {
  39663. var key = matches[1].toLowerCase()
  39664. if (key === 'set-cookie') {
  39665. if (self.headers[key] === undefined) {
  39666. self.headers[key] = []
  39667. }
  39668. self.headers[key].push(matches[2])
  39669. } else if (self.headers[key] !== undefined) {
  39670. self.headers[key] += ', ' + matches[2]
  39671. } else {
  39672. self.headers[key] = matches[2]
  39673. }
  39674. self.rawHeaders.push(matches[1], matches[2])
  39675. }
  39676. })
  39677. self._charset = 'x-user-defined'
  39678. if (!capability.overrideMimeType) {
  39679. var mimeType = self.rawHeaders['mime-type']
  39680. if (mimeType) {
  39681. var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
  39682. if (charsetMatch) {
  39683. self._charset = charsetMatch[1].toLowerCase()
  39684. }
  39685. }
  39686. if (!self._charset)
  39687. self._charset = 'utf-8' // best guess
  39688. }
  39689. }
  39690. }
  39691. inherits(IncomingMessage, stream.Readable)
  39692. IncomingMessage.prototype._read = function () {}
  39693. IncomingMessage.prototype._onXHRProgress = function () {
  39694. var self = this
  39695. var xhr = self._xhr
  39696. var response = null
  39697. switch (self._mode) {
  39698. case 'text:vbarray': // For IE9
  39699. if (xhr.readyState !== rStates.DONE)
  39700. break
  39701. try {
  39702. // This fails in IE8
  39703. response = new global.VBArray(xhr.responseBody).toArray()
  39704. } catch (e) {}
  39705. if (response !== null) {
  39706. self.push(new Buffer(response))
  39707. break
  39708. }
  39709. // Falls through in IE8
  39710. case 'text':
  39711. try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
  39712. response = xhr.responseText
  39713. } catch (e) {
  39714. self._mode = 'text:vbarray'
  39715. break
  39716. }
  39717. if (response.length > self._pos) {
  39718. var newData = response.substr(self._pos)
  39719. if (self._charset === 'x-user-defined') {
  39720. var buffer = new Buffer(newData.length)
  39721. for (var i = 0; i < newData.length; i++)
  39722. buffer[i] = newData.charCodeAt(i) & 0xff
  39723. self.push(buffer)
  39724. } else {
  39725. self.push(newData, self._charset)
  39726. }
  39727. self._pos = response.length
  39728. }
  39729. break
  39730. case 'arraybuffer':
  39731. if (xhr.readyState !== rStates.DONE || !xhr.response)
  39732. break
  39733. response = xhr.response
  39734. self.push(new Buffer(new Uint8Array(response)))
  39735. break
  39736. case 'moz-chunked-arraybuffer': // take whole
  39737. response = xhr.response
  39738. if (xhr.readyState !== rStates.LOADING || !response)
  39739. break
  39740. self.push(new Buffer(new Uint8Array(response)))
  39741. break
  39742. case 'ms-stream':
  39743. response = xhr.response
  39744. if (xhr.readyState !== rStates.LOADING)
  39745. break
  39746. var reader = new global.MSStreamReader()
  39747. reader.onprogress = function () {
  39748. if (reader.result.byteLength > self._pos) {
  39749. self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))))
  39750. self._pos = reader.result.byteLength
  39751. }
  39752. }
  39753. reader.onload = function () {
  39754. self.push(null)
  39755. }
  39756. // reader.onerror = ??? // TODO: this
  39757. reader.readAsArrayBuffer(response)
  39758. break
  39759. }
  39760. // The ms-stream case handles end separately in reader.onload()
  39761. if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
  39762. self.push(null)
  39763. }
  39764. }
  39765. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
  39766. },{"./capability":132,"_process":125,"buffer":32,"inherits":121,"readable-stream":144}],135:[function(require,module,exports){
  39767. var toString = {}.toString;
  39768. module.exports = Array.isArray || function (arr) {
  39769. return toString.call(arr) == '[object Array]';
  39770. };
  39771. },{}],136:[function(require,module,exports){
  39772. // Copyright Joyent, Inc. and other Node contributors.
  39773. //
  39774. // Permission is hereby granted, free of charge, to any person obtaining a
  39775. // copy of this software and associated documentation files (the
  39776. // "Software"), to deal in the Software without restriction, including
  39777. // without limitation the rights to use, copy, modify, merge, publish,
  39778. // distribute, sublicense, and/or sell copies of the Software, and to permit
  39779. // persons to whom the Software is furnished to do so, subject to the
  39780. // following conditions:
  39781. //
  39782. // The above copyright notice and this permission notice shall be included
  39783. // in all copies or substantial portions of the Software.
  39784. //
  39785. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  39786. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  39787. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  39788. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  39789. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  39790. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  39791. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  39792. // a duplex stream is just a stream that is both readable and writable.
  39793. // Since JS doesn't have multiple prototypal inheritance, this class
  39794. // prototypally inherits from Readable, and then parasitically from
  39795. // Writable.
  39796. 'use strict';
  39797. /*<replacement>*/
  39798. var processNextTick = require('process-nextick-args');
  39799. /*</replacement>*/
  39800. /*<replacement>*/
  39801. var objectKeys = Object.keys || function (obj) {
  39802. var keys = [];
  39803. for (var key in obj) {
  39804. keys.push(key);
  39805. }return keys;
  39806. };
  39807. /*</replacement>*/
  39808. module.exports = Duplex;
  39809. /*<replacement>*/
  39810. var util = require('core-util-is');
  39811. util.inherits = require('inherits');
  39812. /*</replacement>*/
  39813. var Readable = require('./_stream_readable');
  39814. var Writable = require('./_stream_writable');
  39815. util.inherits(Duplex, Readable);
  39816. var keys = objectKeys(Writable.prototype);
  39817. for (var v = 0; v < keys.length; v++) {
  39818. var method = keys[v];
  39819. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  39820. }
  39821. function Duplex(options) {
  39822. if (!(this instanceof Duplex)) return new Duplex(options);
  39823. Readable.call(this, options);
  39824. Writable.call(this, options);
  39825. if (options && options.readable === false) this.readable = false;
  39826. if (options && options.writable === false) this.writable = false;
  39827. this.allowHalfOpen = true;
  39828. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  39829. this.once('end', onend);
  39830. }
  39831. // the no-half-open enforcer
  39832. function onend() {
  39833. // if we allow half-open state, or if the writable side ended,
  39834. // then we're ok.
  39835. if (this.allowHalfOpen || this._writableState.ended) return;
  39836. // no more data can be written.
  39837. // But allow more writes to happen in this tick.
  39838. processNextTick(onEndNT, this);
  39839. }
  39840. function onEndNT(self) {
  39841. self.end();
  39842. }
  39843. Object.defineProperty(Duplex.prototype, 'destroyed', {
  39844. get: function () {
  39845. if (this._readableState === undefined || this._writableState === undefined) {
  39846. return false;
  39847. }
  39848. return this._readableState.destroyed && this._writableState.destroyed;
  39849. },
  39850. set: function (value) {
  39851. // we ignore the value if the stream
  39852. // has not been initialized yet
  39853. if (this._readableState === undefined || this._writableState === undefined) {
  39854. return;
  39855. }
  39856. // backward compatibility, the user is explicitly
  39857. // managing destroyed
  39858. this._readableState.destroyed = value;
  39859. this._writableState.destroyed = value;
  39860. }
  39861. });
  39862. Duplex.prototype._destroy = function (err, cb) {
  39863. this.push(null);
  39864. this.end();
  39865. processNextTick(cb, err);
  39866. };
  39867. function forEach(xs, f) {
  39868. for (var i = 0, l = xs.length; i < l; i++) {
  39869. f(xs[i], i);
  39870. }
  39871. }
  39872. },{"./_stream_readable":138,"./_stream_writable":140,"core-util-is":38,"inherits":121,"process-nextick-args":124}],137:[function(require,module,exports){
  39873. // Copyright Joyent, Inc. and other Node contributors.
  39874. //
  39875. // Permission is hereby granted, free of charge, to any person obtaining a
  39876. // copy of this software and associated documentation files (the
  39877. // "Software"), to deal in the Software without restriction, including
  39878. // without limitation the rights to use, copy, modify, merge, publish,
  39879. // distribute, sublicense, and/or sell copies of the Software, and to permit
  39880. // persons to whom the Software is furnished to do so, subject to the
  39881. // following conditions:
  39882. //
  39883. // The above copyright notice and this permission notice shall be included
  39884. // in all copies or substantial portions of the Software.
  39885. //
  39886. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  39887. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  39888. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  39889. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  39890. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  39891. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  39892. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  39893. // a passthrough stream.
  39894. // basically just the most minimal sort of Transform stream.
  39895. // Every written chunk gets output as-is.
  39896. 'use strict';
  39897. module.exports = PassThrough;
  39898. var Transform = require('./_stream_transform');
  39899. /*<replacement>*/
  39900. var util = require('core-util-is');
  39901. util.inherits = require('inherits');
  39902. /*</replacement>*/
  39903. util.inherits(PassThrough, Transform);
  39904. function PassThrough(options) {
  39905. if (!(this instanceof PassThrough)) return new PassThrough(options);
  39906. Transform.call(this, options);
  39907. }
  39908. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  39909. cb(null, chunk);
  39910. };
  39911. },{"./_stream_transform":139,"core-util-is":38,"inherits":121}],138:[function(require,module,exports){
  39912. (function (process,global){
  39913. // Copyright Joyent, Inc. and other Node contributors.
  39914. //
  39915. // Permission is hereby granted, free of charge, to any person obtaining a
  39916. // copy of this software and associated documentation files (the
  39917. // "Software"), to deal in the Software without restriction, including
  39918. // without limitation the rights to use, copy, modify, merge, publish,
  39919. // distribute, sublicense, and/or sell copies of the Software, and to permit
  39920. // persons to whom the Software is furnished to do so, subject to the
  39921. // following conditions:
  39922. //
  39923. // The above copyright notice and this permission notice shall be included
  39924. // in all copies or substantial portions of the Software.
  39925. //
  39926. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  39927. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  39928. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  39929. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  39930. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  39931. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  39932. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  39933. 'use strict';
  39934. /*<replacement>*/
  39935. var processNextTick = require('process-nextick-args');
  39936. /*</replacement>*/
  39937. module.exports = Readable;
  39938. /*<replacement>*/
  39939. var isArray = require('isarray');
  39940. /*</replacement>*/
  39941. /*<replacement>*/
  39942. var Duplex;
  39943. /*</replacement>*/
  39944. Readable.ReadableState = ReadableState;
  39945. /*<replacement>*/
  39946. var EE = require('events').EventEmitter;
  39947. var EElistenerCount = function (emitter, type) {
  39948. return emitter.listeners(type).length;
  39949. };
  39950. /*</replacement>*/
  39951. /*<replacement>*/
  39952. var Stream = require('./internal/streams/stream');
  39953. /*</replacement>*/
  39954. // TODO(bmeurer): Change this back to const once hole checks are
  39955. // properly optimized away early in Ignition+TurboFan.
  39956. /*<replacement>*/
  39957. var Buffer = require('safe-buffer').Buffer;
  39958. var OurUint8Array = global.Uint8Array || function () {};
  39959. function _uint8ArrayToBuffer(chunk) {
  39960. return Buffer.from(chunk);
  39961. }
  39962. function _isUint8Array(obj) {
  39963. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  39964. }
  39965. /*</replacement>*/
  39966. /*<replacement>*/
  39967. var util = require('core-util-is');
  39968. util.inherits = require('inherits');
  39969. /*</replacement>*/
  39970. /*<replacement>*/
  39971. var debugUtil = require('util');
  39972. var debug = void 0;
  39973. if (debugUtil && debugUtil.debuglog) {
  39974. debug = debugUtil.debuglog('stream');
  39975. } else {
  39976. debug = function () {};
  39977. }
  39978. /*</replacement>*/
  39979. var BufferList = require('./internal/streams/BufferList');
  39980. var destroyImpl = require('./internal/streams/destroy');
  39981. var StringDecoder;
  39982. util.inherits(Readable, Stream);
  39983. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  39984. function prependListener(emitter, event, fn) {
  39985. // Sadly this is not cacheable as some libraries bundle their own
  39986. // event emitter implementation with them.
  39987. if (typeof emitter.prependListener === 'function') {
  39988. return emitter.prependListener(event, fn);
  39989. } else {
  39990. // This is a hack to make sure that our error handler is attached before any
  39991. // userland ones. NEVER DO THIS. This is here only because this code needs
  39992. // to continue to work with older versions of Node.js that do not include
  39993. // the prependListener() method. The goal is to eventually remove this hack.
  39994. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  39995. }
  39996. }
  39997. function ReadableState(options, stream) {
  39998. Duplex = Duplex || require('./_stream_duplex');
  39999. options = options || {};
  40000. // object stream flag. Used to make read(n) ignore n and to
  40001. // make all the buffer merging and length checks go away
  40002. this.objectMode = !!options.objectMode;
  40003. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  40004. // the point at which it stops calling _read() to fill the buffer
  40005. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  40006. var hwm = options.highWaterMark;
  40007. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  40008. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  40009. // cast to ints.
  40010. this.highWaterMark = Math.floor(this.highWaterMark);
  40011. // A linked list is used to store data chunks instead of an array because the
  40012. // linked list can remove elements from the beginning faster than
  40013. // array.shift()
  40014. this.buffer = new BufferList();
  40015. this.length = 0;
  40016. this.pipes = null;
  40017. this.pipesCount = 0;
  40018. this.flowing = null;
  40019. this.ended = false;
  40020. this.endEmitted = false;
  40021. this.reading = false;
  40022. // a flag to be able to tell if the event 'readable'/'data' is emitted
  40023. // immediately, or on a later tick. We set this to true at first, because
  40024. // any actions that shouldn't happen until "later" should generally also
  40025. // not happen before the first read call.
  40026. this.sync = true;
  40027. // whenever we return null, then we set a flag to say
  40028. // that we're awaiting a 'readable' event emission.
  40029. this.needReadable = false;
  40030. this.emittedReadable = false;
  40031. this.readableListening = false;
  40032. this.resumeScheduled = false;
  40033. // has it been destroyed
  40034. this.destroyed = false;
  40035. // Crypto is kind of old and crusty. Historically, its default string
  40036. // encoding is 'binary' so we have to make this configurable.
  40037. // Everything else in the universe uses 'utf8', though.
  40038. this.defaultEncoding = options.defaultEncoding || 'utf8';
  40039. // the number of writers that are awaiting a drain event in .pipe()s
  40040. this.awaitDrain = 0;
  40041. // if true, a maybeReadMore has been scheduled
  40042. this.readingMore = false;
  40043. this.decoder = null;
  40044. this.encoding = null;
  40045. if (options.encoding) {
  40046. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  40047. this.decoder = new StringDecoder(options.encoding);
  40048. this.encoding = options.encoding;
  40049. }
  40050. }
  40051. function Readable(options) {
  40052. Duplex = Duplex || require('./_stream_duplex');
  40053. if (!(this instanceof Readable)) return new Readable(options);
  40054. this._readableState = new ReadableState(options, this);
  40055. // legacy
  40056. this.readable = true;
  40057. if (options) {
  40058. if (typeof options.read === 'function') this._read = options.read;
  40059. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  40060. }
  40061. Stream.call(this);
  40062. }
  40063. Object.defineProperty(Readable.prototype, 'destroyed', {
  40064. get: function () {
  40065. if (this._readableState === undefined) {
  40066. return false;
  40067. }
  40068. return this._readableState.destroyed;
  40069. },
  40070. set: function (value) {
  40071. // we ignore the value if the stream
  40072. // has not been initialized yet
  40073. if (!this._readableState) {
  40074. return;
  40075. }
  40076. // backward compatibility, the user is explicitly
  40077. // managing destroyed
  40078. this._readableState.destroyed = value;
  40079. }
  40080. });
  40081. Readable.prototype.destroy = destroyImpl.destroy;
  40082. Readable.prototype._undestroy = destroyImpl.undestroy;
  40083. Readable.prototype._destroy = function (err, cb) {
  40084. this.push(null);
  40085. cb(err);
  40086. };
  40087. // Manually shove something into the read() buffer.
  40088. // This returns true if the highWaterMark has not been hit yet,
  40089. // similar to how Writable.write() returns true if you should
  40090. // write() some more.
  40091. Readable.prototype.push = function (chunk, encoding) {
  40092. var state = this._readableState;
  40093. var skipChunkCheck;
  40094. if (!state.objectMode) {
  40095. if (typeof chunk === 'string') {
  40096. encoding = encoding || state.defaultEncoding;
  40097. if (encoding !== state.encoding) {
  40098. chunk = Buffer.from(chunk, encoding);
  40099. encoding = '';
  40100. }
  40101. skipChunkCheck = true;
  40102. }
  40103. } else {
  40104. skipChunkCheck = true;
  40105. }
  40106. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  40107. };
  40108. // Unshift should *always* be something directly out of read()
  40109. Readable.prototype.unshift = function (chunk) {
  40110. return readableAddChunk(this, chunk, null, true, false);
  40111. };
  40112. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  40113. var state = stream._readableState;
  40114. if (chunk === null) {
  40115. state.reading = false;
  40116. onEofChunk(stream, state);
  40117. } else {
  40118. var er;
  40119. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  40120. if (er) {
  40121. stream.emit('error', er);
  40122. } else if (state.objectMode || chunk && chunk.length > 0) {
  40123. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  40124. chunk = _uint8ArrayToBuffer(chunk);
  40125. }
  40126. if (addToFront) {
  40127. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  40128. } else if (state.ended) {
  40129. stream.emit('error', new Error('stream.push() after EOF'));
  40130. } else {
  40131. state.reading = false;
  40132. if (state.decoder && !encoding) {
  40133. chunk = state.decoder.write(chunk);
  40134. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  40135. } else {
  40136. addChunk(stream, state, chunk, false);
  40137. }
  40138. }
  40139. } else if (!addToFront) {
  40140. state.reading = false;
  40141. }
  40142. }
  40143. return needMoreData(state);
  40144. }
  40145. function addChunk(stream, state, chunk, addToFront) {
  40146. if (state.flowing && state.length === 0 && !state.sync) {
  40147. stream.emit('data', chunk);
  40148. stream.read(0);
  40149. } else {
  40150. // update the buffer info.
  40151. state.length += state.objectMode ? 1 : chunk.length;
  40152. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  40153. if (state.needReadable) emitReadable(stream);
  40154. }
  40155. maybeReadMore(stream, state);
  40156. }
  40157. function chunkInvalid(state, chunk) {
  40158. var er;
  40159. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  40160. er = new TypeError('Invalid non-string/buffer chunk');
  40161. }
  40162. return er;
  40163. }
  40164. // if it's past the high water mark, we can push in some more.
  40165. // Also, if we have no data yet, we can stand some
  40166. // more bytes. This is to work around cases where hwm=0,
  40167. // such as the repl. Also, if the push() triggered a
  40168. // readable event, and the user called read(largeNumber) such that
  40169. // needReadable was set, then we ought to push more, so that another
  40170. // 'readable' event will be triggered.
  40171. function needMoreData(state) {
  40172. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  40173. }
  40174. Readable.prototype.isPaused = function () {
  40175. return this._readableState.flowing === false;
  40176. };
  40177. // backwards compatibility.
  40178. Readable.prototype.setEncoding = function (enc) {
  40179. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  40180. this._readableState.decoder = new StringDecoder(enc);
  40181. this._readableState.encoding = enc;
  40182. return this;
  40183. };
  40184. // Don't raise the hwm > 8MB
  40185. var MAX_HWM = 0x800000;
  40186. function computeNewHighWaterMark(n) {
  40187. if (n >= MAX_HWM) {
  40188. n = MAX_HWM;
  40189. } else {
  40190. // Get the next highest power of 2 to prevent increasing hwm excessively in
  40191. // tiny amounts
  40192. n--;
  40193. n |= n >>> 1;
  40194. n |= n >>> 2;
  40195. n |= n >>> 4;
  40196. n |= n >>> 8;
  40197. n |= n >>> 16;
  40198. n++;
  40199. }
  40200. return n;
  40201. }
  40202. // This function is designed to be inlinable, so please take care when making
  40203. // changes to the function body.
  40204. function howMuchToRead(n, state) {
  40205. if (n <= 0 || state.length === 0 && state.ended) return 0;
  40206. if (state.objectMode) return 1;
  40207. if (n !== n) {
  40208. // Only flow one buffer at a time
  40209. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  40210. }
  40211. // If we're asking for more than the current hwm, then raise the hwm.
  40212. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  40213. if (n <= state.length) return n;
  40214. // Don't have enough
  40215. if (!state.ended) {
  40216. state.needReadable = true;
  40217. return 0;
  40218. }
  40219. return state.length;
  40220. }
  40221. // you can override either this method, or the async _read(n) below.
  40222. Readable.prototype.read = function (n) {
  40223. debug('read', n);
  40224. n = parseInt(n, 10);
  40225. var state = this._readableState;
  40226. var nOrig = n;
  40227. if (n !== 0) state.emittedReadable = false;
  40228. // if we're doing read(0) to trigger a readable event, but we
  40229. // already have a bunch of data in the buffer, then just trigger
  40230. // the 'readable' event and move on.
  40231. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  40232. debug('read: emitReadable', state.length, state.ended);
  40233. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  40234. return null;
  40235. }
  40236. n = howMuchToRead(n, state);
  40237. // if we've ended, and we're now clear, then finish it up.
  40238. if (n === 0 && state.ended) {
  40239. if (state.length === 0) endReadable(this);
  40240. return null;
  40241. }
  40242. // All the actual chunk generation logic needs to be
  40243. // *below* the call to _read. The reason is that in certain
  40244. // synthetic stream cases, such as passthrough streams, _read
  40245. // may be a completely synchronous operation which may change
  40246. // the state of the read buffer, providing enough data when
  40247. // before there was *not* enough.
  40248. //
  40249. // So, the steps are:
  40250. // 1. Figure out what the state of things will be after we do
  40251. // a read from the buffer.
  40252. //
  40253. // 2. If that resulting state will trigger a _read, then call _read.
  40254. // Note that this may be asynchronous, or synchronous. Yes, it is
  40255. // deeply ugly to write APIs this way, but that still doesn't mean
  40256. // that the Readable class should behave improperly, as streams are
  40257. // designed to be sync/async agnostic.
  40258. // Take note if the _read call is sync or async (ie, if the read call
  40259. // has returned yet), so that we know whether or not it's safe to emit
  40260. // 'readable' etc.
  40261. //
  40262. // 3. Actually pull the requested chunks out of the buffer and return.
  40263. // if we need a readable event, then we need to do some reading.
  40264. var doRead = state.needReadable;
  40265. debug('need readable', doRead);
  40266. // if we currently have less than the highWaterMark, then also read some
  40267. if (state.length === 0 || state.length - n < state.highWaterMark) {
  40268. doRead = true;
  40269. debug('length less than watermark', doRead);
  40270. }
  40271. // however, if we've ended, then there's no point, and if we're already
  40272. // reading, then it's unnecessary.
  40273. if (state.ended || state.reading) {
  40274. doRead = false;
  40275. debug('reading or ended', doRead);
  40276. } else if (doRead) {
  40277. debug('do read');
  40278. state.reading = true;
  40279. state.sync = true;
  40280. // if the length is currently zero, then we *need* a readable event.
  40281. if (state.length === 0) state.needReadable = true;
  40282. // call internal read method
  40283. this._read(state.highWaterMark);
  40284. state.sync = false;
  40285. // If _read pushed data synchronously, then `reading` will be false,
  40286. // and we need to re-evaluate how much data we can return to the user.
  40287. if (!state.reading) n = howMuchToRead(nOrig, state);
  40288. }
  40289. var ret;
  40290. if (n > 0) ret = fromList(n, state);else ret = null;
  40291. if (ret === null) {
  40292. state.needReadable = true;
  40293. n = 0;
  40294. } else {
  40295. state.length -= n;
  40296. }
  40297. if (state.length === 0) {
  40298. // If we have nothing in the buffer, then we want to know
  40299. // as soon as we *do* get something into the buffer.
  40300. if (!state.ended) state.needReadable = true;
  40301. // If we tried to read() past the EOF, then emit end on the next tick.
  40302. if (nOrig !== n && state.ended) endReadable(this);
  40303. }
  40304. if (ret !== null) this.emit('data', ret);
  40305. return ret;
  40306. };
  40307. function onEofChunk(stream, state) {
  40308. if (state.ended) return;
  40309. if (state.decoder) {
  40310. var chunk = state.decoder.end();
  40311. if (chunk && chunk.length) {
  40312. state.buffer.push(chunk);
  40313. state.length += state.objectMode ? 1 : chunk.length;
  40314. }
  40315. }
  40316. state.ended = true;
  40317. // emit 'readable' now to make sure it gets picked up.
  40318. emitReadable(stream);
  40319. }
  40320. // Don't emit readable right away in sync mode, because this can trigger
  40321. // another read() call => stack overflow. This way, it might trigger
  40322. // a nextTick recursion warning, but that's not so bad.
  40323. function emitReadable(stream) {
  40324. var state = stream._readableState;
  40325. state.needReadable = false;
  40326. if (!state.emittedReadable) {
  40327. debug('emitReadable', state.flowing);
  40328. state.emittedReadable = true;
  40329. if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
  40330. }
  40331. }
  40332. function emitReadable_(stream) {
  40333. debug('emit readable');
  40334. stream.emit('readable');
  40335. flow(stream);
  40336. }
  40337. // at this point, the user has presumably seen the 'readable' event,
  40338. // and called read() to consume some data. that may have triggered
  40339. // in turn another _read(n) call, in which case reading = true if
  40340. // it's in progress.
  40341. // However, if we're not ended, or reading, and the length < hwm,
  40342. // then go ahead and try to read some more preemptively.
  40343. function maybeReadMore(stream, state) {
  40344. if (!state.readingMore) {
  40345. state.readingMore = true;
  40346. processNextTick(maybeReadMore_, stream, state);
  40347. }
  40348. }
  40349. function maybeReadMore_(stream, state) {
  40350. var len = state.length;
  40351. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  40352. debug('maybeReadMore read 0');
  40353. stream.read(0);
  40354. if (len === state.length)
  40355. // didn't get any data, stop spinning.
  40356. break;else len = state.length;
  40357. }
  40358. state.readingMore = false;
  40359. }
  40360. // abstract method. to be overridden in specific implementation classes.
  40361. // call cb(er, data) where data is <= n in length.
  40362. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  40363. // arbitrary, and perhaps not very meaningful.
  40364. Readable.prototype._read = function (n) {
  40365. this.emit('error', new Error('_read() is not implemented'));
  40366. };
  40367. Readable.prototype.pipe = function (dest, pipeOpts) {
  40368. var src = this;
  40369. var state = this._readableState;
  40370. switch (state.pipesCount) {
  40371. case 0:
  40372. state.pipes = dest;
  40373. break;
  40374. case 1:
  40375. state.pipes = [state.pipes, dest];
  40376. break;
  40377. default:
  40378. state.pipes.push(dest);
  40379. break;
  40380. }
  40381. state.pipesCount += 1;
  40382. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  40383. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  40384. var endFn = doEnd ? onend : unpipe;
  40385. if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
  40386. dest.on('unpipe', onunpipe);
  40387. function onunpipe(readable, unpipeInfo) {
  40388. debug('onunpipe');
  40389. if (readable === src) {
  40390. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  40391. unpipeInfo.hasUnpiped = true;
  40392. cleanup();
  40393. }
  40394. }
  40395. }
  40396. function onend() {
  40397. debug('onend');
  40398. dest.end();
  40399. }
  40400. // when the dest drains, it reduces the awaitDrain counter
  40401. // on the source. This would be more elegant with a .once()
  40402. // handler in flow(), but adding and removing repeatedly is
  40403. // too slow.
  40404. var ondrain = pipeOnDrain(src);
  40405. dest.on('drain', ondrain);
  40406. var cleanedUp = false;
  40407. function cleanup() {
  40408. debug('cleanup');
  40409. // cleanup event handlers once the pipe is broken
  40410. dest.removeListener('close', onclose);
  40411. dest.removeListener('finish', onfinish);
  40412. dest.removeListener('drain', ondrain);
  40413. dest.removeListener('error', onerror);
  40414. dest.removeListener('unpipe', onunpipe);
  40415. src.removeListener('end', onend);
  40416. src.removeListener('end', unpipe);
  40417. src.removeListener('data', ondata);
  40418. cleanedUp = true;
  40419. // if the reader is waiting for a drain event from this
  40420. // specific writer, then it would cause it to never start
  40421. // flowing again.
  40422. // So, if this is awaiting a drain, then we just call it now.
  40423. // If we don't know, then assume that we are waiting for one.
  40424. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  40425. }
  40426. // If the user pushes more data while we're writing to dest then we'll end up
  40427. // in ondata again. However, we only want to increase awaitDrain once because
  40428. // dest will only emit one 'drain' event for the multiple writes.
  40429. // => Introduce a guard on increasing awaitDrain.
  40430. var increasedAwaitDrain = false;
  40431. src.on('data', ondata);
  40432. function ondata(chunk) {
  40433. debug('ondata');
  40434. increasedAwaitDrain = false;
  40435. var ret = dest.write(chunk);
  40436. if (false === ret && !increasedAwaitDrain) {
  40437. // If the user unpiped during `dest.write()`, it is possible
  40438. // to get stuck in a permanently paused state if that write
  40439. // also returned false.
  40440. // => Check whether `dest` is still a piping destination.
  40441. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  40442. debug('false write response, pause', src._readableState.awaitDrain);
  40443. src._readableState.awaitDrain++;
  40444. increasedAwaitDrain = true;
  40445. }
  40446. src.pause();
  40447. }
  40448. }
  40449. // if the dest has an error, then stop piping into it.
  40450. // however, don't suppress the throwing behavior for this.
  40451. function onerror(er) {
  40452. debug('onerror', er);
  40453. unpipe();
  40454. dest.removeListener('error', onerror);
  40455. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  40456. }
  40457. // Make sure our error handler is attached before userland ones.
  40458. prependListener(dest, 'error', onerror);
  40459. // Both close and finish should trigger unpipe, but only once.
  40460. function onclose() {
  40461. dest.removeListener('finish', onfinish);
  40462. unpipe();
  40463. }
  40464. dest.once('close', onclose);
  40465. function onfinish() {
  40466. debug('onfinish');
  40467. dest.removeListener('close', onclose);
  40468. unpipe();
  40469. }
  40470. dest.once('finish', onfinish);
  40471. function unpipe() {
  40472. debug('unpipe');
  40473. src.unpipe(dest);
  40474. }
  40475. // tell the dest that it's being piped to
  40476. dest.emit('pipe', src);
  40477. // start the flow if it hasn't been started already.
  40478. if (!state.flowing) {
  40479. debug('pipe resume');
  40480. src.resume();
  40481. }
  40482. return dest;
  40483. };
  40484. function pipeOnDrain(src) {
  40485. return function () {
  40486. var state = src._readableState;
  40487. debug('pipeOnDrain', state.awaitDrain);
  40488. if (state.awaitDrain) state.awaitDrain--;
  40489. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  40490. state.flowing = true;
  40491. flow(src);
  40492. }
  40493. };
  40494. }
  40495. Readable.prototype.unpipe = function (dest) {
  40496. var state = this._readableState;
  40497. var unpipeInfo = { hasUnpiped: false };
  40498. // if we're not piping anywhere, then do nothing.
  40499. if (state.pipesCount === 0) return this;
  40500. // just one destination. most common case.
  40501. if (state.pipesCount === 1) {
  40502. // passed in one, but it's not the right one.
  40503. if (dest && dest !== state.pipes) return this;
  40504. if (!dest) dest = state.pipes;
  40505. // got a match.
  40506. state.pipes = null;
  40507. state.pipesCount = 0;
  40508. state.flowing = false;
  40509. if (dest) dest.emit('unpipe', this, unpipeInfo);
  40510. return this;
  40511. }
  40512. // slow case. multiple pipe destinations.
  40513. if (!dest) {
  40514. // remove all.
  40515. var dests = state.pipes;
  40516. var len = state.pipesCount;
  40517. state.pipes = null;
  40518. state.pipesCount = 0;
  40519. state.flowing = false;
  40520. for (var i = 0; i < len; i++) {
  40521. dests[i].emit('unpipe', this, unpipeInfo);
  40522. }return this;
  40523. }
  40524. // try to find the right one.
  40525. var index = indexOf(state.pipes, dest);
  40526. if (index === -1) return this;
  40527. state.pipes.splice(index, 1);
  40528. state.pipesCount -= 1;
  40529. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  40530. dest.emit('unpipe', this, unpipeInfo);
  40531. return this;
  40532. };
  40533. // set up data events if they are asked for
  40534. // Ensure readable listeners eventually get something
  40535. Readable.prototype.on = function (ev, fn) {
  40536. var res = Stream.prototype.on.call(this, ev, fn);
  40537. if (ev === 'data') {
  40538. // Start flowing on next tick if stream isn't explicitly paused
  40539. if (this._readableState.flowing !== false) this.resume();
  40540. } else if (ev === 'readable') {
  40541. var state = this._readableState;
  40542. if (!state.endEmitted && !state.readableListening) {
  40543. state.readableListening = state.needReadable = true;
  40544. state.emittedReadable = false;
  40545. if (!state.reading) {
  40546. processNextTick(nReadingNextTick, this);
  40547. } else if (state.length) {
  40548. emitReadable(this);
  40549. }
  40550. }
  40551. }
  40552. return res;
  40553. };
  40554. Readable.prototype.addListener = Readable.prototype.on;
  40555. function nReadingNextTick(self) {
  40556. debug('readable nexttick read 0');
  40557. self.read(0);
  40558. }
  40559. // pause() and resume() are remnants of the legacy readable stream API
  40560. // If the user uses them, then switch into old mode.
  40561. Readable.prototype.resume = function () {
  40562. var state = this._readableState;
  40563. if (!state.flowing) {
  40564. debug('resume');
  40565. state.flowing = true;
  40566. resume(this, state);
  40567. }
  40568. return this;
  40569. };
  40570. function resume(stream, state) {
  40571. if (!state.resumeScheduled) {
  40572. state.resumeScheduled = true;
  40573. processNextTick(resume_, stream, state);
  40574. }
  40575. }
  40576. function resume_(stream, state) {
  40577. if (!state.reading) {
  40578. debug('resume read 0');
  40579. stream.read(0);
  40580. }
  40581. state.resumeScheduled = false;
  40582. state.awaitDrain = 0;
  40583. stream.emit('resume');
  40584. flow(stream);
  40585. if (state.flowing && !state.reading) stream.read(0);
  40586. }
  40587. Readable.prototype.pause = function () {
  40588. debug('call pause flowing=%j', this._readableState.flowing);
  40589. if (false !== this._readableState.flowing) {
  40590. debug('pause');
  40591. this._readableState.flowing = false;
  40592. this.emit('pause');
  40593. }
  40594. return this;
  40595. };
  40596. function flow(stream) {
  40597. var state = stream._readableState;
  40598. debug('flow', state.flowing);
  40599. while (state.flowing && stream.read() !== null) {}
  40600. }
  40601. // wrap an old-style stream as the async data source.
  40602. // This is *not* part of the readable stream interface.
  40603. // It is an ugly unfortunate mess of history.
  40604. Readable.prototype.wrap = function (stream) {
  40605. var state = this._readableState;
  40606. var paused = false;
  40607. var self = this;
  40608. stream.on('end', function () {
  40609. debug('wrapped end');
  40610. if (state.decoder && !state.ended) {
  40611. var chunk = state.decoder.end();
  40612. if (chunk && chunk.length) self.push(chunk);
  40613. }
  40614. self.push(null);
  40615. });
  40616. stream.on('data', function (chunk) {
  40617. debug('wrapped data');
  40618. if (state.decoder) chunk = state.decoder.write(chunk);
  40619. // don't skip over falsy values in objectMode
  40620. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  40621. var ret = self.push(chunk);
  40622. if (!ret) {
  40623. paused = true;
  40624. stream.pause();
  40625. }
  40626. });
  40627. // proxy all the other methods.
  40628. // important when wrapping filters and duplexes.
  40629. for (var i in stream) {
  40630. if (this[i] === undefined && typeof stream[i] === 'function') {
  40631. this[i] = function (method) {
  40632. return function () {
  40633. return stream[method].apply(stream, arguments);
  40634. };
  40635. }(i);
  40636. }
  40637. }
  40638. // proxy certain important events.
  40639. for (var n = 0; n < kProxyEvents.length; n++) {
  40640. stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
  40641. }
  40642. // when we try to consume some more bytes, simply unpause the
  40643. // underlying stream.
  40644. self._read = function (n) {
  40645. debug('wrapped _read', n);
  40646. if (paused) {
  40647. paused = false;
  40648. stream.resume();
  40649. }
  40650. };
  40651. return self;
  40652. };
  40653. // exposed for testing purposes only.
  40654. Readable._fromList = fromList;
  40655. // Pluck off n bytes from an array of buffers.
  40656. // Length is the combined lengths of all the buffers in the list.
  40657. // This function is designed to be inlinable, so please take care when making
  40658. // changes to the function body.
  40659. function fromList(n, state) {
  40660. // nothing buffered
  40661. if (state.length === 0) return null;
  40662. var ret;
  40663. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  40664. // read it all, truncate the list
  40665. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  40666. state.buffer.clear();
  40667. } else {
  40668. // read part of list
  40669. ret = fromListPartial(n, state.buffer, state.decoder);
  40670. }
  40671. return ret;
  40672. }
  40673. // Extracts only enough buffered data to satisfy the amount requested.
  40674. // This function is designed to be inlinable, so please take care when making
  40675. // changes to the function body.
  40676. function fromListPartial(n, list, hasStrings) {
  40677. var ret;
  40678. if (n < list.head.data.length) {
  40679. // slice is the same for buffers and strings
  40680. ret = list.head.data.slice(0, n);
  40681. list.head.data = list.head.data.slice(n);
  40682. } else if (n === list.head.data.length) {
  40683. // first chunk is a perfect match
  40684. ret = list.shift();
  40685. } else {
  40686. // result spans more than one buffer
  40687. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  40688. }
  40689. return ret;
  40690. }
  40691. // Copies a specified amount of characters from the list of buffered data
  40692. // chunks.
  40693. // This function is designed to be inlinable, so please take care when making
  40694. // changes to the function body.
  40695. function copyFromBufferString(n, list) {
  40696. var p = list.head;
  40697. var c = 1;
  40698. var ret = p.data;
  40699. n -= ret.length;
  40700. while (p = p.next) {
  40701. var str = p.data;
  40702. var nb = n > str.length ? str.length : n;
  40703. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  40704. n -= nb;
  40705. if (n === 0) {
  40706. if (nb === str.length) {
  40707. ++c;
  40708. if (p.next) list.head = p.next;else list.head = list.tail = null;
  40709. } else {
  40710. list.head = p;
  40711. p.data = str.slice(nb);
  40712. }
  40713. break;
  40714. }
  40715. ++c;
  40716. }
  40717. list.length -= c;
  40718. return ret;
  40719. }
  40720. // Copies a specified amount of bytes from the list of buffered data chunks.
  40721. // This function is designed to be inlinable, so please take care when making
  40722. // changes to the function body.
  40723. function copyFromBuffer(n, list) {
  40724. var ret = Buffer.allocUnsafe(n);
  40725. var p = list.head;
  40726. var c = 1;
  40727. p.data.copy(ret);
  40728. n -= p.data.length;
  40729. while (p = p.next) {
  40730. var buf = p.data;
  40731. var nb = n > buf.length ? buf.length : n;
  40732. buf.copy(ret, ret.length - n, 0, nb);
  40733. n -= nb;
  40734. if (n === 0) {
  40735. if (nb === buf.length) {
  40736. ++c;
  40737. if (p.next) list.head = p.next;else list.head = list.tail = null;
  40738. } else {
  40739. list.head = p;
  40740. p.data = buf.slice(nb);
  40741. }
  40742. break;
  40743. }
  40744. ++c;
  40745. }
  40746. list.length -= c;
  40747. return ret;
  40748. }
  40749. function endReadable(stream) {
  40750. var state = stream._readableState;
  40751. // If we get here before consuming all the bytes, then that is a
  40752. // bug in node. Should never happen.
  40753. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  40754. if (!state.endEmitted) {
  40755. state.ended = true;
  40756. processNextTick(endReadableNT, state, stream);
  40757. }
  40758. }
  40759. function endReadableNT(state, stream) {
  40760. // Check that we didn't get one last unshift.
  40761. if (!state.endEmitted && state.length === 0) {
  40762. state.endEmitted = true;
  40763. stream.readable = false;
  40764. stream.emit('end');
  40765. }
  40766. }
  40767. function forEach(xs, f) {
  40768. for (var i = 0, l = xs.length; i < l; i++) {
  40769. f(xs[i], i);
  40770. }
  40771. }
  40772. function indexOf(xs, x) {
  40773. for (var i = 0, l = xs.length; i < l; i++) {
  40774. if (xs[i] === x) return i;
  40775. }
  40776. return -1;
  40777. }
  40778. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  40779. },{"./_stream_duplex":136,"./internal/streams/BufferList":141,"./internal/streams/destroy":142,"./internal/streams/stream":143,"_process":125,"core-util-is":38,"events":33,"inherits":121,"isarray":135,"process-nextick-args":124,"safe-buffer":130,"string_decoder/":145,"util":29}],139:[function(require,module,exports){
  40780. // Copyright Joyent, Inc. and other Node contributors.
  40781. //
  40782. // Permission is hereby granted, free of charge, to any person obtaining a
  40783. // copy of this software and associated documentation files (the
  40784. // "Software"), to deal in the Software without restriction, including
  40785. // without limitation the rights to use, copy, modify, merge, publish,
  40786. // distribute, sublicense, and/or sell copies of the Software, and to permit
  40787. // persons to whom the Software is furnished to do so, subject to the
  40788. // following conditions:
  40789. //
  40790. // The above copyright notice and this permission notice shall be included
  40791. // in all copies or substantial portions of the Software.
  40792. //
  40793. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  40794. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  40795. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  40796. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  40797. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  40798. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  40799. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  40800. // a transform stream is a readable/writable stream where you do
  40801. // something with the data. Sometimes it's called a "filter",
  40802. // but that's not a great name for it, since that implies a thing where
  40803. // some bits pass through, and others are simply ignored. (That would
  40804. // be a valid example of a transform, of course.)
  40805. //
  40806. // While the output is causally related to the input, it's not a
  40807. // necessarily symmetric or synchronous transformation. For example,
  40808. // a zlib stream might take multiple plain-text writes(), and then
  40809. // emit a single compressed chunk some time in the future.
  40810. //
  40811. // Here's how this works:
  40812. //
  40813. // The Transform stream has all the aspects of the readable and writable
  40814. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  40815. // internally, and returns false if there's a lot of pending writes
  40816. // buffered up. When you call read(), that calls _read(n) until
  40817. // there's enough pending readable data buffered up.
  40818. //
  40819. // In a transform stream, the written data is placed in a buffer. When
  40820. // _read(n) is called, it transforms the queued up data, calling the
  40821. // buffered _write cb's as it consumes chunks. If consuming a single
  40822. // written chunk would result in multiple output chunks, then the first
  40823. // outputted bit calls the readcb, and subsequent chunks just go into
  40824. // the read buffer, and will cause it to emit 'readable' if necessary.
  40825. //
  40826. // This way, back-pressure is actually determined by the reading side,
  40827. // since _read has to be called to start processing a new chunk. However,
  40828. // a pathological inflate type of transform can cause excessive buffering
  40829. // here. For example, imagine a stream where every byte of input is
  40830. // interpreted as an integer from 0-255, and then results in that many
  40831. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  40832. // 1kb of data being output. In this case, you could write a very small
  40833. // amount of input, and end up with a very large amount of output. In
  40834. // such a pathological inflating mechanism, there'd be no way to tell
  40835. // the system to stop doing the transform. A single 4MB write could
  40836. // cause the system to run out of memory.
  40837. //
  40838. // However, even in such a pathological case, only a single written chunk
  40839. // would be consumed, and then the rest would wait (un-transformed) until
  40840. // the results of the previous transformed chunk were consumed.
  40841. 'use strict';
  40842. module.exports = Transform;
  40843. var Duplex = require('./_stream_duplex');
  40844. /*<replacement>*/
  40845. var util = require('core-util-is');
  40846. util.inherits = require('inherits');
  40847. /*</replacement>*/
  40848. util.inherits(Transform, Duplex);
  40849. function TransformState(stream) {
  40850. this.afterTransform = function (er, data) {
  40851. return afterTransform(stream, er, data);
  40852. };
  40853. this.needTransform = false;
  40854. this.transforming = false;
  40855. this.writecb = null;
  40856. this.writechunk = null;
  40857. this.writeencoding = null;
  40858. }
  40859. function afterTransform(stream, er, data) {
  40860. var ts = stream._transformState;
  40861. ts.transforming = false;
  40862. var cb = ts.writecb;
  40863. if (!cb) {
  40864. return stream.emit('error', new Error('write callback called multiple times'));
  40865. }
  40866. ts.writechunk = null;
  40867. ts.writecb = null;
  40868. if (data !== null && data !== undefined) stream.push(data);
  40869. cb(er);
  40870. var rs = stream._readableState;
  40871. rs.reading = false;
  40872. if (rs.needReadable || rs.length < rs.highWaterMark) {
  40873. stream._read(rs.highWaterMark);
  40874. }
  40875. }
  40876. function Transform(options) {
  40877. if (!(this instanceof Transform)) return new Transform(options);
  40878. Duplex.call(this, options);
  40879. this._transformState = new TransformState(this);
  40880. var stream = this;
  40881. // start out asking for a readable event once data is transformed.
  40882. this._readableState.needReadable = true;
  40883. // we have implemented the _read method, and done the other things
  40884. // that Readable wants before the first _read call, so unset the
  40885. // sync guard flag.
  40886. this._readableState.sync = false;
  40887. if (options) {
  40888. if (typeof options.transform === 'function') this._transform = options.transform;
  40889. if (typeof options.flush === 'function') this._flush = options.flush;
  40890. }
  40891. // When the writable side finishes, then flush out anything remaining.
  40892. this.once('prefinish', function () {
  40893. if (typeof this._flush === 'function') this._flush(function (er, data) {
  40894. done(stream, er, data);
  40895. });else done(stream);
  40896. });
  40897. }
  40898. Transform.prototype.push = function (chunk, encoding) {
  40899. this._transformState.needTransform = false;
  40900. return Duplex.prototype.push.call(this, chunk, encoding);
  40901. };
  40902. // This is the part where you do stuff!
  40903. // override this function in implementation classes.
  40904. // 'chunk' is an input chunk.
  40905. //
  40906. // Call `push(newChunk)` to pass along transformed output
  40907. // to the readable side. You may call 'push' zero or more times.
  40908. //
  40909. // Call `cb(err)` when you are done with this chunk. If you pass
  40910. // an error, then that'll put the hurt on the whole operation. If you
  40911. // never call cb(), then you'll never get another chunk.
  40912. Transform.prototype._transform = function (chunk, encoding, cb) {
  40913. throw new Error('_transform() is not implemented');
  40914. };
  40915. Transform.prototype._write = function (chunk, encoding, cb) {
  40916. var ts = this._transformState;
  40917. ts.writecb = cb;
  40918. ts.writechunk = chunk;
  40919. ts.writeencoding = encoding;
  40920. if (!ts.transforming) {
  40921. var rs = this._readableState;
  40922. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  40923. }
  40924. };
  40925. // Doesn't matter what the args are here.
  40926. // _transform does all the work.
  40927. // That we got here means that the readable side wants more data.
  40928. Transform.prototype._read = function (n) {
  40929. var ts = this._transformState;
  40930. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  40931. ts.transforming = true;
  40932. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  40933. } else {
  40934. // mark that we need a transform, so that any data that comes in
  40935. // will get processed, now that we've asked for it.
  40936. ts.needTransform = true;
  40937. }
  40938. };
  40939. Transform.prototype._destroy = function (err, cb) {
  40940. var _this = this;
  40941. Duplex.prototype._destroy.call(this, err, function (err2) {
  40942. cb(err2);
  40943. _this.emit('close');
  40944. });
  40945. };
  40946. function done(stream, er, data) {
  40947. if (er) return stream.emit('error', er);
  40948. if (data !== null && data !== undefined) stream.push(data);
  40949. // if there's nothing in the write buffer, then that means
  40950. // that nothing more will ever be provided
  40951. var ws = stream._writableState;
  40952. var ts = stream._transformState;
  40953. if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  40954. if (ts.transforming) throw new Error('Calling transform done when still transforming');
  40955. return stream.push(null);
  40956. }
  40957. },{"./_stream_duplex":136,"core-util-is":38,"inherits":121}],140:[function(require,module,exports){
  40958. (function (process,global){
  40959. // Copyright Joyent, Inc. and other Node contributors.
  40960. //
  40961. // Permission is hereby granted, free of charge, to any person obtaining a
  40962. // copy of this software and associated documentation files (the
  40963. // "Software"), to deal in the Software without restriction, including
  40964. // without limitation the rights to use, copy, modify, merge, publish,
  40965. // distribute, sublicense, and/or sell copies of the Software, and to permit
  40966. // persons to whom the Software is furnished to do so, subject to the
  40967. // following conditions:
  40968. //
  40969. // The above copyright notice and this permission notice shall be included
  40970. // in all copies or substantial portions of the Software.
  40971. //
  40972. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  40973. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  40974. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  40975. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  40976. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  40977. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  40978. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  40979. // A bit simpler than readable streams.
  40980. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  40981. // the drain event emission and buffering.
  40982. 'use strict';
  40983. /*<replacement>*/
  40984. var processNextTick = require('process-nextick-args');
  40985. /*</replacement>*/
  40986. module.exports = Writable;
  40987. /* <replacement> */
  40988. function WriteReq(chunk, encoding, cb) {
  40989. this.chunk = chunk;
  40990. this.encoding = encoding;
  40991. this.callback = cb;
  40992. this.next = null;
  40993. }
  40994. // It seems a linked list but it is not
  40995. // there will be only 2 of these for each stream
  40996. function CorkedRequest(state) {
  40997. var _this = this;
  40998. this.next = null;
  40999. this.entry = null;
  41000. this.finish = function () {
  41001. onCorkedFinish(_this, state);
  41002. };
  41003. }
  41004. /* </replacement> */
  41005. /*<replacement>*/
  41006. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
  41007. /*</replacement>*/
  41008. /*<replacement>*/
  41009. var Duplex;
  41010. /*</replacement>*/
  41011. Writable.WritableState = WritableState;
  41012. /*<replacement>*/
  41013. var util = require('core-util-is');
  41014. util.inherits = require('inherits');
  41015. /*</replacement>*/
  41016. /*<replacement>*/
  41017. var internalUtil = {
  41018. deprecate: require('util-deprecate')
  41019. };
  41020. /*</replacement>*/
  41021. /*<replacement>*/
  41022. var Stream = require('./internal/streams/stream');
  41023. /*</replacement>*/
  41024. /*<replacement>*/
  41025. var Buffer = require('safe-buffer').Buffer;
  41026. var OurUint8Array = global.Uint8Array || function () {};
  41027. function _uint8ArrayToBuffer(chunk) {
  41028. return Buffer.from(chunk);
  41029. }
  41030. function _isUint8Array(obj) {
  41031. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  41032. }
  41033. /*</replacement>*/
  41034. var destroyImpl = require('./internal/streams/destroy');
  41035. util.inherits(Writable, Stream);
  41036. function nop() {}
  41037. function WritableState(options, stream) {
  41038. Duplex = Duplex || require('./_stream_duplex');
  41039. options = options || {};
  41040. // object stream flag to indicate whether or not this stream
  41041. // contains buffers or objects.
  41042. this.objectMode = !!options.objectMode;
  41043. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  41044. // the point at which write() starts returning false
  41045. // Note: 0 is a valid value, means that we always return false if
  41046. // the entire buffer is not flushed immediately on write()
  41047. var hwm = options.highWaterMark;
  41048. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  41049. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  41050. // cast to ints.
  41051. this.highWaterMark = Math.floor(this.highWaterMark);
  41052. // if _final has been called
  41053. this.finalCalled = false;
  41054. // drain event flag.
  41055. this.needDrain = false;
  41056. // at the start of calling end()
  41057. this.ending = false;
  41058. // when end() has been called, and returned
  41059. this.ended = false;
  41060. // when 'finish' is emitted
  41061. this.finished = false;
  41062. // has it been destroyed
  41063. this.destroyed = false;
  41064. // should we decode strings into buffers before passing to _write?
  41065. // this is here so that some node-core streams can optimize string
  41066. // handling at a lower level.
  41067. var noDecode = options.decodeStrings === false;
  41068. this.decodeStrings = !noDecode;
  41069. // Crypto is kind of old and crusty. Historically, its default string
  41070. // encoding is 'binary' so we have to make this configurable.
  41071. // Everything else in the universe uses 'utf8', though.
  41072. this.defaultEncoding = options.defaultEncoding || 'utf8';
  41073. // not an actual buffer we keep track of, but a measurement
  41074. // of how much we're waiting to get pushed to some underlying
  41075. // socket or file.
  41076. this.length = 0;
  41077. // a flag to see when we're in the middle of a write.
  41078. this.writing = false;
  41079. // when true all writes will be buffered until .uncork() call
  41080. this.corked = 0;
  41081. // a flag to be able to tell if the onwrite cb is called immediately,
  41082. // or on a later tick. We set this to true at first, because any
  41083. // actions that shouldn't happen until "later" should generally also
  41084. // not happen before the first write call.
  41085. this.sync = true;
  41086. // a flag to know if we're processing previously buffered items, which
  41087. // may call the _write() callback in the same tick, so that we don't
  41088. // end up in an overlapped onwrite situation.
  41089. this.bufferProcessing = false;
  41090. // the callback that's passed to _write(chunk,cb)
  41091. this.onwrite = function (er) {
  41092. onwrite(stream, er);
  41093. };
  41094. // the callback that the user supplies to write(chunk,encoding,cb)
  41095. this.writecb = null;
  41096. // the amount that is being written when _write is called.
  41097. this.writelen = 0;
  41098. this.bufferedRequest = null;
  41099. this.lastBufferedRequest = null;
  41100. // number of pending user-supplied write callbacks
  41101. // this must be 0 before 'finish' can be emitted
  41102. this.pendingcb = 0;
  41103. // emit prefinish if the only thing we're waiting for is _write cbs
  41104. // This is relevant for synchronous Transform streams
  41105. this.prefinished = false;
  41106. // True if the error was already emitted and should not be thrown again
  41107. this.errorEmitted = false;
  41108. // count buffered requests
  41109. this.bufferedRequestCount = 0;
  41110. // allocate the first CorkedRequest, there is always
  41111. // one allocated and free to use, and we maintain at most two
  41112. this.corkedRequestsFree = new CorkedRequest(this);
  41113. }
  41114. WritableState.prototype.getBuffer = function getBuffer() {
  41115. var current = this.bufferedRequest;
  41116. var out = [];
  41117. while (current) {
  41118. out.push(current);
  41119. current = current.next;
  41120. }
  41121. return out;
  41122. };
  41123. (function () {
  41124. try {
  41125. Object.defineProperty(WritableState.prototype, 'buffer', {
  41126. get: internalUtil.deprecate(function () {
  41127. return this.getBuffer();
  41128. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  41129. });
  41130. } catch (_) {}
  41131. })();
  41132. // Test _writableState for inheritance to account for Duplex streams,
  41133. // whose prototype chain only points to Readable.
  41134. var realHasInstance;
  41135. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  41136. realHasInstance = Function.prototype[Symbol.hasInstance];
  41137. Object.defineProperty(Writable, Symbol.hasInstance, {
  41138. value: function (object) {
  41139. if (realHasInstance.call(this, object)) return true;
  41140. return object && object._writableState instanceof WritableState;
  41141. }
  41142. });
  41143. } else {
  41144. realHasInstance = function (object) {
  41145. return object instanceof this;
  41146. };
  41147. }
  41148. function Writable(options) {
  41149. Duplex = Duplex || require('./_stream_duplex');
  41150. // Writable ctor is applied to Duplexes, too.
  41151. // `realHasInstance` is necessary because using plain `instanceof`
  41152. // would return false, as no `_writableState` property is attached.
  41153. // Trying to use the custom `instanceof` for Writable here will also break the
  41154. // Node.js LazyTransform implementation, which has a non-trivial getter for
  41155. // `_writableState` that would lead to infinite recursion.
  41156. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  41157. return new Writable(options);
  41158. }
  41159. this._writableState = new WritableState(options, this);
  41160. // legacy.
  41161. this.writable = true;
  41162. if (options) {
  41163. if (typeof options.write === 'function') this._write = options.write;
  41164. if (typeof options.writev === 'function') this._writev = options.writev;
  41165. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  41166. if (typeof options.final === 'function') this._final = options.final;
  41167. }
  41168. Stream.call(this);
  41169. }
  41170. // Otherwise people can pipe Writable streams, which is just wrong.
  41171. Writable.prototype.pipe = function () {
  41172. this.emit('error', new Error('Cannot pipe, not readable'));
  41173. };
  41174. function writeAfterEnd(stream, cb) {
  41175. var er = new Error('write after end');
  41176. // TODO: defer error events consistently everywhere, not just the cb
  41177. stream.emit('error', er);
  41178. processNextTick(cb, er);
  41179. }
  41180. // Checks that a user-supplied chunk is valid, especially for the particular
  41181. // mode the stream is in. Currently this means that `null` is never accepted
  41182. // and undefined/non-string values are only allowed in object mode.
  41183. function validChunk(stream, state, chunk, cb) {
  41184. var valid = true;
  41185. var er = false;
  41186. if (chunk === null) {
  41187. er = new TypeError('May not write null values to stream');
  41188. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  41189. er = new TypeError('Invalid non-string/buffer chunk');
  41190. }
  41191. if (er) {
  41192. stream.emit('error', er);
  41193. processNextTick(cb, er);
  41194. valid = false;
  41195. }
  41196. return valid;
  41197. }
  41198. Writable.prototype.write = function (chunk, encoding, cb) {
  41199. var state = this._writableState;
  41200. var ret = false;
  41201. var isBuf = _isUint8Array(chunk) && !state.objectMode;
  41202. if (isBuf && !Buffer.isBuffer(chunk)) {
  41203. chunk = _uint8ArrayToBuffer(chunk);
  41204. }
  41205. if (typeof encoding === 'function') {
  41206. cb = encoding;
  41207. encoding = null;
  41208. }
  41209. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  41210. if (typeof cb !== 'function') cb = nop;
  41211. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  41212. state.pendingcb++;
  41213. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  41214. }
  41215. return ret;
  41216. };
  41217. Writable.prototype.cork = function () {
  41218. var state = this._writableState;
  41219. state.corked++;
  41220. };
  41221. Writable.prototype.uncork = function () {
  41222. var state = this._writableState;
  41223. if (state.corked) {
  41224. state.corked--;
  41225. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  41226. }
  41227. };
  41228. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  41229. // node::ParseEncoding() requires lower case.
  41230. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  41231. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  41232. this._writableState.defaultEncoding = encoding;
  41233. return this;
  41234. };
  41235. function decodeChunk(state, chunk, encoding) {
  41236. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  41237. chunk = Buffer.from(chunk, encoding);
  41238. }
  41239. return chunk;
  41240. }
  41241. // if we're already writing something, then just put this
  41242. // in the queue, and wait our turn. Otherwise, call _write
  41243. // If we return false, then we need a drain event, so set that flag.
  41244. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  41245. if (!isBuf) {
  41246. var newChunk = decodeChunk(state, chunk, encoding);
  41247. if (chunk !== newChunk) {
  41248. isBuf = true;
  41249. encoding = 'buffer';
  41250. chunk = newChunk;
  41251. }
  41252. }
  41253. var len = state.objectMode ? 1 : chunk.length;
  41254. state.length += len;
  41255. var ret = state.length < state.highWaterMark;
  41256. // we must ensure that previous needDrain will not be reset to false.
  41257. if (!ret) state.needDrain = true;
  41258. if (state.writing || state.corked) {
  41259. var last = state.lastBufferedRequest;
  41260. state.lastBufferedRequest = {
  41261. chunk: chunk,
  41262. encoding: encoding,
  41263. isBuf: isBuf,
  41264. callback: cb,
  41265. next: null
  41266. };
  41267. if (last) {
  41268. last.next = state.lastBufferedRequest;
  41269. } else {
  41270. state.bufferedRequest = state.lastBufferedRequest;
  41271. }
  41272. state.bufferedRequestCount += 1;
  41273. } else {
  41274. doWrite(stream, state, false, len, chunk, encoding, cb);
  41275. }
  41276. return ret;
  41277. }
  41278. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  41279. state.writelen = len;
  41280. state.writecb = cb;
  41281. state.writing = true;
  41282. state.sync = true;
  41283. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  41284. state.sync = false;
  41285. }
  41286. function onwriteError(stream, state, sync, er, cb) {
  41287. --state.pendingcb;
  41288. if (sync) {
  41289. // defer the callback if we are being called synchronously
  41290. // to avoid piling up things on the stack
  41291. processNextTick(cb, er);
  41292. // this can emit finish, and it will always happen
  41293. // after error
  41294. processNextTick(finishMaybe, stream, state);
  41295. stream._writableState.errorEmitted = true;
  41296. stream.emit('error', er);
  41297. } else {
  41298. // the caller expect this to happen before if
  41299. // it is async
  41300. cb(er);
  41301. stream._writableState.errorEmitted = true;
  41302. stream.emit('error', er);
  41303. // this can emit finish, but finish must
  41304. // always follow error
  41305. finishMaybe(stream, state);
  41306. }
  41307. }
  41308. function onwriteStateUpdate(state) {
  41309. state.writing = false;
  41310. state.writecb = null;
  41311. state.length -= state.writelen;
  41312. state.writelen = 0;
  41313. }
  41314. function onwrite(stream, er) {
  41315. var state = stream._writableState;
  41316. var sync = state.sync;
  41317. var cb = state.writecb;
  41318. onwriteStateUpdate(state);
  41319. if (er) onwriteError(stream, state, sync, er, cb);else {
  41320. // Check if we're actually ready to finish, but don't emit yet
  41321. var finished = needFinish(state);
  41322. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  41323. clearBuffer(stream, state);
  41324. }
  41325. if (sync) {
  41326. /*<replacement>*/
  41327. asyncWrite(afterWrite, stream, state, finished, cb);
  41328. /*</replacement>*/
  41329. } else {
  41330. afterWrite(stream, state, finished, cb);
  41331. }
  41332. }
  41333. }
  41334. function afterWrite(stream, state, finished, cb) {
  41335. if (!finished) onwriteDrain(stream, state);
  41336. state.pendingcb--;
  41337. cb();
  41338. finishMaybe(stream, state);
  41339. }
  41340. // Must force callback to be called on nextTick, so that we don't
  41341. // emit 'drain' before the write() consumer gets the 'false' return
  41342. // value, and has a chance to attach a 'drain' listener.
  41343. function onwriteDrain(stream, state) {
  41344. if (state.length === 0 && state.needDrain) {
  41345. state.needDrain = false;
  41346. stream.emit('drain');
  41347. }
  41348. }
  41349. // if there's something in the buffer waiting, then process it
  41350. function clearBuffer(stream, state) {
  41351. state.bufferProcessing = true;
  41352. var entry = state.bufferedRequest;
  41353. if (stream._writev && entry && entry.next) {
  41354. // Fast case, write everything using _writev()
  41355. var l = state.bufferedRequestCount;
  41356. var buffer = new Array(l);
  41357. var holder = state.corkedRequestsFree;
  41358. holder.entry = entry;
  41359. var count = 0;
  41360. var allBuffers = true;
  41361. while (entry) {
  41362. buffer[count] = entry;
  41363. if (!entry.isBuf) allBuffers = false;
  41364. entry = entry.next;
  41365. count += 1;
  41366. }
  41367. buffer.allBuffers = allBuffers;
  41368. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  41369. // doWrite is almost always async, defer these to save a bit of time
  41370. // as the hot path ends with doWrite
  41371. state.pendingcb++;
  41372. state.lastBufferedRequest = null;
  41373. if (holder.next) {
  41374. state.corkedRequestsFree = holder.next;
  41375. holder.next = null;
  41376. } else {
  41377. state.corkedRequestsFree = new CorkedRequest(state);
  41378. }
  41379. } else {
  41380. // Slow case, write chunks one-by-one
  41381. while (entry) {
  41382. var chunk = entry.chunk;
  41383. var encoding = entry.encoding;
  41384. var cb = entry.callback;
  41385. var len = state.objectMode ? 1 : chunk.length;
  41386. doWrite(stream, state, false, len, chunk, encoding, cb);
  41387. entry = entry.next;
  41388. // if we didn't call the onwrite immediately, then
  41389. // it means that we need to wait until it does.
  41390. // also, that means that the chunk and cb are currently
  41391. // being processed, so move the buffer counter past them.
  41392. if (state.writing) {
  41393. break;
  41394. }
  41395. }
  41396. if (entry === null) state.lastBufferedRequest = null;
  41397. }
  41398. state.bufferedRequestCount = 0;
  41399. state.bufferedRequest = entry;
  41400. state.bufferProcessing = false;
  41401. }
  41402. Writable.prototype._write = function (chunk, encoding, cb) {
  41403. cb(new Error('_write() is not implemented'));
  41404. };
  41405. Writable.prototype._writev = null;
  41406. Writable.prototype.end = function (chunk, encoding, cb) {
  41407. var state = this._writableState;
  41408. if (typeof chunk === 'function') {
  41409. cb = chunk;
  41410. chunk = null;
  41411. encoding = null;
  41412. } else if (typeof encoding === 'function') {
  41413. cb = encoding;
  41414. encoding = null;
  41415. }
  41416. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  41417. // .end() fully uncorks
  41418. if (state.corked) {
  41419. state.corked = 1;
  41420. this.uncork();
  41421. }
  41422. // ignore unnecessary end() calls.
  41423. if (!state.ending && !state.finished) endWritable(this, state, cb);
  41424. };
  41425. function needFinish(state) {
  41426. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  41427. }
  41428. function callFinal(stream, state) {
  41429. stream._final(function (err) {
  41430. state.pendingcb--;
  41431. if (err) {
  41432. stream.emit('error', err);
  41433. }
  41434. state.prefinished = true;
  41435. stream.emit('prefinish');
  41436. finishMaybe(stream, state);
  41437. });
  41438. }
  41439. function prefinish(stream, state) {
  41440. if (!state.prefinished && !state.finalCalled) {
  41441. if (typeof stream._final === 'function') {
  41442. state.pendingcb++;
  41443. state.finalCalled = true;
  41444. processNextTick(callFinal, stream, state);
  41445. } else {
  41446. state.prefinished = true;
  41447. stream.emit('prefinish');
  41448. }
  41449. }
  41450. }
  41451. function finishMaybe(stream, state) {
  41452. var need = needFinish(state);
  41453. if (need) {
  41454. prefinish(stream, state);
  41455. if (state.pendingcb === 0) {
  41456. state.finished = true;
  41457. stream.emit('finish');
  41458. }
  41459. }
  41460. return need;
  41461. }
  41462. function endWritable(stream, state, cb) {
  41463. state.ending = true;
  41464. finishMaybe(stream, state);
  41465. if (cb) {
  41466. if (state.finished) processNextTick(cb);else stream.once('finish', cb);
  41467. }
  41468. state.ended = true;
  41469. stream.writable = false;
  41470. }
  41471. function onCorkedFinish(corkReq, state, err) {
  41472. var entry = corkReq.entry;
  41473. corkReq.entry = null;
  41474. while (entry) {
  41475. var cb = entry.callback;
  41476. state.pendingcb--;
  41477. cb(err);
  41478. entry = entry.next;
  41479. }
  41480. if (state.corkedRequestsFree) {
  41481. state.corkedRequestsFree.next = corkReq;
  41482. } else {
  41483. state.corkedRequestsFree = corkReq;
  41484. }
  41485. }
  41486. Object.defineProperty(Writable.prototype, 'destroyed', {
  41487. get: function () {
  41488. if (this._writableState === undefined) {
  41489. return false;
  41490. }
  41491. return this._writableState.destroyed;
  41492. },
  41493. set: function (value) {
  41494. // we ignore the value if the stream
  41495. // has not been initialized yet
  41496. if (!this._writableState) {
  41497. return;
  41498. }
  41499. // backward compatibility, the user is explicitly
  41500. // managing destroyed
  41501. this._writableState.destroyed = value;
  41502. }
  41503. });
  41504. Writable.prototype.destroy = destroyImpl.destroy;
  41505. Writable.prototype._undestroy = destroyImpl.undestroy;
  41506. Writable.prototype._destroy = function (err, cb) {
  41507. this.end();
  41508. cb(err);
  41509. };
  41510. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  41511. },{"./_stream_duplex":136,"./internal/streams/destroy":142,"./internal/streams/stream":143,"_process":125,"core-util-is":38,"inherits":121,"process-nextick-args":124,"safe-buffer":130,"util-deprecate":147}],141:[function(require,module,exports){
  41512. 'use strict';
  41513. /*<replacement>*/
  41514. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  41515. var Buffer = require('safe-buffer').Buffer;
  41516. /*</replacement>*/
  41517. function copyBuffer(src, target, offset) {
  41518. src.copy(target, offset);
  41519. }
  41520. module.exports = function () {
  41521. function BufferList() {
  41522. _classCallCheck(this, BufferList);
  41523. this.head = null;
  41524. this.tail = null;
  41525. this.length = 0;
  41526. }
  41527. BufferList.prototype.push = function push(v) {
  41528. var entry = { data: v, next: null };
  41529. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  41530. this.tail = entry;
  41531. ++this.length;
  41532. };
  41533. BufferList.prototype.unshift = function unshift(v) {
  41534. var entry = { data: v, next: this.head };
  41535. if (this.length === 0) this.tail = entry;
  41536. this.head = entry;
  41537. ++this.length;
  41538. };
  41539. BufferList.prototype.shift = function shift() {
  41540. if (this.length === 0) return;
  41541. var ret = this.head.data;
  41542. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  41543. --this.length;
  41544. return ret;
  41545. };
  41546. BufferList.prototype.clear = function clear() {
  41547. this.head = this.tail = null;
  41548. this.length = 0;
  41549. };
  41550. BufferList.prototype.join = function join(s) {
  41551. if (this.length === 0) return '';
  41552. var p = this.head;
  41553. var ret = '' + p.data;
  41554. while (p = p.next) {
  41555. ret += s + p.data;
  41556. }return ret;
  41557. };
  41558. BufferList.prototype.concat = function concat(n) {
  41559. if (this.length === 0) return Buffer.alloc(0);
  41560. if (this.length === 1) return this.head.data;
  41561. var ret = Buffer.allocUnsafe(n >>> 0);
  41562. var p = this.head;
  41563. var i = 0;
  41564. while (p) {
  41565. copyBuffer(p.data, ret, i);
  41566. i += p.data.length;
  41567. p = p.next;
  41568. }
  41569. return ret;
  41570. };
  41571. return BufferList;
  41572. }();
  41573. },{"safe-buffer":130}],142:[function(require,module,exports){
  41574. 'use strict';
  41575. /*<replacement>*/
  41576. var processNextTick = require('process-nextick-args');
  41577. /*</replacement>*/
  41578. // undocumented cb() API, needed for core, not for public API
  41579. function destroy(err, cb) {
  41580. var _this = this;
  41581. var readableDestroyed = this._readableState && this._readableState.destroyed;
  41582. var writableDestroyed = this._writableState && this._writableState.destroyed;
  41583. if (readableDestroyed || writableDestroyed) {
  41584. if (cb) {
  41585. cb(err);
  41586. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  41587. processNextTick(emitErrorNT, this, err);
  41588. }
  41589. return;
  41590. }
  41591. // we set destroyed to true before firing error callbacks in order
  41592. // to make it re-entrance safe in case destroy() is called within callbacks
  41593. if (this._readableState) {
  41594. this._readableState.destroyed = true;
  41595. }
  41596. // if this is a duplex stream mark the writable part as destroyed as well
  41597. if (this._writableState) {
  41598. this._writableState.destroyed = true;
  41599. }
  41600. this._destroy(err || null, function (err) {
  41601. if (!cb && err) {
  41602. processNextTick(emitErrorNT, _this, err);
  41603. if (_this._writableState) {
  41604. _this._writableState.errorEmitted = true;
  41605. }
  41606. } else if (cb) {
  41607. cb(err);
  41608. }
  41609. });
  41610. }
  41611. function undestroy() {
  41612. if (this._readableState) {
  41613. this._readableState.destroyed = false;
  41614. this._readableState.reading = false;
  41615. this._readableState.ended = false;
  41616. this._readableState.endEmitted = false;
  41617. }
  41618. if (this._writableState) {
  41619. this._writableState.destroyed = false;
  41620. this._writableState.ended = false;
  41621. this._writableState.ending = false;
  41622. this._writableState.finished = false;
  41623. this._writableState.errorEmitted = false;
  41624. }
  41625. }
  41626. function emitErrorNT(self, err) {
  41627. self.emit('error', err);
  41628. }
  41629. module.exports = {
  41630. destroy: destroy,
  41631. undestroy: undestroy
  41632. };
  41633. },{"process-nextick-args":124}],143:[function(require,module,exports){
  41634. module.exports = require('events').EventEmitter;
  41635. },{"events":33}],144:[function(require,module,exports){
  41636. exports = module.exports = require('./lib/_stream_readable.js');
  41637. exports.Stream = exports;
  41638. exports.Readable = exports;
  41639. exports.Writable = require('./lib/_stream_writable.js');
  41640. exports.Duplex = require('./lib/_stream_duplex.js');
  41641. exports.Transform = require('./lib/_stream_transform.js');
  41642. exports.PassThrough = require('./lib/_stream_passthrough.js');
  41643. },{"./lib/_stream_duplex.js":136,"./lib/_stream_passthrough.js":137,"./lib/_stream_readable.js":138,"./lib/_stream_transform.js":139,"./lib/_stream_writable.js":140}],145:[function(require,module,exports){
  41644. 'use strict';
  41645. var Buffer = require('safe-buffer').Buffer;
  41646. var isEncoding = Buffer.isEncoding || function (encoding) {
  41647. encoding = '' + encoding;
  41648. switch (encoding && encoding.toLowerCase()) {
  41649. case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
  41650. return true;
  41651. default:
  41652. return false;
  41653. }
  41654. };
  41655. function _normalizeEncoding(enc) {
  41656. if (!enc) return 'utf8';
  41657. var retried;
  41658. while (true) {
  41659. switch (enc) {
  41660. case 'utf8':
  41661. case 'utf-8':
  41662. return 'utf8';
  41663. case 'ucs2':
  41664. case 'ucs-2':
  41665. case 'utf16le':
  41666. case 'utf-16le':
  41667. return 'utf16le';
  41668. case 'latin1':
  41669. case 'binary':
  41670. return 'latin1';
  41671. case 'base64':
  41672. case 'ascii':
  41673. case 'hex':
  41674. return enc;
  41675. default:
  41676. if (retried) return; // undefined
  41677. enc = ('' + enc).toLowerCase();
  41678. retried = true;
  41679. }
  41680. }
  41681. };
  41682. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  41683. // modules monkey-patch it to support additional encodings
  41684. function normalizeEncoding(enc) {
  41685. var nenc = _normalizeEncoding(enc);
  41686. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  41687. return nenc || enc;
  41688. }
  41689. // StringDecoder provides an interface for efficiently splitting a series of
  41690. // buffers into a series of JS strings without breaking apart multi-byte
  41691. // characters.
  41692. exports.StringDecoder = StringDecoder;
  41693. function StringDecoder(encoding) {
  41694. this.encoding = normalizeEncoding(encoding);
  41695. var nb;
  41696. switch (this.encoding) {
  41697. case 'utf16le':
  41698. this.text = utf16Text;
  41699. this.end = utf16End;
  41700. nb = 4;
  41701. break;
  41702. case 'utf8':
  41703. this.fillLast = utf8FillLast;
  41704. nb = 4;
  41705. break;
  41706. case 'base64':
  41707. this.text = base64Text;
  41708. this.end = base64End;
  41709. nb = 3;
  41710. break;
  41711. default:
  41712. this.write = simpleWrite;
  41713. this.end = simpleEnd;
  41714. return;
  41715. }
  41716. this.lastNeed = 0;
  41717. this.lastTotal = 0;
  41718. this.lastChar = Buffer.allocUnsafe(nb);
  41719. }
  41720. StringDecoder.prototype.write = function (buf) {
  41721. if (buf.length === 0) return '';
  41722. var r;
  41723. var i;
  41724. if (this.lastNeed) {
  41725. r = this.fillLast(buf);
  41726. if (r === undefined) return '';
  41727. i = this.lastNeed;
  41728. this.lastNeed = 0;
  41729. } else {
  41730. i = 0;
  41731. }
  41732. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  41733. return r || '';
  41734. };
  41735. StringDecoder.prototype.end = utf8End;
  41736. // Returns only complete characters in a Buffer
  41737. StringDecoder.prototype.text = utf8Text;
  41738. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  41739. StringDecoder.prototype.fillLast = function (buf) {
  41740. if (this.lastNeed <= buf.length) {
  41741. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  41742. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  41743. }
  41744. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  41745. this.lastNeed -= buf.length;
  41746. };
  41747. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  41748. // continuation byte.
  41749. function utf8CheckByte(byte) {
  41750. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  41751. return -1;
  41752. }
  41753. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  41754. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  41755. // needed to complete the UTF-8 character (if applicable) are returned.
  41756. function utf8CheckIncomplete(self, buf, i) {
  41757. var j = buf.length - 1;
  41758. if (j < i) return 0;
  41759. var nb = utf8CheckByte(buf[j]);
  41760. if (nb >= 0) {
  41761. if (nb > 0) self.lastNeed = nb - 1;
  41762. return nb;
  41763. }
  41764. if (--j < i) return 0;
  41765. nb = utf8CheckByte(buf[j]);
  41766. if (nb >= 0) {
  41767. if (nb > 0) self.lastNeed = nb - 2;
  41768. return nb;
  41769. }
  41770. if (--j < i) return 0;
  41771. nb = utf8CheckByte(buf[j]);
  41772. if (nb >= 0) {
  41773. if (nb > 0) {
  41774. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  41775. }
  41776. return nb;
  41777. }
  41778. return 0;
  41779. }
  41780. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  41781. // needed or are available. If we see a non-continuation byte where we expect
  41782. // one, we "replace" the validated continuation bytes we've seen so far with
  41783. // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
  41784. // behavior. The continuation byte check is included three times in the case
  41785. // where all of the continuation bytes for a character exist in the same buffer.
  41786. // It is also done this way as a slight performance increase instead of using a
  41787. // loop.
  41788. function utf8CheckExtraBytes(self, buf, p) {
  41789. if ((buf[0] & 0xC0) !== 0x80) {
  41790. self.lastNeed = 0;
  41791. return '\ufffd'.repeat(p);
  41792. }
  41793. if (self.lastNeed > 1 && buf.length > 1) {
  41794. if ((buf[1] & 0xC0) !== 0x80) {
  41795. self.lastNeed = 1;
  41796. return '\ufffd'.repeat(p + 1);
  41797. }
  41798. if (self.lastNeed > 2 && buf.length > 2) {
  41799. if ((buf[2] & 0xC0) !== 0x80) {
  41800. self.lastNeed = 2;
  41801. return '\ufffd'.repeat(p + 2);
  41802. }
  41803. }
  41804. }
  41805. }
  41806. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  41807. function utf8FillLast(buf) {
  41808. var p = this.lastTotal - this.lastNeed;
  41809. var r = utf8CheckExtraBytes(this, buf, p);
  41810. if (r !== undefined) return r;
  41811. if (this.lastNeed <= buf.length) {
  41812. buf.copy(this.lastChar, p, 0, this.lastNeed);
  41813. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  41814. }
  41815. buf.copy(this.lastChar, p, 0, buf.length);
  41816. this.lastNeed -= buf.length;
  41817. }
  41818. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  41819. // partial character, the character's bytes are buffered until the required
  41820. // number of bytes are available.
  41821. function utf8Text(buf, i) {
  41822. var total = utf8CheckIncomplete(this, buf, i);
  41823. if (!this.lastNeed) return buf.toString('utf8', i);
  41824. this.lastTotal = total;
  41825. var end = buf.length - (total - this.lastNeed);
  41826. buf.copy(this.lastChar, 0, end);
  41827. return buf.toString('utf8', i, end);
  41828. }
  41829. // For UTF-8, a replacement character for each buffered byte of a (partial)
  41830. // character needs to be added to the output.
  41831. function utf8End(buf) {
  41832. var r = buf && buf.length ? this.write(buf) : '';
  41833. if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
  41834. return r;
  41835. }
  41836. // UTF-16LE typically needs two bytes per character, but even if we have an even
  41837. // number of bytes available, we need to check if we end on a leading/high
  41838. // surrogate. In that case, we need to wait for the next two bytes in order to
  41839. // decode the last character properly.
  41840. function utf16Text(buf, i) {
  41841. if ((buf.length - i) % 2 === 0) {
  41842. var r = buf.toString('utf16le', i);
  41843. if (r) {
  41844. var c = r.charCodeAt(r.length - 1);
  41845. if (c >= 0xD800 && c <= 0xDBFF) {
  41846. this.lastNeed = 2;
  41847. this.lastTotal = 4;
  41848. this.lastChar[0] = buf[buf.length - 2];
  41849. this.lastChar[1] = buf[buf.length - 1];
  41850. return r.slice(0, -1);
  41851. }
  41852. }
  41853. return r;
  41854. }
  41855. this.lastNeed = 1;
  41856. this.lastTotal = 2;
  41857. this.lastChar[0] = buf[buf.length - 1];
  41858. return buf.toString('utf16le', i, buf.length - 1);
  41859. }
  41860. // For UTF-16LE we do not explicitly append special replacement characters if we
  41861. // end on a partial character, we simply let v8 handle that.
  41862. function utf16End(buf) {
  41863. var r = buf && buf.length ? this.write(buf) : '';
  41864. if (this.lastNeed) {
  41865. var end = this.lastTotal - this.lastNeed;
  41866. return r + this.lastChar.toString('utf16le', 0, end);
  41867. }
  41868. return r;
  41869. }
  41870. function base64Text(buf, i) {
  41871. var n = (buf.length - i) % 3;
  41872. if (n === 0) return buf.toString('base64', i);
  41873. this.lastNeed = 3 - n;
  41874. this.lastTotal = 3;
  41875. if (n === 1) {
  41876. this.lastChar[0] = buf[buf.length - 1];
  41877. } else {
  41878. this.lastChar[0] = buf[buf.length - 2];
  41879. this.lastChar[1] = buf[buf.length - 1];
  41880. }
  41881. return buf.toString('base64', i, buf.length - n);
  41882. }
  41883. function base64End(buf) {
  41884. var r = buf && buf.length ? this.write(buf) : '';
  41885. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  41886. return r;
  41887. }
  41888. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  41889. function simpleWrite(buf) {
  41890. return buf.toString(this.encoding);
  41891. }
  41892. function simpleEnd(buf) {
  41893. return buf && buf.length ? this.write(buf) : '';
  41894. }
  41895. },{"safe-buffer":130}],146:[function(require,module,exports){
  41896. var Buffer = require('buffer').Buffer
  41897. module.exports = function (buf) {
  41898. // If the buffer is backed by a Uint8Array, a faster version will work
  41899. if (buf instanceof Uint8Array) {
  41900. // If the buffer isn't a subarray, return the underlying ArrayBuffer
  41901. if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
  41902. return buf.buffer
  41903. } else if (typeof buf.buffer.slice === 'function') {
  41904. // Otherwise we need to get a proper copy
  41905. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
  41906. }
  41907. }
  41908. if (Buffer.isBuffer(buf)) {
  41909. // This is the slow version that will work with any Buffer
  41910. // implementation (even in old browsers)
  41911. var arrayCopy = new Uint8Array(buf.length)
  41912. var len = buf.length
  41913. for (var i = 0; i < len; i++) {
  41914. arrayCopy[i] = buf[i]
  41915. }
  41916. return arrayCopy.buffer
  41917. } else {
  41918. throw new Error('Argument must be a Buffer')
  41919. }
  41920. }
  41921. },{"buffer":32}],147:[function(require,module,exports){
  41922. (function (global){
  41923. /**
  41924. * Module exports.
  41925. */
  41926. module.exports = deprecate;
  41927. /**
  41928. * Mark that a method should not be used.
  41929. * Returns a modified function which warns once by default.
  41930. *
  41931. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  41932. *
  41933. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  41934. * will throw an Error when invoked.
  41935. *
  41936. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  41937. * will invoke `console.trace()` instead of `console.error()`.
  41938. *
  41939. * @param {Function} fn - the function to deprecate
  41940. * @param {String} msg - the string to print to the console when `fn` is invoked
  41941. * @returns {Function} a new "deprecated" version of `fn`
  41942. * @api public
  41943. */
  41944. function deprecate (fn, msg) {
  41945. if (config('noDeprecation')) {
  41946. return fn;
  41947. }
  41948. var warned = false;
  41949. function deprecated() {
  41950. if (!warned) {
  41951. if (config('throwDeprecation')) {
  41952. throw new Error(msg);
  41953. } else if (config('traceDeprecation')) {
  41954. console.trace(msg);
  41955. } else {
  41956. console.warn(msg);
  41957. }
  41958. warned = true;
  41959. }
  41960. return fn.apply(this, arguments);
  41961. }
  41962. return deprecated;
  41963. }
  41964. /**
  41965. * Checks `localStorage` for boolean values for the given `name`.
  41966. *
  41967. * @param {String} name
  41968. * @returns {Boolean}
  41969. * @api private
  41970. */
  41971. function config (name) {
  41972. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  41973. try {
  41974. if (!global.localStorage) return false;
  41975. } catch (_) {
  41976. return false;
  41977. }
  41978. var val = global.localStorage[name];
  41979. if (null == val) return false;
  41980. return String(val).toLowerCase() === 'true';
  41981. }
  41982. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  41983. },{}],148:[function(require,module,exports){
  41984. (function (process,Buffer){
  41985. /**
  41986. * Wrapper for built-in http.js to emulate the browser XMLHttpRequest object.
  41987. *
  41988. * This can be used with JS designed for browsers to improve reuse of code and
  41989. * allow the use of existing libraries.
  41990. *
  41991. * Usage: include("XMLHttpRequest.js") and use XMLHttpRequest per W3C specs.
  41992. *
  41993. * @author Dan DeFelippi <dan@driverdan.com>
  41994. * @contributor David Ellis <d.f.ellis@ieee.org>
  41995. * @license MIT
  41996. */
  41997. var Url = require("url");
  41998. var spawn = require("child_process").spawn;
  41999. var fs = require("fs");
  42000. exports.XMLHttpRequest = function() {
  42001. "use strict";
  42002. /**
  42003. * Private variables
  42004. */
  42005. var self = this;
  42006. var http = require("http");
  42007. var https = require("https");
  42008. // Holds http.js objects
  42009. var request;
  42010. var response;
  42011. // Request settings
  42012. var settings = {};
  42013. // Disable header blacklist.
  42014. // Not part of XHR specs.
  42015. var disableHeaderCheck = false;
  42016. // Set some default headers
  42017. var defaultHeaders = {
  42018. "User-Agent": "node-XMLHttpRequest",
  42019. "Accept": "*/*",
  42020. };
  42021. var headers = {};
  42022. var headersCase = {};
  42023. // These headers are not user setable.
  42024. // The following are allowed but banned in the spec:
  42025. // * user-agent
  42026. var forbiddenRequestHeaders = [
  42027. "accept-charset",
  42028. "accept-encoding",
  42029. "access-control-request-headers",
  42030. "access-control-request-method",
  42031. "connection",
  42032. "content-length",
  42033. "content-transfer-encoding",
  42034. "cookie",
  42035. "cookie2",
  42036. "date",
  42037. "expect",
  42038. "host",
  42039. "keep-alive",
  42040. "origin",
  42041. "referer",
  42042. "te",
  42043. "trailer",
  42044. "transfer-encoding",
  42045. "upgrade",
  42046. "via"
  42047. ];
  42048. // These request methods are not allowed
  42049. var forbiddenRequestMethods = [
  42050. "TRACE",
  42051. "TRACK",
  42052. "CONNECT"
  42053. ];
  42054. // Send flag
  42055. var sendFlag = false;
  42056. // Error flag, used when errors occur or abort is called
  42057. var errorFlag = false;
  42058. // Event listeners
  42059. var listeners = {};
  42060. /**
  42061. * Constants
  42062. */
  42063. this.UNSENT = 0;
  42064. this.OPENED = 1;
  42065. this.HEADERS_RECEIVED = 2;
  42066. this.LOADING = 3;
  42067. this.DONE = 4;
  42068. /**
  42069. * Public vars
  42070. */
  42071. // Current state
  42072. this.readyState = this.UNSENT;
  42073. // default ready state change handler in case one is not set or is set late
  42074. this.onreadystatechange = null;
  42075. // Result & response
  42076. this.responseText = "";
  42077. this.responseXML = "";
  42078. this.status = null;
  42079. this.statusText = null;
  42080. // Whether cross-site Access-Control requests should be made using
  42081. // credentials such as cookies or authorization headers
  42082. this.withCredentials = false;
  42083. /**
  42084. * Private methods
  42085. */
  42086. /**
  42087. * Check if the specified header is allowed.
  42088. *
  42089. * @param string header Header to validate
  42090. * @return boolean False if not allowed, otherwise true
  42091. */
  42092. var isAllowedHttpHeader = function(header) {
  42093. return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1);
  42094. };
  42095. /**
  42096. * Check if the specified method is allowed.
  42097. *
  42098. * @param string method Request method to validate
  42099. * @return boolean False if not allowed, otherwise true
  42100. */
  42101. var isAllowedHttpMethod = function(method) {
  42102. return (method && forbiddenRequestMethods.indexOf(method) === -1);
  42103. };
  42104. /**
  42105. * Public methods
  42106. */
  42107. /**
  42108. * Open the connection. Currently supports local server requests.
  42109. *
  42110. * @param string method Connection method (eg GET, POST)
  42111. * @param string url URL for the connection.
  42112. * @param boolean async Asynchronous connection. Default is true.
  42113. * @param string user Username for basic authentication (optional)
  42114. * @param string password Password for basic authentication (optional)
  42115. */
  42116. this.open = function(method, url, async, user, password) {
  42117. this.abort();
  42118. errorFlag = false;
  42119. // Check for valid request method
  42120. if (!isAllowedHttpMethod(method)) {
  42121. throw new Error("SecurityError: Request method not allowed");
  42122. }
  42123. settings = {
  42124. "method": method,
  42125. "url": url.toString(),
  42126. "async": (typeof async !== "boolean" ? true : async),
  42127. "user": user || null,
  42128. "password": password || null
  42129. };
  42130. setState(this.OPENED);
  42131. };
  42132. /**
  42133. * Disables or enables isAllowedHttpHeader() check the request. Enabled by default.
  42134. * This does not conform to the W3C spec.
  42135. *
  42136. * @param boolean state Enable or disable header checking.
  42137. */
  42138. this.setDisableHeaderCheck = function(state) {
  42139. disableHeaderCheck = state;
  42140. };
  42141. /**
  42142. * Sets a header for the request or appends the value if one is already set.
  42143. *
  42144. * @param string header Header name
  42145. * @param string value Header value
  42146. */
  42147. this.setRequestHeader = function(header, value) {
  42148. if (this.readyState !== this.OPENED) {
  42149. throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");
  42150. }
  42151. if (!isAllowedHttpHeader(header)) {
  42152. console.warn("Refused to set unsafe header \"" + header + "\"");
  42153. return;
  42154. }
  42155. if (sendFlag) {
  42156. throw new Error("INVALID_STATE_ERR: send flag is true");
  42157. }
  42158. header = headersCase[header.toLowerCase()] || header;
  42159. headersCase[header.toLowerCase()] = header;
  42160. headers[header] = headers[header] ? headers[header] + ', ' + value : value;
  42161. };
  42162. /**
  42163. * Gets a header from the server response.
  42164. *
  42165. * @param string header Name of header to get.
  42166. * @return string Text of the header or null if it doesn't exist.
  42167. */
  42168. this.getResponseHeader = function(header) {
  42169. if (typeof header === "string"
  42170. && this.readyState > this.OPENED
  42171. && response
  42172. && response.headers
  42173. && response.headers[header.toLowerCase()]
  42174. && !errorFlag
  42175. ) {
  42176. return response.headers[header.toLowerCase()];
  42177. }
  42178. return null;
  42179. };
  42180. /**
  42181. * Gets all the response headers.
  42182. *
  42183. * @return string A string with all response headers separated by CR+LF
  42184. */
  42185. this.getAllResponseHeaders = function() {
  42186. if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {
  42187. return "";
  42188. }
  42189. var result = "";
  42190. for (var i in response.headers) {
  42191. // Cookie headers are excluded
  42192. if (i !== "set-cookie" && i !== "set-cookie2") {
  42193. result += i + ": " + response.headers[i] + "\r\n";
  42194. }
  42195. }
  42196. return result.substr(0, result.length - 2);
  42197. };
  42198. /**
  42199. * Gets a request header
  42200. *
  42201. * @param string name Name of header to get
  42202. * @return string Returns the request header or empty string if not set
  42203. */
  42204. this.getRequestHeader = function(name) {
  42205. if (typeof name === "string" && headersCase[name.toLowerCase()]) {
  42206. return headers[headersCase[name.toLowerCase()]];
  42207. }
  42208. return "";
  42209. };
  42210. /**
  42211. * Sends the request to the server.
  42212. *
  42213. * @param string data Optional data to send as request body.
  42214. */
  42215. this.send = function(data) {
  42216. if (this.readyState !== this.OPENED) {
  42217. throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");
  42218. }
  42219. if (sendFlag) {
  42220. throw new Error("INVALID_STATE_ERR: send has already been called");
  42221. }
  42222. var ssl = false, local = false;
  42223. var url = Url.parse(settings.url);
  42224. var host;
  42225. // Determine the server
  42226. switch (url.protocol) {
  42227. case "https:":
  42228. ssl = true;
  42229. // SSL & non-SSL both need host, no break here.
  42230. case "http:":
  42231. host = url.hostname;
  42232. break;
  42233. case "file:":
  42234. local = true;
  42235. break;
  42236. case undefined:
  42237. case null:
  42238. case "":
  42239. host = "localhost";
  42240. break;
  42241. default:
  42242. throw new Error("Protocol not supported.");
  42243. }
  42244. // Load files off the local filesystem (file://)
  42245. if (local) {
  42246. if (settings.method !== "GET") {
  42247. throw new Error("XMLHttpRequest: Only GET method is supported");
  42248. }
  42249. if (settings.async) {
  42250. fs.readFile(url.pathname, "utf8", function(error, data) {
  42251. if (error) {
  42252. self.handleError(error);
  42253. } else {
  42254. self.status = 200;
  42255. self.responseText = data;
  42256. setState(self.DONE);
  42257. }
  42258. });
  42259. } else {
  42260. try {
  42261. this.responseText = fs.readFileSync(url.pathname, "utf8");
  42262. this.status = 200;
  42263. setState(self.DONE);
  42264. } catch(e) {
  42265. this.handleError(e);
  42266. }
  42267. }
  42268. return;
  42269. }
  42270. // Default to port 80. If accessing localhost on another port be sure
  42271. // to use http://localhost:port/path
  42272. var port = url.port || (ssl ? 443 : 80);
  42273. // Add query string if one is used
  42274. var uri = url.pathname + (url.search ? url.search : "");
  42275. // Set the defaults if they haven't been set
  42276. for (var name in defaultHeaders) {
  42277. if (!headersCase[name.toLowerCase()]) {
  42278. headers[name] = defaultHeaders[name];
  42279. }
  42280. }
  42281. // Set the Host header or the server may reject the request
  42282. headers.Host = host;
  42283. if (!((ssl && port === 443) || port === 80)) {
  42284. headers.Host += ":" + url.port;
  42285. }
  42286. // Set Basic Auth if necessary
  42287. if (settings.user) {
  42288. if (typeof settings.password === "undefined") {
  42289. settings.password = "";
  42290. }
  42291. var authBuf = new Buffer(settings.user + ":" + settings.password);
  42292. headers.Authorization = "Basic " + authBuf.toString("base64");
  42293. }
  42294. // Set content length header
  42295. if (settings.method === "GET" || settings.method === "HEAD") {
  42296. data = null;
  42297. } else if (data) {
  42298. headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);
  42299. if (!headers["Content-Type"]) {
  42300. headers["Content-Type"] = "text/plain;charset=UTF-8";
  42301. }
  42302. } else if (settings.method === "POST") {
  42303. // For a post with no data set Content-Length: 0.
  42304. // This is required by buggy servers that don't meet the specs.
  42305. headers["Content-Length"] = 0;
  42306. }
  42307. var options = {
  42308. host: host,
  42309. port: port,
  42310. path: uri,
  42311. method: settings.method,
  42312. headers: headers,
  42313. agent: false,
  42314. withCredentials: self.withCredentials
  42315. };
  42316. // Reset error flag
  42317. errorFlag = false;
  42318. // Handle async requests
  42319. if (settings.async) {
  42320. // Use the proper protocol
  42321. var doRequest = ssl ? https.request : http.request;
  42322. // Request is being sent, set send flag
  42323. sendFlag = true;
  42324. // As per spec, this is called here for historical reasons.
  42325. self.dispatchEvent("readystatechange");
  42326. // Handler for the response
  42327. var responseHandler = function responseHandler(resp) {
  42328. // Set response var to the response we got back
  42329. // This is so it remains accessable outside this scope
  42330. response = resp;
  42331. // Check for redirect
  42332. // @TODO Prevent looped redirects
  42333. if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
  42334. // Change URL to the redirect location
  42335. settings.url = response.headers.location;
  42336. var url = Url.parse(settings.url);
  42337. // Set host var in case it's used later
  42338. host = url.hostname;
  42339. // Options for the new request
  42340. var newOptions = {
  42341. hostname: url.hostname,
  42342. port: url.port,
  42343. path: url.path,
  42344. method: response.statusCode === 303 ? "GET" : settings.method,
  42345. headers: headers,
  42346. withCredentials: self.withCredentials
  42347. };
  42348. // Issue the new request
  42349. request = doRequest(newOptions, responseHandler).on("error", errorHandler);
  42350. request.end();
  42351. // @TODO Check if an XHR event needs to be fired here
  42352. return;
  42353. }
  42354. response.setEncoding("utf8");
  42355. setState(self.HEADERS_RECEIVED);
  42356. self.status = response.statusCode;
  42357. response.on("data", function(chunk) {
  42358. // Make sure there's some data
  42359. if (chunk) {
  42360. self.responseText += chunk;
  42361. }
  42362. // Don't emit state changes if the connection has been aborted.
  42363. if (sendFlag) {
  42364. setState(self.LOADING);
  42365. }
  42366. });
  42367. response.on("end", function() {
  42368. if (sendFlag) {
  42369. // Discard the end event if the connection has been aborted
  42370. setState(self.DONE);
  42371. sendFlag = false;
  42372. }
  42373. });
  42374. response.on("error", function(error) {
  42375. self.handleError(error);
  42376. });
  42377. };
  42378. // Error handler for the request
  42379. var errorHandler = function errorHandler(error) {
  42380. self.handleError(error);
  42381. };
  42382. // Create the request
  42383. request = doRequest(options, responseHandler).on("error", errorHandler);
  42384. // Node 0.4 and later won't accept empty data. Make sure it's needed.
  42385. if (data) {
  42386. request.write(data);
  42387. }
  42388. request.end();
  42389. self.dispatchEvent("loadstart");
  42390. } else { // Synchronous
  42391. // Create a temporary file for communication with the other Node process
  42392. var contentFile = ".node-xmlhttprequest-content-" + process.pid;
  42393. var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
  42394. fs.writeFileSync(syncFile, "", "utf8");
  42395. // The async request the other Node process executes
  42396. var execString = "var http = require('http'), https = require('https'), fs = require('fs');"
  42397. + "var doRequest = http" + (ssl ? "s" : "") + ".request;"
  42398. + "var options = " + JSON.stringify(options) + ";"
  42399. + "var responseText = '';"
  42400. + "var req = doRequest(options, function(response) {"
  42401. + "response.setEncoding('utf8');"
  42402. + "response.on('data', function(chunk) {"
  42403. + " responseText += chunk;"
  42404. + "});"
  42405. + "response.on('end', function() {"
  42406. + "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText}}), 'utf8');"
  42407. + "fs.unlinkSync('" + syncFile + "');"
  42408. + "});"
  42409. + "response.on('error', function(error) {"
  42410. + "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');"
  42411. + "fs.unlinkSync('" + syncFile + "');"
  42412. + "});"
  42413. + "}).on('error', function(error) {"
  42414. + "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');"
  42415. + "fs.unlinkSync('" + syncFile + "');"
  42416. + "});"
  42417. + (data ? "req.write('" + JSON.stringify(data).slice(1,-1).replace(/'/g, "\\'") + "');":"")
  42418. + "req.end();";
  42419. // Start the other Node Process, executing this string
  42420. var syncProc = spawn(process.argv[0], ["-e", execString]);
  42421. while(fs.existsSync(syncFile)) {
  42422. // Wait while the sync file is empty
  42423. }
  42424. var resp = JSON.parse(fs.readFileSync(contentFile, 'utf8'));
  42425. // Kill the child process once the file has data
  42426. syncProc.stdin.end();
  42427. // Remove the temporary file
  42428. fs.unlinkSync(contentFile);
  42429. if (resp.err) {
  42430. self.handleError(resp.err);
  42431. } else {
  42432. response = resp.data;
  42433. self.status = resp.data.statusCode;
  42434. self.responseText = resp.data.text;
  42435. setState(self.DONE);
  42436. }
  42437. }
  42438. };
  42439. /**
  42440. * Called when an error is encountered to deal with it.
  42441. */
  42442. this.handleError = function(error) {
  42443. this.status = 0;
  42444. this.statusText = error;
  42445. this.responseText = error.stack;
  42446. errorFlag = true;
  42447. setState(this.DONE);
  42448. this.dispatchEvent('error');
  42449. };
  42450. /**
  42451. * Aborts a request.
  42452. */
  42453. this.abort = function() {
  42454. if (request) {
  42455. request.abort();
  42456. request = null;
  42457. }
  42458. headers = defaultHeaders;
  42459. this.status = 0;
  42460. this.responseText = "";
  42461. this.responseXML = "";
  42462. errorFlag = true;
  42463. if (this.readyState !== this.UNSENT
  42464. && (this.readyState !== this.OPENED || sendFlag)
  42465. && this.readyState !== this.DONE) {
  42466. sendFlag = false;
  42467. setState(this.DONE);
  42468. }
  42469. this.readyState = this.UNSENT;
  42470. this.dispatchEvent('abort');
  42471. };
  42472. /**
  42473. * Adds an event listener. Preferred method of binding to events.
  42474. */
  42475. this.addEventListener = function(event, callback) {
  42476. if (!(event in listeners)) {
  42477. listeners[event] = [];
  42478. }
  42479. // Currently allows duplicate callbacks. Should it?
  42480. listeners[event].push(callback);
  42481. };
  42482. /**
  42483. * Remove an event callback that has already been bound.
  42484. * Only works on the matching funciton, cannot be a copy.
  42485. */
  42486. this.removeEventListener = function(event, callback) {
  42487. if (event in listeners) {
  42488. // Filter will return a new array with the callback removed
  42489. listeners[event] = listeners[event].filter(function(ev) {
  42490. return ev !== callback;
  42491. });
  42492. }
  42493. };
  42494. /**
  42495. * Dispatch any events, including both "on" methods and events attached using addEventListener.
  42496. */
  42497. this.dispatchEvent = function(event) {
  42498. if (typeof self["on" + event] === "function") {
  42499. self["on" + event]();
  42500. }
  42501. if (event in listeners) {
  42502. for (var i = 0, len = listeners[event].length; i < len; i++) {
  42503. listeners[event][i].call(self);
  42504. }
  42505. }
  42506. };
  42507. /**
  42508. * Changes readyState and calls onreadystatechange.
  42509. *
  42510. * @param int state New state
  42511. */
  42512. var setState = function(state) {
  42513. if (state == self.LOADING || self.readyState !== state) {
  42514. self.readyState = state;
  42515. if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
  42516. self.dispatchEvent("readystatechange");
  42517. }
  42518. if (self.readyState === self.DONE && !errorFlag) {
  42519. self.dispatchEvent("load");
  42520. // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
  42521. self.dispatchEvent("loadend");
  42522. }
  42523. }
  42524. };
  42525. };
  42526. }).call(this,require('_process'),require("buffer").Buffer)
  42527. },{"_process":125,"buffer":32,"child_process":30,"fs":30,"http":131,"https":34,"url":35}],149:[function(require,module,exports){
  42528. module.exports = extend
  42529. var hasOwnProperty = Object.prototype.hasOwnProperty;
  42530. function extend() {
  42531. var target = {}
  42532. for (var i = 0; i < arguments.length; i++) {
  42533. var source = arguments[i]
  42534. for (var key in source) {
  42535. if (hasOwnProperty.call(source, key)) {
  42536. target[key] = source[key]
  42537. }
  42538. }
  42539. }
  42540. return target
  42541. }
  42542. },{}]},{},[1])(1)
  42543. });