immutable.js 139 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977
  1. /**
  2. * Copyright (c) 2014-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  9. typeof define === 'function' && define.amd ? define(factory) :
  10. (global.Immutable = factory());
  11. }(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice;
  12. function createClass(ctor, superClass) {
  13. if (superClass) {
  14. ctor.prototype = Object.create(superClass.prototype);
  15. }
  16. ctor.prototype.constructor = ctor;
  17. }
  18. function Iterable(value) {
  19. return isIterable(value) ? value : Seq(value);
  20. }
  21. createClass(KeyedIterable, Iterable);
  22. function KeyedIterable(value) {
  23. return isKeyed(value) ? value : KeyedSeq(value);
  24. }
  25. createClass(IndexedIterable, Iterable);
  26. function IndexedIterable(value) {
  27. return isIndexed(value) ? value : IndexedSeq(value);
  28. }
  29. createClass(SetIterable, Iterable);
  30. function SetIterable(value) {
  31. return isIterable(value) && !isAssociative(value) ? value : SetSeq(value);
  32. }
  33. function isIterable(maybeIterable) {
  34. return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]);
  35. }
  36. function isKeyed(maybeKeyed) {
  37. return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]);
  38. }
  39. function isIndexed(maybeIndexed) {
  40. return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]);
  41. }
  42. function isAssociative(maybeAssociative) {
  43. return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
  44. }
  45. function isOrdered(maybeOrdered) {
  46. return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]);
  47. }
  48. Iterable.isIterable = isIterable;
  49. Iterable.isKeyed = isKeyed;
  50. Iterable.isIndexed = isIndexed;
  51. Iterable.isAssociative = isAssociative;
  52. Iterable.isOrdered = isOrdered;
  53. Iterable.Keyed = KeyedIterable;
  54. Iterable.Indexed = IndexedIterable;
  55. Iterable.Set = SetIterable;
  56. var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  57. var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  58. var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  59. var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';
  60. // Used for setting prototype methods that IE8 chokes on.
  61. var DELETE = 'delete';
  62. // Constants describing the size of trie nodes.
  63. var SHIFT = 5; // Resulted in best performance after ______?
  64. var SIZE = 1 << SHIFT;
  65. var MASK = SIZE - 1;
  66. // A consistent shared value representing "not set" which equals nothing other
  67. // than itself, and nothing that could be provided externally.
  68. var NOT_SET = {};
  69. // Boolean references, Rough equivalent of `bool &`.
  70. var CHANGE_LENGTH = { value: false };
  71. var DID_ALTER = { value: false };
  72. function MakeRef(ref) {
  73. ref.value = false;
  74. return ref;
  75. }
  76. function SetRef(ref) {
  77. ref && (ref.value = true);
  78. }
  79. // A function which returns a value representing an "owner" for transient writes
  80. // to tries. The return value will only ever equal itself, and will not equal
  81. // the return of any subsequent call of this function.
  82. function OwnerID() {}
  83. // http://jsperf.com/copy-array-inline
  84. function arrCopy(arr, offset) {
  85. offset = offset || 0;
  86. var len = Math.max(0, arr.length - offset);
  87. var newArr = new Array(len);
  88. for (var ii = 0; ii < len; ii++) {
  89. newArr[ii] = arr[ii + offset];
  90. }
  91. return newArr;
  92. }
  93. function ensureSize(iter) {
  94. if (iter.size === undefined) {
  95. iter.size = iter.__iterate(returnTrue);
  96. }
  97. return iter.size;
  98. }
  99. function wrapIndex(iter, index) {
  100. // This implements "is array index" which the ECMAString spec defines as:
  101. //
  102. // A String property name P is an array index if and only if
  103. // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
  104. // to 2^32−1.
  105. //
  106. // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
  107. if (typeof index !== 'number') {
  108. var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
  109. if ('' + uint32Index !== index || uint32Index === 4294967295) {
  110. return NaN;
  111. }
  112. index = uint32Index;
  113. }
  114. return index < 0 ? ensureSize(iter) + index : index;
  115. }
  116. function returnTrue() {
  117. return true;
  118. }
  119. function wholeSlice(begin, end, size) {
  120. return (begin === 0 || (size !== undefined && begin <= -size)) &&
  121. (end === undefined || (size !== undefined && end >= size));
  122. }
  123. function resolveBegin(begin, size) {
  124. return resolveIndex(begin, size, 0);
  125. }
  126. function resolveEnd(end, size) {
  127. return resolveIndex(end, size, size);
  128. }
  129. function resolveIndex(index, size, defaultIndex) {
  130. return index === undefined ?
  131. defaultIndex :
  132. index < 0 ?
  133. Math.max(0, size + index) :
  134. size === undefined ?
  135. index :
  136. Math.min(size, index);
  137. }
  138. /* global Symbol */
  139. var ITERATE_KEYS = 0;
  140. var ITERATE_VALUES = 1;
  141. var ITERATE_ENTRIES = 2;
  142. var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  143. var FAUX_ITERATOR_SYMBOL = '@@iterator';
  144. var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
  145. function Iterator(next) {
  146. this.next = next;
  147. }
  148. Iterator.prototype.toString = function() {
  149. return '[Iterator]';
  150. };
  151. Iterator.KEYS = ITERATE_KEYS;
  152. Iterator.VALUES = ITERATE_VALUES;
  153. Iterator.ENTRIES = ITERATE_ENTRIES;
  154. Iterator.prototype.inspect =
  155. Iterator.prototype.toSource = function () { return this.toString(); }
  156. Iterator.prototype[ITERATOR_SYMBOL] = function () {
  157. return this;
  158. };
  159. function iteratorValue(type, k, v, iteratorResult) {
  160. var value = type === 0 ? k : type === 1 ? v : [k, v];
  161. iteratorResult ? (iteratorResult.value = value) : (iteratorResult = {
  162. value: value, done: false
  163. });
  164. return iteratorResult;
  165. }
  166. function iteratorDone() {
  167. return { value: undefined, done: true };
  168. }
  169. function hasIterator(maybeIterable) {
  170. return !!getIteratorFn(maybeIterable);
  171. }
  172. function isIterator(maybeIterator) {
  173. return maybeIterator && typeof maybeIterator.next === 'function';
  174. }
  175. function getIterator(iterable) {
  176. var iteratorFn = getIteratorFn(iterable);
  177. return iteratorFn && iteratorFn.call(iterable);
  178. }
  179. function getIteratorFn(iterable) {
  180. var iteratorFn = iterable && (
  181. (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
  182. iterable[FAUX_ITERATOR_SYMBOL]
  183. );
  184. if (typeof iteratorFn === 'function') {
  185. return iteratorFn;
  186. }
  187. }
  188. function isArrayLike(value) {
  189. return value && typeof value.length === 'number';
  190. }
  191. createClass(Seq, Iterable);
  192. function Seq(value) {
  193. return value === null || value === undefined ? emptySequence() :
  194. isIterable(value) ? value.toSeq() : seqFromValue(value);
  195. }
  196. Seq.of = function(/*...values*/) {
  197. return Seq(arguments);
  198. };
  199. Seq.prototype.toSeq = function() {
  200. return this;
  201. };
  202. Seq.prototype.toString = function() {
  203. return this.__toString('Seq {', '}');
  204. };
  205. Seq.prototype.cacheResult = function() {
  206. if (!this._cache && this.__iterateUncached) {
  207. this._cache = this.entrySeq().toArray();
  208. this.size = this._cache.length;
  209. }
  210. return this;
  211. };
  212. // abstract __iterateUncached(fn, reverse)
  213. Seq.prototype.__iterate = function(fn, reverse) {
  214. return seqIterate(this, fn, reverse, true);
  215. };
  216. // abstract __iteratorUncached(type, reverse)
  217. Seq.prototype.__iterator = function(type, reverse) {
  218. return seqIterator(this, type, reverse, true);
  219. };
  220. createClass(KeyedSeq, Seq);
  221. function KeyedSeq(value) {
  222. return value === null || value === undefined ?
  223. emptySequence().toKeyedSeq() :
  224. isIterable(value) ?
  225. (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) :
  226. keyedSeqFromValue(value);
  227. }
  228. KeyedSeq.prototype.toKeyedSeq = function() {
  229. return this;
  230. };
  231. createClass(IndexedSeq, Seq);
  232. function IndexedSeq(value) {
  233. return value === null || value === undefined ? emptySequence() :
  234. !isIterable(value) ? indexedSeqFromValue(value) :
  235. isKeyed(value) ? value.entrySeq() : value.toIndexedSeq();
  236. }
  237. IndexedSeq.of = function(/*...values*/) {
  238. return IndexedSeq(arguments);
  239. };
  240. IndexedSeq.prototype.toIndexedSeq = function() {
  241. return this;
  242. };
  243. IndexedSeq.prototype.toString = function() {
  244. return this.__toString('Seq [', ']');
  245. };
  246. IndexedSeq.prototype.__iterate = function(fn, reverse) {
  247. return seqIterate(this, fn, reverse, false);
  248. };
  249. IndexedSeq.prototype.__iterator = function(type, reverse) {
  250. return seqIterator(this, type, reverse, false);
  251. };
  252. createClass(SetSeq, Seq);
  253. function SetSeq(value) {
  254. return (
  255. value === null || value === undefined ? emptySequence() :
  256. !isIterable(value) ? indexedSeqFromValue(value) :
  257. isKeyed(value) ? value.entrySeq() : value
  258. ).toSetSeq();
  259. }
  260. SetSeq.of = function(/*...values*/) {
  261. return SetSeq(arguments);
  262. };
  263. SetSeq.prototype.toSetSeq = function() {
  264. return this;
  265. };
  266. Seq.isSeq = isSeq;
  267. Seq.Keyed = KeyedSeq;
  268. Seq.Set = SetSeq;
  269. Seq.Indexed = IndexedSeq;
  270. var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@';
  271. Seq.prototype[IS_SEQ_SENTINEL] = true;
  272. createClass(ArraySeq, IndexedSeq);
  273. function ArraySeq(array) {
  274. this._array = array;
  275. this.size = array.length;
  276. }
  277. ArraySeq.prototype.get = function(index, notSetValue) {
  278. return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
  279. };
  280. ArraySeq.prototype.__iterate = function(fn, reverse) {
  281. var array = this._array;
  282. var maxIndex = array.length - 1;
  283. for (var ii = 0; ii <= maxIndex; ii++) {
  284. if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) {
  285. return ii + 1;
  286. }
  287. }
  288. return ii;
  289. };
  290. ArraySeq.prototype.__iterator = function(type, reverse) {
  291. var array = this._array;
  292. var maxIndex = array.length - 1;
  293. var ii = 0;
  294. return new Iterator(function()
  295. {return ii > maxIndex ?
  296. iteratorDone() :
  297. iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])}
  298. );
  299. };
  300. createClass(ObjectSeq, KeyedSeq);
  301. function ObjectSeq(object) {
  302. var keys = Object.keys(object);
  303. this._object = object;
  304. this._keys = keys;
  305. this.size = keys.length;
  306. }
  307. ObjectSeq.prototype.get = function(key, notSetValue) {
  308. if (notSetValue !== undefined && !this.has(key)) {
  309. return notSetValue;
  310. }
  311. return this._object[key];
  312. };
  313. ObjectSeq.prototype.has = function(key) {
  314. return this._object.hasOwnProperty(key);
  315. };
  316. ObjectSeq.prototype.__iterate = function(fn, reverse) {
  317. var object = this._object;
  318. var keys = this._keys;
  319. var maxIndex = keys.length - 1;
  320. for (var ii = 0; ii <= maxIndex; ii++) {
  321. var key = keys[reverse ? maxIndex - ii : ii];
  322. if (fn(object[key], key, this) === false) {
  323. return ii + 1;
  324. }
  325. }
  326. return ii;
  327. };
  328. ObjectSeq.prototype.__iterator = function(type, reverse) {
  329. var object = this._object;
  330. var keys = this._keys;
  331. var maxIndex = keys.length - 1;
  332. var ii = 0;
  333. return new Iterator(function() {
  334. var key = keys[reverse ? maxIndex - ii : ii];
  335. return ii++ > maxIndex ?
  336. iteratorDone() :
  337. iteratorValue(type, key, object[key]);
  338. });
  339. };
  340. ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true;
  341. createClass(IterableSeq, IndexedSeq);
  342. function IterableSeq(iterable) {
  343. this._iterable = iterable;
  344. this.size = iterable.length || iterable.size;
  345. }
  346. IterableSeq.prototype.__iterateUncached = function(fn, reverse) {
  347. if (reverse) {
  348. return this.cacheResult().__iterate(fn, reverse);
  349. }
  350. var iterable = this._iterable;
  351. var iterator = getIterator(iterable);
  352. var iterations = 0;
  353. if (isIterator(iterator)) {
  354. var step;
  355. while (!(step = iterator.next()).done) {
  356. if (fn(step.value, iterations++, this) === false) {
  357. break;
  358. }
  359. }
  360. }
  361. return iterations;
  362. };
  363. IterableSeq.prototype.__iteratorUncached = function(type, reverse) {
  364. if (reverse) {
  365. return this.cacheResult().__iterator(type, reverse);
  366. }
  367. var iterable = this._iterable;
  368. var iterator = getIterator(iterable);
  369. if (!isIterator(iterator)) {
  370. return new Iterator(iteratorDone);
  371. }
  372. var iterations = 0;
  373. return new Iterator(function() {
  374. var step = iterator.next();
  375. return step.done ? step : iteratorValue(type, iterations++, step.value);
  376. });
  377. };
  378. createClass(IteratorSeq, IndexedSeq);
  379. function IteratorSeq(iterator) {
  380. this._iterator = iterator;
  381. this._iteratorCache = [];
  382. }
  383. IteratorSeq.prototype.__iterateUncached = function(fn, reverse) {
  384. if (reverse) {
  385. return this.cacheResult().__iterate(fn, reverse);
  386. }
  387. var iterator = this._iterator;
  388. var cache = this._iteratorCache;
  389. var iterations = 0;
  390. while (iterations < cache.length) {
  391. if (fn(cache[iterations], iterations++, this) === false) {
  392. return iterations;
  393. }
  394. }
  395. var step;
  396. while (!(step = iterator.next()).done) {
  397. var val = step.value;
  398. cache[iterations] = val;
  399. if (fn(val, iterations++, this) === false) {
  400. break;
  401. }
  402. }
  403. return iterations;
  404. };
  405. IteratorSeq.prototype.__iteratorUncached = function(type, reverse) {
  406. if (reverse) {
  407. return this.cacheResult().__iterator(type, reverse);
  408. }
  409. var iterator = this._iterator;
  410. var cache = this._iteratorCache;
  411. var iterations = 0;
  412. return new Iterator(function() {
  413. if (iterations >= cache.length) {
  414. var step = iterator.next();
  415. if (step.done) {
  416. return step;
  417. }
  418. cache[iterations] = step.value;
  419. }
  420. return iteratorValue(type, iterations, cache[iterations++]);
  421. });
  422. };
  423. // # pragma Helper functions
  424. function isSeq(maybeSeq) {
  425. return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]);
  426. }
  427. var EMPTY_SEQ;
  428. function emptySequence() {
  429. return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
  430. }
  431. function keyedSeqFromValue(value) {
  432. var seq =
  433. Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() :
  434. isIterator(value) ? new IteratorSeq(value).fromEntrySeq() :
  435. hasIterator(value) ? new IterableSeq(value).fromEntrySeq() :
  436. typeof value === 'object' ? new ObjectSeq(value) :
  437. undefined;
  438. if (!seq) {
  439. throw new TypeError(
  440. 'Expected Array or iterable object of [k, v] entries, '+
  441. 'or keyed object: ' + value
  442. );
  443. }
  444. return seq;
  445. }
  446. function indexedSeqFromValue(value) {
  447. var seq = maybeIndexedSeqFromValue(value);
  448. if (!seq) {
  449. throw new TypeError(
  450. 'Expected Array or iterable object of values: ' + value
  451. );
  452. }
  453. return seq;
  454. }
  455. function seqFromValue(value) {
  456. var seq = maybeIndexedSeqFromValue(value) ||
  457. (typeof value === 'object' && new ObjectSeq(value));
  458. if (!seq) {
  459. throw new TypeError(
  460. 'Expected Array or iterable object of values, or keyed object: ' + value
  461. );
  462. }
  463. return seq;
  464. }
  465. function maybeIndexedSeqFromValue(value) {
  466. return (
  467. isArrayLike(value) ? new ArraySeq(value) :
  468. isIterator(value) ? new IteratorSeq(value) :
  469. hasIterator(value) ? new IterableSeq(value) :
  470. undefined
  471. );
  472. }
  473. function seqIterate(seq, fn, reverse, useKeys) {
  474. var cache = seq._cache;
  475. if (cache) {
  476. var maxIndex = cache.length - 1;
  477. for (var ii = 0; ii <= maxIndex; ii++) {
  478. var entry = cache[reverse ? maxIndex - ii : ii];
  479. if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) {
  480. return ii + 1;
  481. }
  482. }
  483. return ii;
  484. }
  485. return seq.__iterateUncached(fn, reverse);
  486. }
  487. function seqIterator(seq, type, reverse, useKeys) {
  488. var cache = seq._cache;
  489. if (cache) {
  490. var maxIndex = cache.length - 1;
  491. var ii = 0;
  492. return new Iterator(function() {
  493. var entry = cache[reverse ? maxIndex - ii : ii];
  494. return ii++ > maxIndex ?
  495. iteratorDone() :
  496. iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]);
  497. });
  498. }
  499. return seq.__iteratorUncached(type, reverse);
  500. }
  501. function fromJS(json, converter) {
  502. return converter ?
  503. fromJSWith(converter, json, '', {'': json}) :
  504. fromJSDefault(json);
  505. }
  506. function fromJSWith(converter, json, key, parentJSON) {
  507. if (Array.isArray(json)) {
  508. return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)}));
  509. }
  510. if (isPlainObj(json)) {
  511. return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)}));
  512. }
  513. return json;
  514. }
  515. function fromJSDefault(json) {
  516. if (Array.isArray(json)) {
  517. return IndexedSeq(json).map(fromJSDefault).toList();
  518. }
  519. if (isPlainObj(json)) {
  520. return KeyedSeq(json).map(fromJSDefault).toMap();
  521. }
  522. return json;
  523. }
  524. function isPlainObj(value) {
  525. return value && (value.constructor === Object || value.constructor === undefined);
  526. }
  527. /**
  528. * An extension of the "same-value" algorithm as [described for use by ES6 Map
  529. * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
  530. *
  531. * NaN is considered the same as NaN, however -0 and 0 are considered the same
  532. * value, which is different from the algorithm described by
  533. * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
  534. *
  535. * This is extended further to allow Objects to describe the values they
  536. * represent, by way of `valueOf` or `equals` (and `hashCode`).
  537. *
  538. * Note: because of this extension, the key equality of Immutable.Map and the
  539. * value equality of Immutable.Set will differ from ES6 Map and Set.
  540. *
  541. * ### Defining custom values
  542. *
  543. * The easiest way to describe the value an object represents is by implementing
  544. * `valueOf`. For example, `Date` represents a value by returning a unix
  545. * timestamp for `valueOf`:
  546. *
  547. * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
  548. * var date2 = new Date(1234567890000);
  549. * date1.valueOf(); // 1234567890000
  550. * assert( date1 !== date2 );
  551. * assert( Immutable.is( date1, date2 ) );
  552. *
  553. * Note: overriding `valueOf` may have other implications if you use this object
  554. * where JavaScript expects a primitive, such as implicit string coercion.
  555. *
  556. * For more complex types, especially collections, implementing `valueOf` may
  557. * not be performant. An alternative is to implement `equals` and `hashCode`.
  558. *
  559. * `equals` takes another object, presumably of similar type, and returns true
  560. * if the it is equal. Equality is symmetrical, so the same result should be
  561. * returned if this and the argument are flipped.
  562. *
  563. * assert( a.equals(b) === b.equals(a) );
  564. *
  565. * `hashCode` returns a 32bit integer number representing the object which will
  566. * be used to determine how to store the value object in a Map or Set. You must
  567. * provide both or neither methods, one must not exist without the other.
  568. *
  569. * Also, an important relationship between these methods must be upheld: if two
  570. * values are equal, they *must* return the same hashCode. If the values are not
  571. * equal, they might have the same hashCode; this is called a hash collision,
  572. * and while undesirable for performance reasons, it is acceptable.
  573. *
  574. * if (a.equals(b)) {
  575. * assert( a.hashCode() === b.hashCode() );
  576. * }
  577. *
  578. * All Immutable collections implement `equals` and `hashCode`.
  579. *
  580. */
  581. function is(valueA, valueB) {
  582. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  583. return true;
  584. }
  585. if (!valueA || !valueB) {
  586. return false;
  587. }
  588. if (typeof valueA.valueOf === 'function' &&
  589. typeof valueB.valueOf === 'function') {
  590. valueA = valueA.valueOf();
  591. valueB = valueB.valueOf();
  592. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  593. return true;
  594. }
  595. if (!valueA || !valueB) {
  596. return false;
  597. }
  598. }
  599. if (typeof valueA.equals === 'function' &&
  600. typeof valueB.equals === 'function' &&
  601. valueA.equals(valueB)) {
  602. return true;
  603. }
  604. return false;
  605. }
  606. function deepEqual(a, b) {
  607. if (a === b) {
  608. return true;
  609. }
  610. if (
  611. !isIterable(b) ||
  612. a.size !== undefined && b.size !== undefined && a.size !== b.size ||
  613. a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash ||
  614. isKeyed(a) !== isKeyed(b) ||
  615. isIndexed(a) !== isIndexed(b) ||
  616. isOrdered(a) !== isOrdered(b)
  617. ) {
  618. return false;
  619. }
  620. if (a.size === 0 && b.size === 0) {
  621. return true;
  622. }
  623. var notAssociative = !isAssociative(a);
  624. if (isOrdered(a)) {
  625. var entries = a.entries();
  626. return b.every(function(v, k) {
  627. var entry = entries.next().value;
  628. return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
  629. }) && entries.next().done;
  630. }
  631. var flipped = false;
  632. if (a.size === undefined) {
  633. if (b.size === undefined) {
  634. if (typeof a.cacheResult === 'function') {
  635. a.cacheResult();
  636. }
  637. } else {
  638. flipped = true;
  639. var _ = a;
  640. a = b;
  641. b = _;
  642. }
  643. }
  644. var allEqual = true;
  645. var bSize = b.__iterate(function(v, k) {
  646. if (notAssociative ? !a.has(v) :
  647. flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) {
  648. allEqual = false;
  649. return false;
  650. }
  651. });
  652. return allEqual && a.size === bSize;
  653. }
  654. createClass(Repeat, IndexedSeq);
  655. function Repeat(value, times) {
  656. if (!(this instanceof Repeat)) {
  657. return new Repeat(value, times);
  658. }
  659. this._value = value;
  660. this.size = times === undefined ? Infinity : Math.max(0, times);
  661. if (this.size === 0) {
  662. if (EMPTY_REPEAT) {
  663. return EMPTY_REPEAT;
  664. }
  665. EMPTY_REPEAT = this;
  666. }
  667. }
  668. Repeat.prototype.toString = function() {
  669. if (this.size === 0) {
  670. return 'Repeat []';
  671. }
  672. return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
  673. };
  674. Repeat.prototype.get = function(index, notSetValue) {
  675. return this.has(index) ? this._value : notSetValue;
  676. };
  677. Repeat.prototype.includes = function(searchValue) {
  678. return is(this._value, searchValue);
  679. };
  680. Repeat.prototype.slice = function(begin, end) {
  681. var size = this.size;
  682. return wholeSlice(begin, end, size) ? this :
  683. new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size));
  684. };
  685. Repeat.prototype.reverse = function() {
  686. return this;
  687. };
  688. Repeat.prototype.indexOf = function(searchValue) {
  689. if (is(this._value, searchValue)) {
  690. return 0;
  691. }
  692. return -1;
  693. };
  694. Repeat.prototype.lastIndexOf = function(searchValue) {
  695. if (is(this._value, searchValue)) {
  696. return this.size;
  697. }
  698. return -1;
  699. };
  700. Repeat.prototype.__iterate = function(fn, reverse) {
  701. for (var ii = 0; ii < this.size; ii++) {
  702. if (fn(this._value, ii, this) === false) {
  703. return ii + 1;
  704. }
  705. }
  706. return ii;
  707. };
  708. Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this;
  709. var ii = 0;
  710. return new Iterator(function()
  711. {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()}
  712. );
  713. };
  714. Repeat.prototype.equals = function(other) {
  715. return other instanceof Repeat ?
  716. is(this._value, other._value) :
  717. deepEqual(other);
  718. };
  719. var EMPTY_REPEAT;
  720. function invariant(condition, error) {
  721. if (!condition) throw new Error(error);
  722. }
  723. createClass(Range, IndexedSeq);
  724. function Range(start, end, step) {
  725. if (!(this instanceof Range)) {
  726. return new Range(start, end, step);
  727. }
  728. invariant(step !== 0, 'Cannot step a Range by 0');
  729. start = start || 0;
  730. if (end === undefined) {
  731. end = Infinity;
  732. }
  733. step = step === undefined ? 1 : Math.abs(step);
  734. if (end < start) {
  735. step = -step;
  736. }
  737. this._start = start;
  738. this._end = end;
  739. this._step = step;
  740. this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
  741. if (this.size === 0) {
  742. if (EMPTY_RANGE) {
  743. return EMPTY_RANGE;
  744. }
  745. EMPTY_RANGE = this;
  746. }
  747. }
  748. Range.prototype.toString = function() {
  749. if (this.size === 0) {
  750. return 'Range []';
  751. }
  752. return 'Range [ ' +
  753. this._start + '...' + this._end +
  754. (this._step !== 1 ? ' by ' + this._step : '') +
  755. ' ]';
  756. };
  757. Range.prototype.get = function(index, notSetValue) {
  758. return this.has(index) ?
  759. this._start + wrapIndex(this, index) * this._step :
  760. notSetValue;
  761. };
  762. Range.prototype.includes = function(searchValue) {
  763. var possibleIndex = (searchValue - this._start) / this._step;
  764. return possibleIndex >= 0 &&
  765. possibleIndex < this.size &&
  766. possibleIndex === Math.floor(possibleIndex);
  767. };
  768. Range.prototype.slice = function(begin, end) {
  769. if (wholeSlice(begin, end, this.size)) {
  770. return this;
  771. }
  772. begin = resolveBegin(begin, this.size);
  773. end = resolveEnd(end, this.size);
  774. if (end <= begin) {
  775. return new Range(0, 0);
  776. }
  777. return new Range(this.get(begin, this._end), this.get(end, this._end), this._step);
  778. };
  779. Range.prototype.indexOf = function(searchValue) {
  780. var offsetValue = searchValue - this._start;
  781. if (offsetValue % this._step === 0) {
  782. var index = offsetValue / this._step;
  783. if (index >= 0 && index < this.size) {
  784. return index
  785. }
  786. }
  787. return -1;
  788. };
  789. Range.prototype.lastIndexOf = function(searchValue) {
  790. return this.indexOf(searchValue);
  791. };
  792. Range.prototype.__iterate = function(fn, reverse) {
  793. var maxIndex = this.size - 1;
  794. var step = this._step;
  795. var value = reverse ? this._start + maxIndex * step : this._start;
  796. for (var ii = 0; ii <= maxIndex; ii++) {
  797. if (fn(value, ii, this) === false) {
  798. return ii + 1;
  799. }
  800. value += reverse ? -step : step;
  801. }
  802. return ii;
  803. };
  804. Range.prototype.__iterator = function(type, reverse) {
  805. var maxIndex = this.size - 1;
  806. var step = this._step;
  807. var value = reverse ? this._start + maxIndex * step : this._start;
  808. var ii = 0;
  809. return new Iterator(function() {
  810. var v = value;
  811. value += reverse ? -step : step;
  812. return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v);
  813. });
  814. };
  815. Range.prototype.equals = function(other) {
  816. return other instanceof Range ?
  817. this._start === other._start &&
  818. this._end === other._end &&
  819. this._step === other._step :
  820. deepEqual(this, other);
  821. };
  822. var EMPTY_RANGE;
  823. createClass(Collection, Iterable);
  824. function Collection() {
  825. throw TypeError('Abstract');
  826. }
  827. createClass(KeyedCollection, Collection);function KeyedCollection() {}
  828. createClass(IndexedCollection, Collection);function IndexedCollection() {}
  829. createClass(SetCollection, Collection);function SetCollection() {}
  830. Collection.Keyed = KeyedCollection;
  831. Collection.Indexed = IndexedCollection;
  832. Collection.Set = SetCollection;
  833. var imul =
  834. typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ?
  835. Math.imul :
  836. function imul(a, b) {
  837. a = a | 0; // int
  838. b = b | 0; // int
  839. var c = a & 0xffff;
  840. var d = b & 0xffff;
  841. // Shift by 0 fixes the sign on the high part.
  842. return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int
  843. };
  844. // v8 has an optimization for storing 31-bit signed numbers.
  845. // Values which have either 00 or 11 as the high order bits qualify.
  846. // This function drops the highest order bit in a signed number, maintaining
  847. // the sign bit.
  848. function smi(i32) {
  849. return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF);
  850. }
  851. function hash(o) {
  852. if (o === false || o === null || o === undefined) {
  853. return 0;
  854. }
  855. if (typeof o.valueOf === 'function') {
  856. o = o.valueOf();
  857. if (o === false || o === null || o === undefined) {
  858. return 0;
  859. }
  860. }
  861. if (o === true) {
  862. return 1;
  863. }
  864. var type = typeof o;
  865. if (type === 'number') {
  866. if (o !== o || o === Infinity) {
  867. return 0;
  868. }
  869. var h = o | 0;
  870. if (h !== o) {
  871. h ^= o * 0xFFFFFFFF;
  872. }
  873. while (o > 0xFFFFFFFF) {
  874. o /= 0xFFFFFFFF;
  875. h ^= o;
  876. }
  877. return smi(h);
  878. }
  879. if (type === 'string') {
  880. return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o);
  881. }
  882. if (typeof o.hashCode === 'function') {
  883. return o.hashCode();
  884. }
  885. if (type === 'object') {
  886. return hashJSObj(o);
  887. }
  888. if (typeof o.toString === 'function') {
  889. return hashString(o.toString());
  890. }
  891. throw new Error('Value type ' + type + ' cannot be hashed.');
  892. }
  893. function cachedHashString(string) {
  894. var hash = stringHashCache[string];
  895. if (hash === undefined) {
  896. hash = hashString(string);
  897. if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
  898. STRING_HASH_CACHE_SIZE = 0;
  899. stringHashCache = {};
  900. }
  901. STRING_HASH_CACHE_SIZE++;
  902. stringHashCache[string] = hash;
  903. }
  904. return hash;
  905. }
  906. // http://jsperf.com/hashing-strings
  907. function hashString(string) {
  908. // This is the hash from JVM
  909. // The hash code for a string is computed as
  910. // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
  911. // where s[i] is the ith character of the string and n is the length of
  912. // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
  913. // (exclusive) by dropping high bits.
  914. var hash = 0;
  915. for (var ii = 0; ii < string.length; ii++) {
  916. hash = 31 * hash + string.charCodeAt(ii) | 0;
  917. }
  918. return smi(hash);
  919. }
  920. function hashJSObj(obj) {
  921. var hash;
  922. if (usingWeakMap) {
  923. hash = weakMap.get(obj);
  924. if (hash !== undefined) {
  925. return hash;
  926. }
  927. }
  928. hash = obj[UID_HASH_KEY];
  929. if (hash !== undefined) {
  930. return hash;
  931. }
  932. if (!canDefineProperty) {
  933. hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
  934. if (hash !== undefined) {
  935. return hash;
  936. }
  937. hash = getIENodeHash(obj);
  938. if (hash !== undefined) {
  939. return hash;
  940. }
  941. }
  942. hash = ++objHashUID;
  943. if (objHashUID & 0x40000000) {
  944. objHashUID = 0;
  945. }
  946. if (usingWeakMap) {
  947. weakMap.set(obj, hash);
  948. } else if (isExtensible !== undefined && isExtensible(obj) === false) {
  949. throw new Error('Non-extensible objects are not allowed as keys.');
  950. } else if (canDefineProperty) {
  951. Object.defineProperty(obj, UID_HASH_KEY, {
  952. 'enumerable': false,
  953. 'configurable': false,
  954. 'writable': false,
  955. 'value': hash
  956. });
  957. } else if (obj.propertyIsEnumerable !== undefined &&
  958. obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) {
  959. // Since we can't define a non-enumerable property on the object
  960. // we'll hijack one of the less-used non-enumerable properties to
  961. // save our hash on it. Since this is a function it will not show up in
  962. // `JSON.stringify` which is what we want.
  963. obj.propertyIsEnumerable = function() {
  964. return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments);
  965. };
  966. obj.propertyIsEnumerable[UID_HASH_KEY] = hash;
  967. } else if (obj.nodeType !== undefined) {
  968. // At this point we couldn't get the IE `uniqueID` to use as a hash
  969. // and we couldn't use a non-enumerable property to exploit the
  970. // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
  971. // itself.
  972. obj[UID_HASH_KEY] = hash;
  973. } else {
  974. throw new Error('Unable to set a non-enumerable property on object.');
  975. }
  976. return hash;
  977. }
  978. // Get references to ES5 object methods.
  979. var isExtensible = Object.isExtensible;
  980. // True if Object.defineProperty works as expected. IE8 fails this test.
  981. var canDefineProperty = (function() {
  982. try {
  983. Object.defineProperty({}, '@', {});
  984. return true;
  985. } catch (e) {
  986. return false;
  987. }
  988. }());
  989. // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
  990. // and avoid memory leaks from the IE cloneNode bug.
  991. function getIENodeHash(node) {
  992. if (node && node.nodeType > 0) {
  993. switch (node.nodeType) {
  994. case 1: // Element
  995. return node.uniqueID;
  996. case 9: // Document
  997. return node.documentElement && node.documentElement.uniqueID;
  998. }
  999. }
  1000. }
  1001. // If possible, use a WeakMap.
  1002. var usingWeakMap = typeof WeakMap === 'function';
  1003. var weakMap;
  1004. if (usingWeakMap) {
  1005. weakMap = new WeakMap();
  1006. }
  1007. var objHashUID = 0;
  1008. var UID_HASH_KEY = '__immutablehash__';
  1009. if (typeof Symbol === 'function') {
  1010. UID_HASH_KEY = Symbol(UID_HASH_KEY);
  1011. }
  1012. var STRING_HASH_CACHE_MIN_STRLEN = 16;
  1013. var STRING_HASH_CACHE_MAX_SIZE = 255;
  1014. var STRING_HASH_CACHE_SIZE = 0;
  1015. var stringHashCache = {};
  1016. function assertNotInfinite(size) {
  1017. invariant(
  1018. size !== Infinity,
  1019. 'Cannot perform this action with an infinite size.'
  1020. );
  1021. }
  1022. createClass(Map, KeyedCollection);
  1023. // @pragma Construction
  1024. function Map(value) {
  1025. return value === null || value === undefined ? emptyMap() :
  1026. isMap(value) && !isOrdered(value) ? value :
  1027. emptyMap().withMutations(function(map ) {
  1028. var iter = KeyedIterable(value);
  1029. assertNotInfinite(iter.size);
  1030. iter.forEach(function(v, k) {return map.set(k, v)});
  1031. });
  1032. }
  1033. Map.of = function() {var keyValues = SLICE$0.call(arguments, 0);
  1034. return emptyMap().withMutations(function(map ) {
  1035. for (var i = 0; i < keyValues.length; i += 2) {
  1036. if (i + 1 >= keyValues.length) {
  1037. throw new Error('Missing value for key: ' + keyValues[i]);
  1038. }
  1039. map.set(keyValues[i], keyValues[i + 1]);
  1040. }
  1041. });
  1042. };
  1043. Map.prototype.toString = function() {
  1044. return this.__toString('Map {', '}');
  1045. };
  1046. // @pragma Access
  1047. Map.prototype.get = function(k, notSetValue) {
  1048. return this._root ?
  1049. this._root.get(0, undefined, k, notSetValue) :
  1050. notSetValue;
  1051. };
  1052. // @pragma Modification
  1053. Map.prototype.set = function(k, v) {
  1054. return updateMap(this, k, v);
  1055. };
  1056. Map.prototype.setIn = function(keyPath, v) {
  1057. return this.updateIn(keyPath, NOT_SET, function() {return v});
  1058. };
  1059. Map.prototype.remove = function(k) {
  1060. return updateMap(this, k, NOT_SET);
  1061. };
  1062. Map.prototype.deleteIn = function(keyPath) {
  1063. return this.updateIn(keyPath, function() {return NOT_SET});
  1064. };
  1065. Map.prototype.update = function(k, notSetValue, updater) {
  1066. return arguments.length === 1 ?
  1067. k(this) :
  1068. this.updateIn([k], notSetValue, updater);
  1069. };
  1070. Map.prototype.updateIn = function(keyPath, notSetValue, updater) {
  1071. if (!updater) {
  1072. updater = notSetValue;
  1073. notSetValue = undefined;
  1074. }
  1075. var updatedValue = updateInDeepMap(
  1076. this,
  1077. forceIterator(keyPath),
  1078. notSetValue,
  1079. updater
  1080. );
  1081. return updatedValue === NOT_SET ? undefined : updatedValue;
  1082. };
  1083. Map.prototype.clear = function() {
  1084. if (this.size === 0) {
  1085. return this;
  1086. }
  1087. if (this.__ownerID) {
  1088. this.size = 0;
  1089. this._root = null;
  1090. this.__hash = undefined;
  1091. this.__altered = true;
  1092. return this;
  1093. }
  1094. return emptyMap();
  1095. };
  1096. // @pragma Composition
  1097. Map.prototype.merge = function(/*...iters*/) {
  1098. return mergeIntoMapWith(this, undefined, arguments);
  1099. };
  1100. Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  1101. return mergeIntoMapWith(this, merger, iters);
  1102. };
  1103. Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
  1104. return this.updateIn(
  1105. keyPath,
  1106. emptyMap(),
  1107. function(m ) {return typeof m.merge === 'function' ?
  1108. m.merge.apply(m, iters) :
  1109. iters[iters.length - 1]}
  1110. );
  1111. };
  1112. Map.prototype.mergeDeep = function(/*...iters*/) {
  1113. return mergeIntoMapWith(this, deepMerger, arguments);
  1114. };
  1115. Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  1116. return mergeIntoMapWith(this, deepMergerWith(merger), iters);
  1117. };
  1118. Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
  1119. return this.updateIn(
  1120. keyPath,
  1121. emptyMap(),
  1122. function(m ) {return typeof m.mergeDeep === 'function' ?
  1123. m.mergeDeep.apply(m, iters) :
  1124. iters[iters.length - 1]}
  1125. );
  1126. };
  1127. Map.prototype.sort = function(comparator) {
  1128. // Late binding
  1129. return OrderedMap(sortFactory(this, comparator));
  1130. };
  1131. Map.prototype.sortBy = function(mapper, comparator) {
  1132. // Late binding
  1133. return OrderedMap(sortFactory(this, comparator, mapper));
  1134. };
  1135. // @pragma Mutability
  1136. Map.prototype.withMutations = function(fn) {
  1137. var mutable = this.asMutable();
  1138. fn(mutable);
  1139. return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
  1140. };
  1141. Map.prototype.asMutable = function() {
  1142. return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
  1143. };
  1144. Map.prototype.asImmutable = function() {
  1145. return this.__ensureOwner();
  1146. };
  1147. Map.prototype.wasAltered = function() {
  1148. return this.__altered;
  1149. };
  1150. Map.prototype.__iterator = function(type, reverse) {
  1151. return new MapIterator(this, type, reverse);
  1152. };
  1153. Map.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  1154. var iterations = 0;
  1155. this._root && this._root.iterate(function(entry ) {
  1156. iterations++;
  1157. return fn(entry[1], entry[0], this$0);
  1158. }, reverse);
  1159. return iterations;
  1160. };
  1161. Map.prototype.__ensureOwner = function(ownerID) {
  1162. if (ownerID === this.__ownerID) {
  1163. return this;
  1164. }
  1165. if (!ownerID) {
  1166. this.__ownerID = ownerID;
  1167. this.__altered = false;
  1168. return this;
  1169. }
  1170. return makeMap(this.size, this._root, ownerID, this.__hash);
  1171. };
  1172. function isMap(maybeMap) {
  1173. return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]);
  1174. }
  1175. Map.isMap = isMap;
  1176. var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@';
  1177. var MapPrototype = Map.prototype;
  1178. MapPrototype[IS_MAP_SENTINEL] = true;
  1179. MapPrototype[DELETE] = MapPrototype.remove;
  1180. MapPrototype.removeIn = MapPrototype.deleteIn;
  1181. // #pragma Trie Nodes
  1182. function ArrayMapNode(ownerID, entries) {
  1183. this.ownerID = ownerID;
  1184. this.entries = entries;
  1185. }
  1186. ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1187. var entries = this.entries;
  1188. for (var ii = 0, len = entries.length; ii < len; ii++) {
  1189. if (is(key, entries[ii][0])) {
  1190. return entries[ii][1];
  1191. }
  1192. }
  1193. return notSetValue;
  1194. };
  1195. ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1196. var removed = value === NOT_SET;
  1197. var entries = this.entries;
  1198. var idx = 0;
  1199. for (var len = entries.length; idx < len; idx++) {
  1200. if (is(key, entries[idx][0])) {
  1201. break;
  1202. }
  1203. }
  1204. var exists = idx < len;
  1205. if (exists ? entries[idx][1] === value : removed) {
  1206. return this;
  1207. }
  1208. SetRef(didAlter);
  1209. (removed || !exists) && SetRef(didChangeSize);
  1210. if (removed && entries.length === 1) {
  1211. return; // undefined
  1212. }
  1213. if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
  1214. return createNodes(ownerID, entries, key, value);
  1215. }
  1216. var isEditable = ownerID && ownerID === this.ownerID;
  1217. var newEntries = isEditable ? entries : arrCopy(entries);
  1218. if (exists) {
  1219. if (removed) {
  1220. idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
  1221. } else {
  1222. newEntries[idx] = [key, value];
  1223. }
  1224. } else {
  1225. newEntries.push([key, value]);
  1226. }
  1227. if (isEditable) {
  1228. this.entries = newEntries;
  1229. return this;
  1230. }
  1231. return new ArrayMapNode(ownerID, newEntries);
  1232. };
  1233. function BitmapIndexedNode(ownerID, bitmap, nodes) {
  1234. this.ownerID = ownerID;
  1235. this.bitmap = bitmap;
  1236. this.nodes = nodes;
  1237. }
  1238. BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1239. if (keyHash === undefined) {
  1240. keyHash = hash(key);
  1241. }
  1242. var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK));
  1243. var bitmap = this.bitmap;
  1244. return (bitmap & bit) === 0 ? notSetValue :
  1245. this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue);
  1246. };
  1247. BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1248. if (keyHash === undefined) {
  1249. keyHash = hash(key);
  1250. }
  1251. var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  1252. var bit = 1 << keyHashFrag;
  1253. var bitmap = this.bitmap;
  1254. var exists = (bitmap & bit) !== 0;
  1255. if (!exists && value === NOT_SET) {
  1256. return this;
  1257. }
  1258. var idx = popCount(bitmap & (bit - 1));
  1259. var nodes = this.nodes;
  1260. var node = exists ? nodes[idx] : undefined;
  1261. var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
  1262. if (newNode === node) {
  1263. return this;
  1264. }
  1265. if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
  1266. return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
  1267. }
  1268. if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) {
  1269. return nodes[idx ^ 1];
  1270. }
  1271. if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
  1272. return newNode;
  1273. }
  1274. var isEditable = ownerID && ownerID === this.ownerID;
  1275. var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit;
  1276. var newNodes = exists ? newNode ?
  1277. setIn(nodes, idx, newNode, isEditable) :
  1278. spliceOut(nodes, idx, isEditable) :
  1279. spliceIn(nodes, idx, newNode, isEditable);
  1280. if (isEditable) {
  1281. this.bitmap = newBitmap;
  1282. this.nodes = newNodes;
  1283. return this;
  1284. }
  1285. return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
  1286. };
  1287. function HashArrayMapNode(ownerID, count, nodes) {
  1288. this.ownerID = ownerID;
  1289. this.count = count;
  1290. this.nodes = nodes;
  1291. }
  1292. HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1293. if (keyHash === undefined) {
  1294. keyHash = hash(key);
  1295. }
  1296. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  1297. var node = this.nodes[idx];
  1298. return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue;
  1299. };
  1300. HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1301. if (keyHash === undefined) {
  1302. keyHash = hash(key);
  1303. }
  1304. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  1305. var removed = value === NOT_SET;
  1306. var nodes = this.nodes;
  1307. var node = nodes[idx];
  1308. if (removed && !node) {
  1309. return this;
  1310. }
  1311. var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
  1312. if (newNode === node) {
  1313. return this;
  1314. }
  1315. var newCount = this.count;
  1316. if (!node) {
  1317. newCount++;
  1318. } else if (!newNode) {
  1319. newCount--;
  1320. if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
  1321. return packNodes(ownerID, nodes, newCount, idx);
  1322. }
  1323. }
  1324. var isEditable = ownerID && ownerID === this.ownerID;
  1325. var newNodes = setIn(nodes, idx, newNode, isEditable);
  1326. if (isEditable) {
  1327. this.count = newCount;
  1328. this.nodes = newNodes;
  1329. return this;
  1330. }
  1331. return new HashArrayMapNode(ownerID, newCount, newNodes);
  1332. };
  1333. function HashCollisionNode(ownerID, keyHash, entries) {
  1334. this.ownerID = ownerID;
  1335. this.keyHash = keyHash;
  1336. this.entries = entries;
  1337. }
  1338. HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1339. var entries = this.entries;
  1340. for (var ii = 0, len = entries.length; ii < len; ii++) {
  1341. if (is(key, entries[ii][0])) {
  1342. return entries[ii][1];
  1343. }
  1344. }
  1345. return notSetValue;
  1346. };
  1347. HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1348. if (keyHash === undefined) {
  1349. keyHash = hash(key);
  1350. }
  1351. var removed = value === NOT_SET;
  1352. if (keyHash !== this.keyHash) {
  1353. if (removed) {
  1354. return this;
  1355. }
  1356. SetRef(didAlter);
  1357. SetRef(didChangeSize);
  1358. return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
  1359. }
  1360. var entries = this.entries;
  1361. var idx = 0;
  1362. for (var len = entries.length; idx < len; idx++) {
  1363. if (is(key, entries[idx][0])) {
  1364. break;
  1365. }
  1366. }
  1367. var exists = idx < len;
  1368. if (exists ? entries[idx][1] === value : removed) {
  1369. return this;
  1370. }
  1371. SetRef(didAlter);
  1372. (removed || !exists) && SetRef(didChangeSize);
  1373. if (removed && len === 2) {
  1374. return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
  1375. }
  1376. var isEditable = ownerID && ownerID === this.ownerID;
  1377. var newEntries = isEditable ? entries : arrCopy(entries);
  1378. if (exists) {
  1379. if (removed) {
  1380. idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
  1381. } else {
  1382. newEntries[idx] = [key, value];
  1383. }
  1384. } else {
  1385. newEntries.push([key, value]);
  1386. }
  1387. if (isEditable) {
  1388. this.entries = newEntries;
  1389. return this;
  1390. }
  1391. return new HashCollisionNode(ownerID, this.keyHash, newEntries);
  1392. };
  1393. function ValueNode(ownerID, keyHash, entry) {
  1394. this.ownerID = ownerID;
  1395. this.keyHash = keyHash;
  1396. this.entry = entry;
  1397. }
  1398. ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1399. return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
  1400. };
  1401. ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1402. var removed = value === NOT_SET;
  1403. var keyMatch = is(key, this.entry[0]);
  1404. if (keyMatch ? value === this.entry[1] : removed) {
  1405. return this;
  1406. }
  1407. SetRef(didAlter);
  1408. if (removed) {
  1409. SetRef(didChangeSize);
  1410. return; // undefined
  1411. }
  1412. if (keyMatch) {
  1413. if (ownerID && ownerID === this.ownerID) {
  1414. this.entry[1] = value;
  1415. return this;
  1416. }
  1417. return new ValueNode(ownerID, this.keyHash, [key, value]);
  1418. }
  1419. SetRef(didChangeSize);
  1420. return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
  1421. };
  1422. // #pragma Iterators
  1423. ArrayMapNode.prototype.iterate =
  1424. HashCollisionNode.prototype.iterate = function (fn, reverse) {
  1425. var entries = this.entries;
  1426. for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
  1427. if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
  1428. return false;
  1429. }
  1430. }
  1431. }
  1432. BitmapIndexedNode.prototype.iterate =
  1433. HashArrayMapNode.prototype.iterate = function (fn, reverse) {
  1434. var nodes = this.nodes;
  1435. for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
  1436. var node = nodes[reverse ? maxIndex - ii : ii];
  1437. if (node && node.iterate(fn, reverse) === false) {
  1438. return false;
  1439. }
  1440. }
  1441. }
  1442. ValueNode.prototype.iterate = function (fn, reverse) {
  1443. return fn(this.entry);
  1444. }
  1445. createClass(MapIterator, Iterator);
  1446. function MapIterator(map, type, reverse) {
  1447. this._type = type;
  1448. this._reverse = reverse;
  1449. this._stack = map._root && mapIteratorFrame(map._root);
  1450. }
  1451. MapIterator.prototype.next = function() {
  1452. var type = this._type;
  1453. var stack = this._stack;
  1454. while (stack) {
  1455. var node = stack.node;
  1456. var index = stack.index++;
  1457. var maxIndex;
  1458. if (node.entry) {
  1459. if (index === 0) {
  1460. return mapIteratorValue(type, node.entry);
  1461. }
  1462. } else if (node.entries) {
  1463. maxIndex = node.entries.length - 1;
  1464. if (index <= maxIndex) {
  1465. return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]);
  1466. }
  1467. } else {
  1468. maxIndex = node.nodes.length - 1;
  1469. if (index <= maxIndex) {
  1470. var subNode = node.nodes[this._reverse ? maxIndex - index : index];
  1471. if (subNode) {
  1472. if (subNode.entry) {
  1473. return mapIteratorValue(type, subNode.entry);
  1474. }
  1475. stack = this._stack = mapIteratorFrame(subNode, stack);
  1476. }
  1477. continue;
  1478. }
  1479. }
  1480. stack = this._stack = this._stack.__prev;
  1481. }
  1482. return iteratorDone();
  1483. };
  1484. function mapIteratorValue(type, entry) {
  1485. return iteratorValue(type, entry[0], entry[1]);
  1486. }
  1487. function mapIteratorFrame(node, prev) {
  1488. return {
  1489. node: node,
  1490. index: 0,
  1491. __prev: prev
  1492. };
  1493. }
  1494. function makeMap(size, root, ownerID, hash) {
  1495. var map = Object.create(MapPrototype);
  1496. map.size = size;
  1497. map._root = root;
  1498. map.__ownerID = ownerID;
  1499. map.__hash = hash;
  1500. map.__altered = false;
  1501. return map;
  1502. }
  1503. var EMPTY_MAP;
  1504. function emptyMap() {
  1505. return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
  1506. }
  1507. function updateMap(map, k, v) {
  1508. var newRoot;
  1509. var newSize;
  1510. if (!map._root) {
  1511. if (v === NOT_SET) {
  1512. return map;
  1513. }
  1514. newSize = 1;
  1515. newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
  1516. } else {
  1517. var didChangeSize = MakeRef(CHANGE_LENGTH);
  1518. var didAlter = MakeRef(DID_ALTER);
  1519. newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter);
  1520. if (!didAlter.value) {
  1521. return map;
  1522. }
  1523. newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0);
  1524. }
  1525. if (map.__ownerID) {
  1526. map.size = newSize;
  1527. map._root = newRoot;
  1528. map.__hash = undefined;
  1529. map.__altered = true;
  1530. return map;
  1531. }
  1532. return newRoot ? makeMap(newSize, newRoot) : emptyMap();
  1533. }
  1534. function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1535. if (!node) {
  1536. if (value === NOT_SET) {
  1537. return node;
  1538. }
  1539. SetRef(didAlter);
  1540. SetRef(didChangeSize);
  1541. return new ValueNode(ownerID, keyHash, [key, value]);
  1542. }
  1543. return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter);
  1544. }
  1545. function isLeafNode(node) {
  1546. return node.constructor === ValueNode || node.constructor === HashCollisionNode;
  1547. }
  1548. function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
  1549. if (node.keyHash === keyHash) {
  1550. return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
  1551. }
  1552. var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
  1553. var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  1554. var newNode;
  1555. var nodes = idx1 === idx2 ?
  1556. [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] :
  1557. ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]);
  1558. return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
  1559. }
  1560. function createNodes(ownerID, entries, key, value) {
  1561. if (!ownerID) {
  1562. ownerID = new OwnerID();
  1563. }
  1564. var node = new ValueNode(ownerID, hash(key), [key, value]);
  1565. for (var ii = 0; ii < entries.length; ii++) {
  1566. var entry = entries[ii];
  1567. node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
  1568. }
  1569. return node;
  1570. }
  1571. function packNodes(ownerID, nodes, count, excluding) {
  1572. var bitmap = 0;
  1573. var packedII = 0;
  1574. var packedNodes = new Array(count);
  1575. for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
  1576. var node = nodes[ii];
  1577. if (node !== undefined && ii !== excluding) {
  1578. bitmap |= bit;
  1579. packedNodes[packedII++] = node;
  1580. }
  1581. }
  1582. return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
  1583. }
  1584. function expandNodes(ownerID, nodes, bitmap, including, node) {
  1585. var count = 0;
  1586. var expandedNodes = new Array(SIZE);
  1587. for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
  1588. expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
  1589. }
  1590. expandedNodes[including] = node;
  1591. return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
  1592. }
  1593. function mergeIntoMapWith(map, merger, iterables) {
  1594. var iters = [];
  1595. for (var ii = 0; ii < iterables.length; ii++) {
  1596. var value = iterables[ii];
  1597. var iter = KeyedIterable(value);
  1598. if (!isIterable(value)) {
  1599. iter = iter.map(function(v ) {return fromJS(v)});
  1600. }
  1601. iters.push(iter);
  1602. }
  1603. return mergeIntoCollectionWith(map, merger, iters);
  1604. }
  1605. function deepMerger(existing, value, key) {
  1606. return existing && existing.mergeDeep && isIterable(value) ?
  1607. existing.mergeDeep(value) :
  1608. is(existing, value) ? existing : value;
  1609. }
  1610. function deepMergerWith(merger) {
  1611. return function(existing, value, key) {
  1612. if (existing && existing.mergeDeepWith && isIterable(value)) {
  1613. return existing.mergeDeepWith(merger, value);
  1614. }
  1615. var nextValue = merger(existing, value, key);
  1616. return is(existing, nextValue) ? existing : nextValue;
  1617. };
  1618. }
  1619. function mergeIntoCollectionWith(collection, merger, iters) {
  1620. iters = iters.filter(function(x ) {return x.size !== 0});
  1621. if (iters.length === 0) {
  1622. return collection;
  1623. }
  1624. if (collection.size === 0 && !collection.__ownerID && iters.length === 1) {
  1625. return collection.constructor(iters[0]);
  1626. }
  1627. return collection.withMutations(function(collection ) {
  1628. var mergeIntoMap = merger ?
  1629. function(value, key) {
  1630. collection.update(key, NOT_SET, function(existing )
  1631. {return existing === NOT_SET ? value : merger(existing, value, key)}
  1632. );
  1633. } :
  1634. function(value, key) {
  1635. collection.set(key, value);
  1636. }
  1637. for (var ii = 0; ii < iters.length; ii++) {
  1638. iters[ii].forEach(mergeIntoMap);
  1639. }
  1640. });
  1641. }
  1642. function updateInDeepMap(existing, keyPathIter, notSetValue, updater) {
  1643. var isNotSet = existing === NOT_SET;
  1644. var step = keyPathIter.next();
  1645. if (step.done) {
  1646. var existingValue = isNotSet ? notSetValue : existing;
  1647. var newValue = updater(existingValue);
  1648. return newValue === existingValue ? existing : newValue;
  1649. }
  1650. invariant(
  1651. isNotSet || (existing && existing.set),
  1652. 'invalid keyPath'
  1653. );
  1654. var key = step.value;
  1655. var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET);
  1656. var nextUpdated = updateInDeepMap(
  1657. nextExisting,
  1658. keyPathIter,
  1659. notSetValue,
  1660. updater
  1661. );
  1662. return nextUpdated === nextExisting ? existing :
  1663. nextUpdated === NOT_SET ? existing.remove(key) :
  1664. (isNotSet ? emptyMap() : existing).set(key, nextUpdated);
  1665. }
  1666. function popCount(x) {
  1667. x = x - ((x >> 1) & 0x55555555);
  1668. x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
  1669. x = (x + (x >> 4)) & 0x0f0f0f0f;
  1670. x = x + (x >> 8);
  1671. x = x + (x >> 16);
  1672. return x & 0x7f;
  1673. }
  1674. function setIn(array, idx, val, canEdit) {
  1675. var newArray = canEdit ? array : arrCopy(array);
  1676. newArray[idx] = val;
  1677. return newArray;
  1678. }
  1679. function spliceIn(array, idx, val, canEdit) {
  1680. var newLen = array.length + 1;
  1681. if (canEdit && idx + 1 === newLen) {
  1682. array[idx] = val;
  1683. return array;
  1684. }
  1685. var newArray = new Array(newLen);
  1686. var after = 0;
  1687. for (var ii = 0; ii < newLen; ii++) {
  1688. if (ii === idx) {
  1689. newArray[ii] = val;
  1690. after = -1;
  1691. } else {
  1692. newArray[ii] = array[ii + after];
  1693. }
  1694. }
  1695. return newArray;
  1696. }
  1697. function spliceOut(array, idx, canEdit) {
  1698. var newLen = array.length - 1;
  1699. if (canEdit && idx === newLen) {
  1700. array.pop();
  1701. return array;
  1702. }
  1703. var newArray = new Array(newLen);
  1704. var after = 0;
  1705. for (var ii = 0; ii < newLen; ii++) {
  1706. if (ii === idx) {
  1707. after = 1;
  1708. }
  1709. newArray[ii] = array[ii + after];
  1710. }
  1711. return newArray;
  1712. }
  1713. var MAX_ARRAY_MAP_SIZE = SIZE / 4;
  1714. var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
  1715. var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
  1716. createClass(List, IndexedCollection);
  1717. // @pragma Construction
  1718. function List(value) {
  1719. var empty = emptyList();
  1720. if (value === null || value === undefined) {
  1721. return empty;
  1722. }
  1723. if (isList(value)) {
  1724. return value;
  1725. }
  1726. var iter = IndexedIterable(value);
  1727. var size = iter.size;
  1728. if (size === 0) {
  1729. return empty;
  1730. }
  1731. assertNotInfinite(size);
  1732. if (size > 0 && size < SIZE) {
  1733. return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
  1734. }
  1735. return empty.withMutations(function(list ) {
  1736. list.setSize(size);
  1737. iter.forEach(function(v, i) {return list.set(i, v)});
  1738. });
  1739. }
  1740. List.of = function(/*...values*/) {
  1741. return this(arguments);
  1742. };
  1743. List.prototype.toString = function() {
  1744. return this.__toString('List [', ']');
  1745. };
  1746. // @pragma Access
  1747. List.prototype.get = function(index, notSetValue) {
  1748. index = wrapIndex(this, index);
  1749. if (index >= 0 && index < this.size) {
  1750. index += this._origin;
  1751. var node = listNodeFor(this, index);
  1752. return node && node.array[index & MASK];
  1753. }
  1754. return notSetValue;
  1755. };
  1756. // @pragma Modification
  1757. List.prototype.set = function(index, value) {
  1758. return updateList(this, index, value);
  1759. };
  1760. List.prototype.remove = function(index) {
  1761. return !this.has(index) ? this :
  1762. index === 0 ? this.shift() :
  1763. index === this.size - 1 ? this.pop() :
  1764. this.splice(index, 1);
  1765. };
  1766. List.prototype.insert = function(index, value) {
  1767. return this.splice(index, 0, value);
  1768. };
  1769. List.prototype.clear = function() {
  1770. if (this.size === 0) {
  1771. return this;
  1772. }
  1773. if (this.__ownerID) {
  1774. this.size = this._origin = this._capacity = 0;
  1775. this._level = SHIFT;
  1776. this._root = this._tail = null;
  1777. this.__hash = undefined;
  1778. this.__altered = true;
  1779. return this;
  1780. }
  1781. return emptyList();
  1782. };
  1783. List.prototype.push = function(/*...values*/) {
  1784. var values = arguments;
  1785. var oldSize = this.size;
  1786. return this.withMutations(function(list ) {
  1787. setListBounds(list, 0, oldSize + values.length);
  1788. for (var ii = 0; ii < values.length; ii++) {
  1789. list.set(oldSize + ii, values[ii]);
  1790. }
  1791. });
  1792. };
  1793. List.prototype.pop = function() {
  1794. return setListBounds(this, 0, -1);
  1795. };
  1796. List.prototype.unshift = function(/*...values*/) {
  1797. var values = arguments;
  1798. return this.withMutations(function(list ) {
  1799. setListBounds(list, -values.length);
  1800. for (var ii = 0; ii < values.length; ii++) {
  1801. list.set(ii, values[ii]);
  1802. }
  1803. });
  1804. };
  1805. List.prototype.shift = function() {
  1806. return setListBounds(this, 1);
  1807. };
  1808. // @pragma Composition
  1809. List.prototype.merge = function(/*...iters*/) {
  1810. return mergeIntoListWith(this, undefined, arguments);
  1811. };
  1812. List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  1813. return mergeIntoListWith(this, merger, iters);
  1814. };
  1815. List.prototype.mergeDeep = function(/*...iters*/) {
  1816. return mergeIntoListWith(this, deepMerger, arguments);
  1817. };
  1818. List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  1819. return mergeIntoListWith(this, deepMergerWith(merger), iters);
  1820. };
  1821. List.prototype.setSize = function(size) {
  1822. return setListBounds(this, 0, size);
  1823. };
  1824. // @pragma Iteration
  1825. List.prototype.slice = function(begin, end) {
  1826. var size = this.size;
  1827. if (wholeSlice(begin, end, size)) {
  1828. return this;
  1829. }
  1830. return setListBounds(
  1831. this,
  1832. resolveBegin(begin, size),
  1833. resolveEnd(end, size)
  1834. );
  1835. };
  1836. List.prototype.__iterator = function(type, reverse) {
  1837. var index = 0;
  1838. var values = iterateList(this, reverse);
  1839. return new Iterator(function() {
  1840. var value = values();
  1841. return value === DONE ?
  1842. iteratorDone() :
  1843. iteratorValue(type, index++, value);
  1844. });
  1845. };
  1846. List.prototype.__iterate = function(fn, reverse) {
  1847. var index = 0;
  1848. var values = iterateList(this, reverse);
  1849. var value;
  1850. while ((value = values()) !== DONE) {
  1851. if (fn(value, index++, this) === false) {
  1852. break;
  1853. }
  1854. }
  1855. return index;
  1856. };
  1857. List.prototype.__ensureOwner = function(ownerID) {
  1858. if (ownerID === this.__ownerID) {
  1859. return this;
  1860. }
  1861. if (!ownerID) {
  1862. this.__ownerID = ownerID;
  1863. return this;
  1864. }
  1865. return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash);
  1866. };
  1867. function isList(maybeList) {
  1868. return !!(maybeList && maybeList[IS_LIST_SENTINEL]);
  1869. }
  1870. List.isList = isList;
  1871. var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@';
  1872. var ListPrototype = List.prototype;
  1873. ListPrototype[IS_LIST_SENTINEL] = true;
  1874. ListPrototype[DELETE] = ListPrototype.remove;
  1875. ListPrototype.setIn = MapPrototype.setIn;
  1876. ListPrototype.deleteIn =
  1877. ListPrototype.removeIn = MapPrototype.removeIn;
  1878. ListPrototype.update = MapPrototype.update;
  1879. ListPrototype.updateIn = MapPrototype.updateIn;
  1880. ListPrototype.mergeIn = MapPrototype.mergeIn;
  1881. ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  1882. ListPrototype.withMutations = MapPrototype.withMutations;
  1883. ListPrototype.asMutable = MapPrototype.asMutable;
  1884. ListPrototype.asImmutable = MapPrototype.asImmutable;
  1885. ListPrototype.wasAltered = MapPrototype.wasAltered;
  1886. function VNode(array, ownerID) {
  1887. this.array = array;
  1888. this.ownerID = ownerID;
  1889. }
  1890. // TODO: seems like these methods are very similar
  1891. VNode.prototype.removeBefore = function(ownerID, level, index) {
  1892. if (index === level ? 1 << level : 0 || this.array.length === 0) {
  1893. return this;
  1894. }
  1895. var originIndex = (index >>> level) & MASK;
  1896. if (originIndex >= this.array.length) {
  1897. return new VNode([], ownerID);
  1898. }
  1899. var removingFirst = originIndex === 0;
  1900. var newChild;
  1901. if (level > 0) {
  1902. var oldChild = this.array[originIndex];
  1903. newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
  1904. if (newChild === oldChild && removingFirst) {
  1905. return this;
  1906. }
  1907. }
  1908. if (removingFirst && !newChild) {
  1909. return this;
  1910. }
  1911. var editable = editableVNode(this, ownerID);
  1912. if (!removingFirst) {
  1913. for (var ii = 0; ii < originIndex; ii++) {
  1914. editable.array[ii] = undefined;
  1915. }
  1916. }
  1917. if (newChild) {
  1918. editable.array[originIndex] = newChild;
  1919. }
  1920. return editable;
  1921. };
  1922. VNode.prototype.removeAfter = function(ownerID, level, index) {
  1923. if (index === (level ? 1 << level : 0) || this.array.length === 0) {
  1924. return this;
  1925. }
  1926. var sizeIndex = ((index - 1) >>> level) & MASK;
  1927. if (sizeIndex >= this.array.length) {
  1928. return this;
  1929. }
  1930. var newChild;
  1931. if (level > 0) {
  1932. var oldChild = this.array[sizeIndex];
  1933. newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
  1934. if (newChild === oldChild && sizeIndex === this.array.length - 1) {
  1935. return this;
  1936. }
  1937. }
  1938. var editable = editableVNode(this, ownerID);
  1939. editable.array.splice(sizeIndex + 1);
  1940. if (newChild) {
  1941. editable.array[sizeIndex] = newChild;
  1942. }
  1943. return editable;
  1944. };
  1945. var DONE = {};
  1946. function iterateList(list, reverse) {
  1947. var left = list._origin;
  1948. var right = list._capacity;
  1949. var tailPos = getTailOffset(right);
  1950. var tail = list._tail;
  1951. return iterateNodeOrLeaf(list._root, list._level, 0);
  1952. function iterateNodeOrLeaf(node, level, offset) {
  1953. return level === 0 ?
  1954. iterateLeaf(node, offset) :
  1955. iterateNode(node, level, offset);
  1956. }
  1957. function iterateLeaf(node, offset) {
  1958. var array = offset === tailPos ? tail && tail.array : node && node.array;
  1959. var from = offset > left ? 0 : left - offset;
  1960. var to = right - offset;
  1961. if (to > SIZE) {
  1962. to = SIZE;
  1963. }
  1964. return function() {
  1965. if (from === to) {
  1966. return DONE;
  1967. }
  1968. var idx = reverse ? --to : from++;
  1969. return array && array[idx];
  1970. };
  1971. }
  1972. function iterateNode(node, level, offset) {
  1973. var values;
  1974. var array = node && node.array;
  1975. var from = offset > left ? 0 : (left - offset) >> level;
  1976. var to = ((right - offset) >> level) + 1;
  1977. if (to > SIZE) {
  1978. to = SIZE;
  1979. }
  1980. return function() {
  1981. do {
  1982. if (values) {
  1983. var value = values();
  1984. if (value !== DONE) {
  1985. return value;
  1986. }
  1987. values = null;
  1988. }
  1989. if (from === to) {
  1990. return DONE;
  1991. }
  1992. var idx = reverse ? --to : from++;
  1993. values = iterateNodeOrLeaf(
  1994. array && array[idx], level - SHIFT, offset + (idx << level)
  1995. );
  1996. } while (true);
  1997. };
  1998. }
  1999. }
  2000. function makeList(origin, capacity, level, root, tail, ownerID, hash) {
  2001. var list = Object.create(ListPrototype);
  2002. list.size = capacity - origin;
  2003. list._origin = origin;
  2004. list._capacity = capacity;
  2005. list._level = level;
  2006. list._root = root;
  2007. list._tail = tail;
  2008. list.__ownerID = ownerID;
  2009. list.__hash = hash;
  2010. list.__altered = false;
  2011. return list;
  2012. }
  2013. var EMPTY_LIST;
  2014. function emptyList() {
  2015. return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
  2016. }
  2017. function updateList(list, index, value) {
  2018. index = wrapIndex(list, index);
  2019. if (index !== index) {
  2020. return list;
  2021. }
  2022. if (index >= list.size || index < 0) {
  2023. return list.withMutations(function(list ) {
  2024. index < 0 ?
  2025. setListBounds(list, index).set(0, value) :
  2026. setListBounds(list, 0, index + 1).set(index, value)
  2027. });
  2028. }
  2029. index += list._origin;
  2030. var newTail = list._tail;
  2031. var newRoot = list._root;
  2032. var didAlter = MakeRef(DID_ALTER);
  2033. if (index >= getTailOffset(list._capacity)) {
  2034. newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
  2035. } else {
  2036. newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter);
  2037. }
  2038. if (!didAlter.value) {
  2039. return list;
  2040. }
  2041. if (list.__ownerID) {
  2042. list._root = newRoot;
  2043. list._tail = newTail;
  2044. list.__hash = undefined;
  2045. list.__altered = true;
  2046. return list;
  2047. }
  2048. return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
  2049. }
  2050. function updateVNode(node, ownerID, level, index, value, didAlter) {
  2051. var idx = (index >>> level) & MASK;
  2052. var nodeHas = node && idx < node.array.length;
  2053. if (!nodeHas && value === undefined) {
  2054. return node;
  2055. }
  2056. var newNode;
  2057. if (level > 0) {
  2058. var lowerNode = node && node.array[idx];
  2059. var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter);
  2060. if (newLowerNode === lowerNode) {
  2061. return node;
  2062. }
  2063. newNode = editableVNode(node, ownerID);
  2064. newNode.array[idx] = newLowerNode;
  2065. return newNode;
  2066. }
  2067. if (nodeHas && node.array[idx] === value) {
  2068. return node;
  2069. }
  2070. SetRef(didAlter);
  2071. newNode = editableVNode(node, ownerID);
  2072. if (value === undefined && idx === newNode.array.length - 1) {
  2073. newNode.array.pop();
  2074. } else {
  2075. newNode.array[idx] = value;
  2076. }
  2077. return newNode;
  2078. }
  2079. function editableVNode(node, ownerID) {
  2080. if (ownerID && node && ownerID === node.ownerID) {
  2081. return node;
  2082. }
  2083. return new VNode(node ? node.array.slice() : [], ownerID);
  2084. }
  2085. function listNodeFor(list, rawIndex) {
  2086. if (rawIndex >= getTailOffset(list._capacity)) {
  2087. return list._tail;
  2088. }
  2089. if (rawIndex < 1 << (list._level + SHIFT)) {
  2090. var node = list._root;
  2091. var level = list._level;
  2092. while (node && level > 0) {
  2093. node = node.array[(rawIndex >>> level) & MASK];
  2094. level -= SHIFT;
  2095. }
  2096. return node;
  2097. }
  2098. }
  2099. function setListBounds(list, begin, end) {
  2100. // Sanitize begin & end using this shorthand for ToInt32(argument)
  2101. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  2102. if (begin !== undefined) {
  2103. begin = begin | 0;
  2104. }
  2105. if (end !== undefined) {
  2106. end = end | 0;
  2107. }
  2108. var owner = list.__ownerID || new OwnerID();
  2109. var oldOrigin = list._origin;
  2110. var oldCapacity = list._capacity;
  2111. var newOrigin = oldOrigin + begin;
  2112. var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end;
  2113. if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
  2114. return list;
  2115. }
  2116. // If it's going to end after it starts, it's empty.
  2117. if (newOrigin >= newCapacity) {
  2118. return list.clear();
  2119. }
  2120. var newLevel = list._level;
  2121. var newRoot = list._root;
  2122. // New origin might need creating a higher root.
  2123. var offsetShift = 0;
  2124. while (newOrigin + offsetShift < 0) {
  2125. newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner);
  2126. newLevel += SHIFT;
  2127. offsetShift += 1 << newLevel;
  2128. }
  2129. if (offsetShift) {
  2130. newOrigin += offsetShift;
  2131. oldOrigin += offsetShift;
  2132. newCapacity += offsetShift;
  2133. oldCapacity += offsetShift;
  2134. }
  2135. var oldTailOffset = getTailOffset(oldCapacity);
  2136. var newTailOffset = getTailOffset(newCapacity);
  2137. // New size might need creating a higher root.
  2138. while (newTailOffset >= 1 << (newLevel + SHIFT)) {
  2139. newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner);
  2140. newLevel += SHIFT;
  2141. }
  2142. // Locate or create the new tail.
  2143. var oldTail = list._tail;
  2144. var newTail = newTailOffset < oldTailOffset ?
  2145. listNodeFor(list, newCapacity - 1) :
  2146. newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail;
  2147. // Merge Tail into tree.
  2148. if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) {
  2149. newRoot = editableVNode(newRoot, owner);
  2150. var node = newRoot;
  2151. for (var level = newLevel; level > SHIFT; level -= SHIFT) {
  2152. var idx = (oldTailOffset >>> level) & MASK;
  2153. node = node.array[idx] = editableVNode(node.array[idx], owner);
  2154. }
  2155. node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
  2156. }
  2157. // If the size has been reduced, there's a chance the tail needs to be trimmed.
  2158. if (newCapacity < oldCapacity) {
  2159. newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
  2160. }
  2161. // If the new origin is within the tail, then we do not need a root.
  2162. if (newOrigin >= newTailOffset) {
  2163. newOrigin -= newTailOffset;
  2164. newCapacity -= newTailOffset;
  2165. newLevel = SHIFT;
  2166. newRoot = null;
  2167. newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
  2168. // Otherwise, if the root has been trimmed, garbage collect.
  2169. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
  2170. offsetShift = 0;
  2171. // Identify the new top root node of the subtree of the old root.
  2172. while (newRoot) {
  2173. var beginIndex = (newOrigin >>> newLevel) & MASK;
  2174. if (beginIndex !== (newTailOffset >>> newLevel) & MASK) {
  2175. break;
  2176. }
  2177. if (beginIndex) {
  2178. offsetShift += (1 << newLevel) * beginIndex;
  2179. }
  2180. newLevel -= SHIFT;
  2181. newRoot = newRoot.array[beginIndex];
  2182. }
  2183. // Trim the new sides of the new root.
  2184. if (newRoot && newOrigin > oldOrigin) {
  2185. newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
  2186. }
  2187. if (newRoot && newTailOffset < oldTailOffset) {
  2188. newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift);
  2189. }
  2190. if (offsetShift) {
  2191. newOrigin -= offsetShift;
  2192. newCapacity -= offsetShift;
  2193. }
  2194. }
  2195. if (list.__ownerID) {
  2196. list.size = newCapacity - newOrigin;
  2197. list._origin = newOrigin;
  2198. list._capacity = newCapacity;
  2199. list._level = newLevel;
  2200. list._root = newRoot;
  2201. list._tail = newTail;
  2202. list.__hash = undefined;
  2203. list.__altered = true;
  2204. return list;
  2205. }
  2206. return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
  2207. }
  2208. function mergeIntoListWith(list, merger, iterables) {
  2209. var iters = [];
  2210. var maxSize = 0;
  2211. for (var ii = 0; ii < iterables.length; ii++) {
  2212. var value = iterables[ii];
  2213. var iter = IndexedIterable(value);
  2214. if (iter.size > maxSize) {
  2215. maxSize = iter.size;
  2216. }
  2217. if (!isIterable(value)) {
  2218. iter = iter.map(function(v ) {return fromJS(v)});
  2219. }
  2220. iters.push(iter);
  2221. }
  2222. if (maxSize > list.size) {
  2223. list = list.setSize(maxSize);
  2224. }
  2225. return mergeIntoCollectionWith(list, merger, iters);
  2226. }
  2227. function getTailOffset(size) {
  2228. return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT);
  2229. }
  2230. createClass(OrderedMap, Map);
  2231. // @pragma Construction
  2232. function OrderedMap(value) {
  2233. return value === null || value === undefined ? emptyOrderedMap() :
  2234. isOrderedMap(value) ? value :
  2235. emptyOrderedMap().withMutations(function(map ) {
  2236. var iter = KeyedIterable(value);
  2237. assertNotInfinite(iter.size);
  2238. iter.forEach(function(v, k) {return map.set(k, v)});
  2239. });
  2240. }
  2241. OrderedMap.of = function(/*...values*/) {
  2242. return this(arguments);
  2243. };
  2244. OrderedMap.prototype.toString = function() {
  2245. return this.__toString('OrderedMap {', '}');
  2246. };
  2247. // @pragma Access
  2248. OrderedMap.prototype.get = function(k, notSetValue) {
  2249. var index = this._map.get(k);
  2250. return index !== undefined ? this._list.get(index)[1] : notSetValue;
  2251. };
  2252. // @pragma Modification
  2253. OrderedMap.prototype.clear = function() {
  2254. if (this.size === 0) {
  2255. return this;
  2256. }
  2257. if (this.__ownerID) {
  2258. this.size = 0;
  2259. this._map.clear();
  2260. this._list.clear();
  2261. return this;
  2262. }
  2263. return emptyOrderedMap();
  2264. };
  2265. OrderedMap.prototype.set = function(k, v) {
  2266. return updateOrderedMap(this, k, v);
  2267. };
  2268. OrderedMap.prototype.remove = function(k) {
  2269. return updateOrderedMap(this, k, NOT_SET);
  2270. };
  2271. OrderedMap.prototype.wasAltered = function() {
  2272. return this._map.wasAltered() || this._list.wasAltered();
  2273. };
  2274. OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2275. return this._list.__iterate(
  2276. function(entry ) {return entry && fn(entry[1], entry[0], this$0)},
  2277. reverse
  2278. );
  2279. };
  2280. OrderedMap.prototype.__iterator = function(type, reverse) {
  2281. return this._list.fromEntrySeq().__iterator(type, reverse);
  2282. };
  2283. OrderedMap.prototype.__ensureOwner = function(ownerID) {
  2284. if (ownerID === this.__ownerID) {
  2285. return this;
  2286. }
  2287. var newMap = this._map.__ensureOwner(ownerID);
  2288. var newList = this._list.__ensureOwner(ownerID);
  2289. if (!ownerID) {
  2290. this.__ownerID = ownerID;
  2291. this._map = newMap;
  2292. this._list = newList;
  2293. return this;
  2294. }
  2295. return makeOrderedMap(newMap, newList, ownerID, this.__hash);
  2296. };
  2297. function isOrderedMap(maybeOrderedMap) {
  2298. return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
  2299. }
  2300. OrderedMap.isOrderedMap = isOrderedMap;
  2301. OrderedMap.prototype[IS_ORDERED_SENTINEL] = true;
  2302. OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
  2303. function makeOrderedMap(map, list, ownerID, hash) {
  2304. var omap = Object.create(OrderedMap.prototype);
  2305. omap.size = map ? map.size : 0;
  2306. omap._map = map;
  2307. omap._list = list;
  2308. omap.__ownerID = ownerID;
  2309. omap.__hash = hash;
  2310. return omap;
  2311. }
  2312. var EMPTY_ORDERED_MAP;
  2313. function emptyOrderedMap() {
  2314. return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()));
  2315. }
  2316. function updateOrderedMap(omap, k, v) {
  2317. var map = omap._map;
  2318. var list = omap._list;
  2319. var i = map.get(k);
  2320. var has = i !== undefined;
  2321. var newMap;
  2322. var newList;
  2323. if (v === NOT_SET) { // removed
  2324. if (!has) {
  2325. return omap;
  2326. }
  2327. if (list.size >= SIZE && list.size >= map.size * 2) {
  2328. newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx});
  2329. newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap();
  2330. if (omap.__ownerID) {
  2331. newMap.__ownerID = newList.__ownerID = omap.__ownerID;
  2332. }
  2333. } else {
  2334. newMap = map.remove(k);
  2335. newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
  2336. }
  2337. } else {
  2338. if (has) {
  2339. if (v === list.get(i)[1]) {
  2340. return omap;
  2341. }
  2342. newMap = map;
  2343. newList = list.set(i, [k, v]);
  2344. } else {
  2345. newMap = map.set(k, list.size);
  2346. newList = list.set(list.size, [k, v]);
  2347. }
  2348. }
  2349. if (omap.__ownerID) {
  2350. omap.size = newMap.size;
  2351. omap._map = newMap;
  2352. omap._list = newList;
  2353. omap.__hash = undefined;
  2354. return omap;
  2355. }
  2356. return makeOrderedMap(newMap, newList);
  2357. }
  2358. createClass(ToKeyedSequence, KeyedSeq);
  2359. function ToKeyedSequence(indexed, useKeys) {
  2360. this._iter = indexed;
  2361. this._useKeys = useKeys;
  2362. this.size = indexed.size;
  2363. }
  2364. ToKeyedSequence.prototype.get = function(key, notSetValue) {
  2365. return this._iter.get(key, notSetValue);
  2366. };
  2367. ToKeyedSequence.prototype.has = function(key) {
  2368. return this._iter.has(key);
  2369. };
  2370. ToKeyedSequence.prototype.valueSeq = function() {
  2371. return this._iter.valueSeq();
  2372. };
  2373. ToKeyedSequence.prototype.reverse = function() {var this$0 = this;
  2374. var reversedSequence = reverseFactory(this, true);
  2375. if (!this._useKeys) {
  2376. reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()};
  2377. }
  2378. return reversedSequence;
  2379. };
  2380. ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this;
  2381. var mappedSequence = mapFactory(this, mapper, context);
  2382. if (!this._useKeys) {
  2383. mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)};
  2384. }
  2385. return mappedSequence;
  2386. };
  2387. ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2388. var ii;
  2389. return this._iter.__iterate(
  2390. this._useKeys ?
  2391. function(v, k) {return fn(v, k, this$0)} :
  2392. ((ii = reverse ? resolveSize(this) : 0),
  2393. function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}),
  2394. reverse
  2395. );
  2396. };
  2397. ToKeyedSequence.prototype.__iterator = function(type, reverse) {
  2398. if (this._useKeys) {
  2399. return this._iter.__iterator(type, reverse);
  2400. }
  2401. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  2402. var ii = reverse ? resolveSize(this) : 0;
  2403. return new Iterator(function() {
  2404. var step = iterator.next();
  2405. return step.done ? step :
  2406. iteratorValue(type, reverse ? --ii : ii++, step.value, step);
  2407. });
  2408. };
  2409. ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true;
  2410. createClass(ToIndexedSequence, IndexedSeq);
  2411. function ToIndexedSequence(iter) {
  2412. this._iter = iter;
  2413. this.size = iter.size;
  2414. }
  2415. ToIndexedSequence.prototype.includes = function(value) {
  2416. return this._iter.includes(value);
  2417. };
  2418. ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2419. var iterations = 0;
  2420. return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse);
  2421. };
  2422. ToIndexedSequence.prototype.__iterator = function(type, reverse) {
  2423. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  2424. var iterations = 0;
  2425. return new Iterator(function() {
  2426. var step = iterator.next();
  2427. return step.done ? step :
  2428. iteratorValue(type, iterations++, step.value, step)
  2429. });
  2430. };
  2431. createClass(ToSetSequence, SetSeq);
  2432. function ToSetSequence(iter) {
  2433. this._iter = iter;
  2434. this.size = iter.size;
  2435. }
  2436. ToSetSequence.prototype.has = function(key) {
  2437. return this._iter.includes(key);
  2438. };
  2439. ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2440. return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse);
  2441. };
  2442. ToSetSequence.prototype.__iterator = function(type, reverse) {
  2443. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  2444. return new Iterator(function() {
  2445. var step = iterator.next();
  2446. return step.done ? step :
  2447. iteratorValue(type, step.value, step.value, step);
  2448. });
  2449. };
  2450. createClass(FromEntriesSequence, KeyedSeq);
  2451. function FromEntriesSequence(entries) {
  2452. this._iter = entries;
  2453. this.size = entries.size;
  2454. }
  2455. FromEntriesSequence.prototype.entrySeq = function() {
  2456. return this._iter.toSeq();
  2457. };
  2458. FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2459. return this._iter.__iterate(function(entry ) {
  2460. // Check if entry exists first so array access doesn't throw for holes
  2461. // in the parent iteration.
  2462. if (entry) {
  2463. validateEntry(entry);
  2464. var indexedIterable = isIterable(entry);
  2465. return fn(
  2466. indexedIterable ? entry.get(1) : entry[1],
  2467. indexedIterable ? entry.get(0) : entry[0],
  2468. this$0
  2469. );
  2470. }
  2471. }, reverse);
  2472. };
  2473. FromEntriesSequence.prototype.__iterator = function(type, reverse) {
  2474. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  2475. return new Iterator(function() {
  2476. while (true) {
  2477. var step = iterator.next();
  2478. if (step.done) {
  2479. return step;
  2480. }
  2481. var entry = step.value;
  2482. // Check if entry exists first so array access doesn't throw for holes
  2483. // in the parent iteration.
  2484. if (entry) {
  2485. validateEntry(entry);
  2486. var indexedIterable = isIterable(entry);
  2487. return iteratorValue(
  2488. type,
  2489. indexedIterable ? entry.get(0) : entry[0],
  2490. indexedIterable ? entry.get(1) : entry[1],
  2491. step
  2492. );
  2493. }
  2494. }
  2495. });
  2496. };
  2497. ToIndexedSequence.prototype.cacheResult =
  2498. ToKeyedSequence.prototype.cacheResult =
  2499. ToSetSequence.prototype.cacheResult =
  2500. FromEntriesSequence.prototype.cacheResult =
  2501. cacheResultThrough;
  2502. function flipFactory(iterable) {
  2503. var flipSequence = makeSequence(iterable);
  2504. flipSequence._iter = iterable;
  2505. flipSequence.size = iterable.size;
  2506. flipSequence.flip = function() {return iterable};
  2507. flipSequence.reverse = function () {
  2508. var reversedSequence = iterable.reverse.apply(this); // super.reverse()
  2509. reversedSequence.flip = function() {return iterable.reverse()};
  2510. return reversedSequence;
  2511. };
  2512. flipSequence.has = function(key ) {return iterable.includes(key)};
  2513. flipSequence.includes = function(key ) {return iterable.has(key)};
  2514. flipSequence.cacheResult = cacheResultThrough;
  2515. flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  2516. return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse);
  2517. }
  2518. flipSequence.__iteratorUncached = function(type, reverse) {
  2519. if (type === ITERATE_ENTRIES) {
  2520. var iterator = iterable.__iterator(type, reverse);
  2521. return new Iterator(function() {
  2522. var step = iterator.next();
  2523. if (!step.done) {
  2524. var k = step.value[0];
  2525. step.value[0] = step.value[1];
  2526. step.value[1] = k;
  2527. }
  2528. return step;
  2529. });
  2530. }
  2531. return iterable.__iterator(
  2532. type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
  2533. reverse
  2534. );
  2535. }
  2536. return flipSequence;
  2537. }
  2538. function mapFactory(iterable, mapper, context) {
  2539. var mappedSequence = makeSequence(iterable);
  2540. mappedSequence.size = iterable.size;
  2541. mappedSequence.has = function(key ) {return iterable.has(key)};
  2542. mappedSequence.get = function(key, notSetValue) {
  2543. var v = iterable.get(key, NOT_SET);
  2544. return v === NOT_SET ?
  2545. notSetValue :
  2546. mapper.call(context, v, key, iterable);
  2547. };
  2548. mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  2549. return iterable.__iterate(
  2550. function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false},
  2551. reverse
  2552. );
  2553. }
  2554. mappedSequence.__iteratorUncached = function (type, reverse) {
  2555. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  2556. return new Iterator(function() {
  2557. var step = iterator.next();
  2558. if (step.done) {
  2559. return step;
  2560. }
  2561. var entry = step.value;
  2562. var key = entry[0];
  2563. return iteratorValue(
  2564. type,
  2565. key,
  2566. mapper.call(context, entry[1], key, iterable),
  2567. step
  2568. );
  2569. });
  2570. }
  2571. return mappedSequence;
  2572. }
  2573. function reverseFactory(iterable, useKeys) {
  2574. var reversedSequence = makeSequence(iterable);
  2575. reversedSequence._iter = iterable;
  2576. reversedSequence.size = iterable.size;
  2577. reversedSequence.reverse = function() {return iterable};
  2578. if (iterable.flip) {
  2579. reversedSequence.flip = function () {
  2580. var flipSequence = flipFactory(iterable);
  2581. flipSequence.reverse = function() {return iterable.flip()};
  2582. return flipSequence;
  2583. };
  2584. }
  2585. reversedSequence.get = function(key, notSetValue)
  2586. {return iterable.get(useKeys ? key : -1 - key, notSetValue)};
  2587. reversedSequence.has = function(key )
  2588. {return iterable.has(useKeys ? key : -1 - key)};
  2589. reversedSequence.includes = function(value ) {return iterable.includes(value)};
  2590. reversedSequence.cacheResult = cacheResultThrough;
  2591. reversedSequence.__iterate = function (fn, reverse) {var this$0 = this;
  2592. return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse);
  2593. };
  2594. reversedSequence.__iterator =
  2595. function(type, reverse) {return iterable.__iterator(type, !reverse)};
  2596. return reversedSequence;
  2597. }
  2598. function filterFactory(iterable, predicate, context, useKeys) {
  2599. var filterSequence = makeSequence(iterable);
  2600. if (useKeys) {
  2601. filterSequence.has = function(key ) {
  2602. var v = iterable.get(key, NOT_SET);
  2603. return v !== NOT_SET && !!predicate.call(context, v, key, iterable);
  2604. };
  2605. filterSequence.get = function(key, notSetValue) {
  2606. var v = iterable.get(key, NOT_SET);
  2607. return v !== NOT_SET && predicate.call(context, v, key, iterable) ?
  2608. v : notSetValue;
  2609. };
  2610. }
  2611. filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  2612. var iterations = 0;
  2613. iterable.__iterate(function(v, k, c) {
  2614. if (predicate.call(context, v, k, c)) {
  2615. iterations++;
  2616. return fn(v, useKeys ? k : iterations - 1, this$0);
  2617. }
  2618. }, reverse);
  2619. return iterations;
  2620. };
  2621. filterSequence.__iteratorUncached = function (type, reverse) {
  2622. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  2623. var iterations = 0;
  2624. return new Iterator(function() {
  2625. while (true) {
  2626. var step = iterator.next();
  2627. if (step.done) {
  2628. return step;
  2629. }
  2630. var entry = step.value;
  2631. var key = entry[0];
  2632. var value = entry[1];
  2633. if (predicate.call(context, value, key, iterable)) {
  2634. return iteratorValue(type, useKeys ? key : iterations++, value, step);
  2635. }
  2636. }
  2637. });
  2638. }
  2639. return filterSequence;
  2640. }
  2641. function countByFactory(iterable, grouper, context) {
  2642. var groups = Map().asMutable();
  2643. iterable.__iterate(function(v, k) {
  2644. groups.update(
  2645. grouper.call(context, v, k, iterable),
  2646. 0,
  2647. function(a ) {return a + 1}
  2648. );
  2649. });
  2650. return groups.asImmutable();
  2651. }
  2652. function groupByFactory(iterable, grouper, context) {
  2653. var isKeyedIter = isKeyed(iterable);
  2654. var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable();
  2655. iterable.__iterate(function(v, k) {
  2656. groups.update(
  2657. grouper.call(context, v, k, iterable),
  2658. function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)}
  2659. );
  2660. });
  2661. var coerce = iterableClass(iterable);
  2662. return groups.map(function(arr ) {return reify(iterable, coerce(arr))});
  2663. }
  2664. function sliceFactory(iterable, begin, end, useKeys) {
  2665. var originalSize = iterable.size;
  2666. // Sanitize begin & end using this shorthand for ToInt32(argument)
  2667. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  2668. if (begin !== undefined) {
  2669. begin = begin | 0;
  2670. }
  2671. if (end !== undefined) {
  2672. if (end === Infinity) {
  2673. end = originalSize;
  2674. } else {
  2675. end = end | 0;
  2676. }
  2677. }
  2678. if (wholeSlice(begin, end, originalSize)) {
  2679. return iterable;
  2680. }
  2681. var resolvedBegin = resolveBegin(begin, originalSize);
  2682. var resolvedEnd = resolveEnd(end, originalSize);
  2683. // begin or end will be NaN if they were provided as negative numbers and
  2684. // this iterable's size is unknown. In that case, cache first so there is
  2685. // a known size and these do not resolve to NaN.
  2686. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
  2687. return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys);
  2688. }
  2689. // Note: resolvedEnd is undefined when the original sequence's length is
  2690. // unknown and this slice did not supply an end and should contain all
  2691. // elements after resolvedBegin.
  2692. // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
  2693. var resolvedSize = resolvedEnd - resolvedBegin;
  2694. var sliceSize;
  2695. if (resolvedSize === resolvedSize) {
  2696. sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
  2697. }
  2698. var sliceSeq = makeSequence(iterable);
  2699. // If iterable.size is undefined, the size of the realized sliceSeq is
  2700. // unknown at this point unless the number of items to slice is 0
  2701. sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined;
  2702. if (!useKeys && isSeq(iterable) && sliceSize >= 0) {
  2703. sliceSeq.get = function (index, notSetValue) {
  2704. index = wrapIndex(this, index);
  2705. return index >= 0 && index < sliceSize ?
  2706. iterable.get(index + resolvedBegin, notSetValue) :
  2707. notSetValue;
  2708. }
  2709. }
  2710. sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this;
  2711. if (sliceSize === 0) {
  2712. return 0;
  2713. }
  2714. if (reverse) {
  2715. return this.cacheResult().__iterate(fn, reverse);
  2716. }
  2717. var skipped = 0;
  2718. var isSkipping = true;
  2719. var iterations = 0;
  2720. iterable.__iterate(function(v, k) {
  2721. if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
  2722. iterations++;
  2723. return fn(v, useKeys ? k : iterations - 1, this$0) !== false &&
  2724. iterations !== sliceSize;
  2725. }
  2726. });
  2727. return iterations;
  2728. };
  2729. sliceSeq.__iteratorUncached = function(type, reverse) {
  2730. if (sliceSize !== 0 && reverse) {
  2731. return this.cacheResult().__iterator(type, reverse);
  2732. }
  2733. // Don't bother instantiating parent iterator if taking 0.
  2734. var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse);
  2735. var skipped = 0;
  2736. var iterations = 0;
  2737. return new Iterator(function() {
  2738. while (skipped++ < resolvedBegin) {
  2739. iterator.next();
  2740. }
  2741. if (++iterations > sliceSize) {
  2742. return iteratorDone();
  2743. }
  2744. var step = iterator.next();
  2745. if (useKeys || type === ITERATE_VALUES) {
  2746. return step;
  2747. } else if (type === ITERATE_KEYS) {
  2748. return iteratorValue(type, iterations - 1, undefined, step);
  2749. } else {
  2750. return iteratorValue(type, iterations - 1, step.value[1], step);
  2751. }
  2752. });
  2753. }
  2754. return sliceSeq;
  2755. }
  2756. function takeWhileFactory(iterable, predicate, context) {
  2757. var takeSequence = makeSequence(iterable);
  2758. takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
  2759. if (reverse) {
  2760. return this.cacheResult().__iterate(fn, reverse);
  2761. }
  2762. var iterations = 0;
  2763. iterable.__iterate(function(v, k, c)
  2764. {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)}
  2765. );
  2766. return iterations;
  2767. };
  2768. takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
  2769. if (reverse) {
  2770. return this.cacheResult().__iterator(type, reverse);
  2771. }
  2772. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  2773. var iterating = true;
  2774. return new Iterator(function() {
  2775. if (!iterating) {
  2776. return iteratorDone();
  2777. }
  2778. var step = iterator.next();
  2779. if (step.done) {
  2780. return step;
  2781. }
  2782. var entry = step.value;
  2783. var k = entry[0];
  2784. var v = entry[1];
  2785. if (!predicate.call(context, v, k, this$0)) {
  2786. iterating = false;
  2787. return iteratorDone();
  2788. }
  2789. return type === ITERATE_ENTRIES ? step :
  2790. iteratorValue(type, k, v, step);
  2791. });
  2792. };
  2793. return takeSequence;
  2794. }
  2795. function skipWhileFactory(iterable, predicate, context, useKeys) {
  2796. var skipSequence = makeSequence(iterable);
  2797. skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  2798. if (reverse) {
  2799. return this.cacheResult().__iterate(fn, reverse);
  2800. }
  2801. var isSkipping = true;
  2802. var iterations = 0;
  2803. iterable.__iterate(function(v, k, c) {
  2804. if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
  2805. iterations++;
  2806. return fn(v, useKeys ? k : iterations - 1, this$0);
  2807. }
  2808. });
  2809. return iterations;
  2810. };
  2811. skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
  2812. if (reverse) {
  2813. return this.cacheResult().__iterator(type, reverse);
  2814. }
  2815. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  2816. var skipping = true;
  2817. var iterations = 0;
  2818. return new Iterator(function() {
  2819. var step, k, v;
  2820. do {
  2821. step = iterator.next();
  2822. if (step.done) {
  2823. if (useKeys || type === ITERATE_VALUES) {
  2824. return step;
  2825. } else if (type === ITERATE_KEYS) {
  2826. return iteratorValue(type, iterations++, undefined, step);
  2827. } else {
  2828. return iteratorValue(type, iterations++, step.value[1], step);
  2829. }
  2830. }
  2831. var entry = step.value;
  2832. k = entry[0];
  2833. v = entry[1];
  2834. skipping && (skipping = predicate.call(context, v, k, this$0));
  2835. } while (skipping);
  2836. return type === ITERATE_ENTRIES ? step :
  2837. iteratorValue(type, k, v, step);
  2838. });
  2839. };
  2840. return skipSequence;
  2841. }
  2842. function concatFactory(iterable, values) {
  2843. var isKeyedIterable = isKeyed(iterable);
  2844. var iters = [iterable].concat(values).map(function(v ) {
  2845. if (!isIterable(v)) {
  2846. v = isKeyedIterable ?
  2847. keyedSeqFromValue(v) :
  2848. indexedSeqFromValue(Array.isArray(v) ? v : [v]);
  2849. } else if (isKeyedIterable) {
  2850. v = KeyedIterable(v);
  2851. }
  2852. return v;
  2853. }).filter(function(v ) {return v.size !== 0});
  2854. if (iters.length === 0) {
  2855. return iterable;
  2856. }
  2857. if (iters.length === 1) {
  2858. var singleton = iters[0];
  2859. if (singleton === iterable ||
  2860. isKeyedIterable && isKeyed(singleton) ||
  2861. isIndexed(iterable) && isIndexed(singleton)) {
  2862. return singleton;
  2863. }
  2864. }
  2865. var concatSeq = new ArraySeq(iters);
  2866. if (isKeyedIterable) {
  2867. concatSeq = concatSeq.toKeyedSeq();
  2868. } else if (!isIndexed(iterable)) {
  2869. concatSeq = concatSeq.toSetSeq();
  2870. }
  2871. concatSeq = concatSeq.flatten(true);
  2872. concatSeq.size = iters.reduce(
  2873. function(sum, seq) {
  2874. if (sum !== undefined) {
  2875. var size = seq.size;
  2876. if (size !== undefined) {
  2877. return sum + size;
  2878. }
  2879. }
  2880. },
  2881. 0
  2882. );
  2883. return concatSeq;
  2884. }
  2885. function flattenFactory(iterable, depth, useKeys) {
  2886. var flatSequence = makeSequence(iterable);
  2887. flatSequence.__iterateUncached = function(fn, reverse) {
  2888. var iterations = 0;
  2889. var stopped = false;
  2890. function flatDeep(iter, currentDepth) {var this$0 = this;
  2891. iter.__iterate(function(v, k) {
  2892. if ((!depth || currentDepth < depth) && isIterable(v)) {
  2893. flatDeep(v, currentDepth + 1);
  2894. } else if (fn(v, useKeys ? k : iterations++, this$0) === false) {
  2895. stopped = true;
  2896. }
  2897. return !stopped;
  2898. }, reverse);
  2899. }
  2900. flatDeep(iterable, 0);
  2901. return iterations;
  2902. }
  2903. flatSequence.__iteratorUncached = function(type, reverse) {
  2904. var iterator = iterable.__iterator(type, reverse);
  2905. var stack = [];
  2906. var iterations = 0;
  2907. return new Iterator(function() {
  2908. while (iterator) {
  2909. var step = iterator.next();
  2910. if (step.done !== false) {
  2911. iterator = stack.pop();
  2912. continue;
  2913. }
  2914. var v = step.value;
  2915. if (type === ITERATE_ENTRIES) {
  2916. v = v[1];
  2917. }
  2918. if ((!depth || stack.length < depth) && isIterable(v)) {
  2919. stack.push(iterator);
  2920. iterator = v.__iterator(type, reverse);
  2921. } else {
  2922. return useKeys ? step : iteratorValue(type, iterations++, v, step);
  2923. }
  2924. }
  2925. return iteratorDone();
  2926. });
  2927. }
  2928. return flatSequence;
  2929. }
  2930. function flatMapFactory(iterable, mapper, context) {
  2931. var coerce = iterableClass(iterable);
  2932. return iterable.toSeq().map(
  2933. function(v, k) {return coerce(mapper.call(context, v, k, iterable))}
  2934. ).flatten(true);
  2935. }
  2936. function interposeFactory(iterable, separator) {
  2937. var interposedSequence = makeSequence(iterable);
  2938. interposedSequence.size = iterable.size && iterable.size * 2 -1;
  2939. interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
  2940. var iterations = 0;
  2941. iterable.__iterate(function(v, k)
  2942. {return (!iterations || fn(separator, iterations++, this$0) !== false) &&
  2943. fn(v, iterations++, this$0) !== false},
  2944. reverse
  2945. );
  2946. return iterations;
  2947. };
  2948. interposedSequence.__iteratorUncached = function(type, reverse) {
  2949. var iterator = iterable.__iterator(ITERATE_VALUES, reverse);
  2950. var iterations = 0;
  2951. var step;
  2952. return new Iterator(function() {
  2953. if (!step || iterations % 2) {
  2954. step = iterator.next();
  2955. if (step.done) {
  2956. return step;
  2957. }
  2958. }
  2959. return iterations % 2 ?
  2960. iteratorValue(type, iterations++, separator) :
  2961. iteratorValue(type, iterations++, step.value, step);
  2962. });
  2963. };
  2964. return interposedSequence;
  2965. }
  2966. function sortFactory(iterable, comparator, mapper) {
  2967. if (!comparator) {
  2968. comparator = defaultComparator;
  2969. }
  2970. var isKeyedIterable = isKeyed(iterable);
  2971. var index = 0;
  2972. var entries = iterable.toSeq().map(
  2973. function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]}
  2974. ).toArray();
  2975. entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach(
  2976. isKeyedIterable ?
  2977. function(v, i) { entries[i].length = 2; } :
  2978. function(v, i) { entries[i] = v[1]; }
  2979. );
  2980. return isKeyedIterable ? KeyedSeq(entries) :
  2981. isIndexed(iterable) ? IndexedSeq(entries) :
  2982. SetSeq(entries);
  2983. }
  2984. function maxFactory(iterable, comparator, mapper) {
  2985. if (!comparator) {
  2986. comparator = defaultComparator;
  2987. }
  2988. if (mapper) {
  2989. var entry = iterable.toSeq()
  2990. .map(function(v, k) {return [v, mapper(v, k, iterable)]})
  2991. .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a});
  2992. return entry && entry[0];
  2993. } else {
  2994. return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a});
  2995. }
  2996. }
  2997. function maxCompare(comparator, a, b) {
  2998. var comp = comparator(b, a);
  2999. // b is considered the new max if the comparator declares them equal, but
  3000. // they are not equal and b is in fact a nullish value.
  3001. return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0;
  3002. }
  3003. function zipWithFactory(keyIter, zipper, iters) {
  3004. var zipSequence = makeSequence(keyIter);
  3005. zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min();
  3006. // Note: this a generic base implementation of __iterate in terms of
  3007. // __iterator which may be more generically useful in the future.
  3008. zipSequence.__iterate = function(fn, reverse) {
  3009. /* generic:
  3010. var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
  3011. var step;
  3012. var iterations = 0;
  3013. while (!(step = iterator.next()).done) {
  3014. iterations++;
  3015. if (fn(step.value[1], step.value[0], this) === false) {
  3016. break;
  3017. }
  3018. }
  3019. return iterations;
  3020. */
  3021. // indexed:
  3022. var iterator = this.__iterator(ITERATE_VALUES, reverse);
  3023. var step;
  3024. var iterations = 0;
  3025. while (!(step = iterator.next()).done) {
  3026. if (fn(step.value, iterations++, this) === false) {
  3027. break;
  3028. }
  3029. }
  3030. return iterations;
  3031. };
  3032. zipSequence.__iteratorUncached = function(type, reverse) {
  3033. var iterators = iters.map(function(i )
  3034. {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))}
  3035. );
  3036. var iterations = 0;
  3037. var isDone = false;
  3038. return new Iterator(function() {
  3039. var steps;
  3040. if (!isDone) {
  3041. steps = iterators.map(function(i ) {return i.next()});
  3042. isDone = steps.some(function(s ) {return s.done});
  3043. }
  3044. if (isDone) {
  3045. return iteratorDone();
  3046. }
  3047. return iteratorValue(
  3048. type,
  3049. iterations++,
  3050. zipper.apply(null, steps.map(function(s ) {return s.value}))
  3051. );
  3052. });
  3053. };
  3054. return zipSequence
  3055. }
  3056. // #pragma Helper Functions
  3057. function reify(iter, seq) {
  3058. return isSeq(iter) ? seq : iter.constructor(seq);
  3059. }
  3060. function validateEntry(entry) {
  3061. if (entry !== Object(entry)) {
  3062. throw new TypeError('Expected [K, V] tuple: ' + entry);
  3063. }
  3064. }
  3065. function resolveSize(iter) {
  3066. assertNotInfinite(iter.size);
  3067. return ensureSize(iter);
  3068. }
  3069. function iterableClass(iterable) {
  3070. return isKeyed(iterable) ? KeyedIterable :
  3071. isIndexed(iterable) ? IndexedIterable :
  3072. SetIterable;
  3073. }
  3074. function makeSequence(iterable) {
  3075. return Object.create(
  3076. (
  3077. isKeyed(iterable) ? KeyedSeq :
  3078. isIndexed(iterable) ? IndexedSeq :
  3079. SetSeq
  3080. ).prototype
  3081. );
  3082. }
  3083. function cacheResultThrough() {
  3084. if (this._iter.cacheResult) {
  3085. this._iter.cacheResult();
  3086. this.size = this._iter.size;
  3087. return this;
  3088. } else {
  3089. return Seq.prototype.cacheResult.call(this);
  3090. }
  3091. }
  3092. function defaultComparator(a, b) {
  3093. return a > b ? 1 : a < b ? -1 : 0;
  3094. }
  3095. function forceIterator(keyPath) {
  3096. var iter = getIterator(keyPath);
  3097. if (!iter) {
  3098. // Array might not be iterable in this environment, so we need a fallback
  3099. // to our wrapped type.
  3100. if (!isArrayLike(keyPath)) {
  3101. throw new TypeError('Expected iterable or array-like: ' + keyPath);
  3102. }
  3103. iter = getIterator(Iterable(keyPath));
  3104. }
  3105. return iter;
  3106. }
  3107. createClass(Record, KeyedCollection);
  3108. function Record(defaultValues, name) {
  3109. var hasInitialized;
  3110. var RecordType = function Record(values) {
  3111. if (values instanceof RecordType) {
  3112. return values;
  3113. }
  3114. if (!(this instanceof RecordType)) {
  3115. return new RecordType(values);
  3116. }
  3117. if (!hasInitialized) {
  3118. hasInitialized = true;
  3119. var keys = Object.keys(defaultValues);
  3120. setProps(RecordTypePrototype, keys);
  3121. RecordTypePrototype.size = keys.length;
  3122. RecordTypePrototype._name = name;
  3123. RecordTypePrototype._keys = keys;
  3124. RecordTypePrototype._defaultValues = defaultValues;
  3125. }
  3126. this._map = Map(values);
  3127. };
  3128. var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype);
  3129. RecordTypePrototype.constructor = RecordType;
  3130. return RecordType;
  3131. }
  3132. Record.prototype.toString = function() {
  3133. return this.__toString(recordName(this) + ' {', '}');
  3134. };
  3135. // @pragma Access
  3136. Record.prototype.has = function(k) {
  3137. return this._defaultValues.hasOwnProperty(k);
  3138. };
  3139. Record.prototype.get = function(k, notSetValue) {
  3140. if (!this.has(k)) {
  3141. return notSetValue;
  3142. }
  3143. var defaultVal = this._defaultValues[k];
  3144. return this._map ? this._map.get(k, defaultVal) : defaultVal;
  3145. };
  3146. // @pragma Modification
  3147. Record.prototype.clear = function() {
  3148. if (this.__ownerID) {
  3149. this._map && this._map.clear();
  3150. return this;
  3151. }
  3152. var RecordType = this.constructor;
  3153. return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap()));
  3154. };
  3155. Record.prototype.set = function(k, v) {
  3156. if (!this.has(k)) {
  3157. throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this));
  3158. }
  3159. if (this._map && !this._map.has(k)) {
  3160. var defaultVal = this._defaultValues[k];
  3161. if (v === defaultVal) {
  3162. return this;
  3163. }
  3164. }
  3165. var newMap = this._map && this._map.set(k, v);
  3166. if (this.__ownerID || newMap === this._map) {
  3167. return this;
  3168. }
  3169. return makeRecord(this, newMap);
  3170. };
  3171. Record.prototype.remove = function(k) {
  3172. if (!this.has(k)) {
  3173. return this;
  3174. }
  3175. var newMap = this._map && this._map.remove(k);
  3176. if (this.__ownerID || newMap === this._map) {
  3177. return this;
  3178. }
  3179. return makeRecord(this, newMap);
  3180. };
  3181. Record.prototype.wasAltered = function() {
  3182. return this._map.wasAltered();
  3183. };
  3184. Record.prototype.__iterator = function(type, reverse) {var this$0 = this;
  3185. return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse);
  3186. };
  3187. Record.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  3188. return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse);
  3189. };
  3190. Record.prototype.__ensureOwner = function(ownerID) {
  3191. if (ownerID === this.__ownerID) {
  3192. return this;
  3193. }
  3194. var newMap = this._map && this._map.__ensureOwner(ownerID);
  3195. if (!ownerID) {
  3196. this.__ownerID = ownerID;
  3197. this._map = newMap;
  3198. return this;
  3199. }
  3200. return makeRecord(this, newMap, ownerID);
  3201. };
  3202. var RecordPrototype = Record.prototype;
  3203. RecordPrototype[DELETE] = RecordPrototype.remove;
  3204. RecordPrototype.deleteIn =
  3205. RecordPrototype.removeIn = MapPrototype.removeIn;
  3206. RecordPrototype.merge = MapPrototype.merge;
  3207. RecordPrototype.mergeWith = MapPrototype.mergeWith;
  3208. RecordPrototype.mergeIn = MapPrototype.mergeIn;
  3209. RecordPrototype.mergeDeep = MapPrototype.mergeDeep;
  3210. RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith;
  3211. RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  3212. RecordPrototype.setIn = MapPrototype.setIn;
  3213. RecordPrototype.update = MapPrototype.update;
  3214. RecordPrototype.updateIn = MapPrototype.updateIn;
  3215. RecordPrototype.withMutations = MapPrototype.withMutations;
  3216. RecordPrototype.asMutable = MapPrototype.asMutable;
  3217. RecordPrototype.asImmutable = MapPrototype.asImmutable;
  3218. function makeRecord(likeRecord, map, ownerID) {
  3219. var record = Object.create(Object.getPrototypeOf(likeRecord));
  3220. record._map = map;
  3221. record.__ownerID = ownerID;
  3222. return record;
  3223. }
  3224. function recordName(record) {
  3225. return record._name || record.constructor.name || 'Record';
  3226. }
  3227. function setProps(prototype, names) {
  3228. try {
  3229. names.forEach(setProp.bind(undefined, prototype));
  3230. } catch (error) {
  3231. // Object.defineProperty failed. Probably IE8.
  3232. }
  3233. }
  3234. function setProp(prototype, name) {
  3235. Object.defineProperty(prototype, name, {
  3236. get: function() {
  3237. return this.get(name);
  3238. },
  3239. set: function(value) {
  3240. invariant(this.__ownerID, 'Cannot set on an immutable record.');
  3241. this.set(name, value);
  3242. }
  3243. });
  3244. }
  3245. createClass(Set, SetCollection);
  3246. // @pragma Construction
  3247. function Set(value) {
  3248. return value === null || value === undefined ? emptySet() :
  3249. isSet(value) && !isOrdered(value) ? value :
  3250. emptySet().withMutations(function(set ) {
  3251. var iter = SetIterable(value);
  3252. assertNotInfinite(iter.size);
  3253. iter.forEach(function(v ) {return set.add(v)});
  3254. });
  3255. }
  3256. Set.of = function(/*...values*/) {
  3257. return this(arguments);
  3258. };
  3259. Set.fromKeys = function(value) {
  3260. return this(KeyedIterable(value).keySeq());
  3261. };
  3262. Set.prototype.toString = function() {
  3263. return this.__toString('Set {', '}');
  3264. };
  3265. // @pragma Access
  3266. Set.prototype.has = function(value) {
  3267. return this._map.has(value);
  3268. };
  3269. // @pragma Modification
  3270. Set.prototype.add = function(value) {
  3271. return updateSet(this, this._map.set(value, true));
  3272. };
  3273. Set.prototype.remove = function(value) {
  3274. return updateSet(this, this._map.remove(value));
  3275. };
  3276. Set.prototype.clear = function() {
  3277. return updateSet(this, this._map.clear());
  3278. };
  3279. // @pragma Composition
  3280. Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0);
  3281. iters = iters.filter(function(x ) {return x.size !== 0});
  3282. if (iters.length === 0) {
  3283. return this;
  3284. }
  3285. if (this.size === 0 && !this.__ownerID && iters.length === 1) {
  3286. return this.constructor(iters[0]);
  3287. }
  3288. return this.withMutations(function(set ) {
  3289. for (var ii = 0; ii < iters.length; ii++) {
  3290. SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)});
  3291. }
  3292. });
  3293. };
  3294. Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0);
  3295. if (iters.length === 0) {
  3296. return this;
  3297. }
  3298. iters = iters.map(function(iter ) {return SetIterable(iter)});
  3299. var originalSet = this;
  3300. return this.withMutations(function(set ) {
  3301. originalSet.forEach(function(value ) {
  3302. if (!iters.every(function(iter ) {return iter.includes(value)})) {
  3303. set.remove(value);
  3304. }
  3305. });
  3306. });
  3307. };
  3308. Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0);
  3309. if (iters.length === 0) {
  3310. return this;
  3311. }
  3312. iters = iters.map(function(iter ) {return SetIterable(iter)});
  3313. var originalSet = this;
  3314. return this.withMutations(function(set ) {
  3315. originalSet.forEach(function(value ) {
  3316. if (iters.some(function(iter ) {return iter.includes(value)})) {
  3317. set.remove(value);
  3318. }
  3319. });
  3320. });
  3321. };
  3322. Set.prototype.merge = function() {
  3323. return this.union.apply(this, arguments);
  3324. };
  3325. Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  3326. return this.union.apply(this, iters);
  3327. };
  3328. Set.prototype.sort = function(comparator) {
  3329. // Late binding
  3330. return OrderedSet(sortFactory(this, comparator));
  3331. };
  3332. Set.prototype.sortBy = function(mapper, comparator) {
  3333. // Late binding
  3334. return OrderedSet(sortFactory(this, comparator, mapper));
  3335. };
  3336. Set.prototype.wasAltered = function() {
  3337. return this._map.wasAltered();
  3338. };
  3339. Set.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  3340. return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse);
  3341. };
  3342. Set.prototype.__iterator = function(type, reverse) {
  3343. return this._map.map(function(_, k) {return k}).__iterator(type, reverse);
  3344. };
  3345. Set.prototype.__ensureOwner = function(ownerID) {
  3346. if (ownerID === this.__ownerID) {
  3347. return this;
  3348. }
  3349. var newMap = this._map.__ensureOwner(ownerID);
  3350. if (!ownerID) {
  3351. this.__ownerID = ownerID;
  3352. this._map = newMap;
  3353. return this;
  3354. }
  3355. return this.__make(newMap, ownerID);
  3356. };
  3357. function isSet(maybeSet) {
  3358. return !!(maybeSet && maybeSet[IS_SET_SENTINEL]);
  3359. }
  3360. Set.isSet = isSet;
  3361. var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@';
  3362. var SetPrototype = Set.prototype;
  3363. SetPrototype[IS_SET_SENTINEL] = true;
  3364. SetPrototype[DELETE] = SetPrototype.remove;
  3365. SetPrototype.mergeDeep = SetPrototype.merge;
  3366. SetPrototype.mergeDeepWith = SetPrototype.mergeWith;
  3367. SetPrototype.withMutations = MapPrototype.withMutations;
  3368. SetPrototype.asMutable = MapPrototype.asMutable;
  3369. SetPrototype.asImmutable = MapPrototype.asImmutable;
  3370. SetPrototype.__empty = emptySet;
  3371. SetPrototype.__make = makeSet;
  3372. function updateSet(set, newMap) {
  3373. if (set.__ownerID) {
  3374. set.size = newMap.size;
  3375. set._map = newMap;
  3376. return set;
  3377. }
  3378. return newMap === set._map ? set :
  3379. newMap.size === 0 ? set.__empty() :
  3380. set.__make(newMap);
  3381. }
  3382. function makeSet(map, ownerID) {
  3383. var set = Object.create(SetPrototype);
  3384. set.size = map ? map.size : 0;
  3385. set._map = map;
  3386. set.__ownerID = ownerID;
  3387. return set;
  3388. }
  3389. var EMPTY_SET;
  3390. function emptySet() {
  3391. return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
  3392. }
  3393. createClass(OrderedSet, Set);
  3394. // @pragma Construction
  3395. function OrderedSet(value) {
  3396. return value === null || value === undefined ? emptyOrderedSet() :
  3397. isOrderedSet(value) ? value :
  3398. emptyOrderedSet().withMutations(function(set ) {
  3399. var iter = SetIterable(value);
  3400. assertNotInfinite(iter.size);
  3401. iter.forEach(function(v ) {return set.add(v)});
  3402. });
  3403. }
  3404. OrderedSet.of = function(/*...values*/) {
  3405. return this(arguments);
  3406. };
  3407. OrderedSet.fromKeys = function(value) {
  3408. return this(KeyedIterable(value).keySeq());
  3409. };
  3410. OrderedSet.prototype.toString = function() {
  3411. return this.__toString('OrderedSet {', '}');
  3412. };
  3413. function isOrderedSet(maybeOrderedSet) {
  3414. return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
  3415. }
  3416. OrderedSet.isOrderedSet = isOrderedSet;
  3417. var OrderedSetPrototype = OrderedSet.prototype;
  3418. OrderedSetPrototype[IS_ORDERED_SENTINEL] = true;
  3419. OrderedSetPrototype.__empty = emptyOrderedSet;
  3420. OrderedSetPrototype.__make = makeOrderedSet;
  3421. function makeOrderedSet(map, ownerID) {
  3422. var set = Object.create(OrderedSetPrototype);
  3423. set.size = map ? map.size : 0;
  3424. set._map = map;
  3425. set.__ownerID = ownerID;
  3426. return set;
  3427. }
  3428. var EMPTY_ORDERED_SET;
  3429. function emptyOrderedSet() {
  3430. return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()));
  3431. }
  3432. createClass(Stack, IndexedCollection);
  3433. // @pragma Construction
  3434. function Stack(value) {
  3435. return value === null || value === undefined ? emptyStack() :
  3436. isStack(value) ? value :
  3437. emptyStack().unshiftAll(value);
  3438. }
  3439. Stack.of = function(/*...values*/) {
  3440. return this(arguments);
  3441. };
  3442. Stack.prototype.toString = function() {
  3443. return this.__toString('Stack [', ']');
  3444. };
  3445. // @pragma Access
  3446. Stack.prototype.get = function(index, notSetValue) {
  3447. var head = this._head;
  3448. index = wrapIndex(this, index);
  3449. while (head && index--) {
  3450. head = head.next;
  3451. }
  3452. return head ? head.value : notSetValue;
  3453. };
  3454. Stack.prototype.peek = function() {
  3455. return this._head && this._head.value;
  3456. };
  3457. // @pragma Modification
  3458. Stack.prototype.push = function(/*...values*/) {
  3459. if (arguments.length === 0) {
  3460. return this;
  3461. }
  3462. var newSize = this.size + arguments.length;
  3463. var head = this._head;
  3464. for (var ii = arguments.length - 1; ii >= 0; ii--) {
  3465. head = {
  3466. value: arguments[ii],
  3467. next: head
  3468. };
  3469. }
  3470. if (this.__ownerID) {
  3471. this.size = newSize;
  3472. this._head = head;
  3473. this.__hash = undefined;
  3474. this.__altered = true;
  3475. return this;
  3476. }
  3477. return makeStack(newSize, head);
  3478. };
  3479. Stack.prototype.pushAll = function(iter) {
  3480. iter = IndexedIterable(iter);
  3481. if (iter.size === 0) {
  3482. return this;
  3483. }
  3484. assertNotInfinite(iter.size);
  3485. var newSize = this.size;
  3486. var head = this._head;
  3487. iter.reverse().forEach(function(value ) {
  3488. newSize++;
  3489. head = {
  3490. value: value,
  3491. next: head
  3492. };
  3493. });
  3494. if (this.__ownerID) {
  3495. this.size = newSize;
  3496. this._head = head;
  3497. this.__hash = undefined;
  3498. this.__altered = true;
  3499. return this;
  3500. }
  3501. return makeStack(newSize, head);
  3502. };
  3503. Stack.prototype.pop = function() {
  3504. return this.slice(1);
  3505. };
  3506. Stack.prototype.unshift = function(/*...values*/) {
  3507. return this.push.apply(this, arguments);
  3508. };
  3509. Stack.prototype.unshiftAll = function(iter) {
  3510. return this.pushAll(iter);
  3511. };
  3512. Stack.prototype.shift = function() {
  3513. return this.pop.apply(this, arguments);
  3514. };
  3515. Stack.prototype.clear = function() {
  3516. if (this.size === 0) {
  3517. return this;
  3518. }
  3519. if (this.__ownerID) {
  3520. this.size = 0;
  3521. this._head = undefined;
  3522. this.__hash = undefined;
  3523. this.__altered = true;
  3524. return this;
  3525. }
  3526. return emptyStack();
  3527. };
  3528. Stack.prototype.slice = function(begin, end) {
  3529. if (wholeSlice(begin, end, this.size)) {
  3530. return this;
  3531. }
  3532. var resolvedBegin = resolveBegin(begin, this.size);
  3533. var resolvedEnd = resolveEnd(end, this.size);
  3534. if (resolvedEnd !== this.size) {
  3535. // super.slice(begin, end);
  3536. return IndexedCollection.prototype.slice.call(this, begin, end);
  3537. }
  3538. var newSize = this.size - resolvedBegin;
  3539. var head = this._head;
  3540. while (resolvedBegin--) {
  3541. head = head.next;
  3542. }
  3543. if (this.__ownerID) {
  3544. this.size = newSize;
  3545. this._head = head;
  3546. this.__hash = undefined;
  3547. this.__altered = true;
  3548. return this;
  3549. }
  3550. return makeStack(newSize, head);
  3551. };
  3552. // @pragma Mutability
  3553. Stack.prototype.__ensureOwner = function(ownerID) {
  3554. if (ownerID === this.__ownerID) {
  3555. return this;
  3556. }
  3557. if (!ownerID) {
  3558. this.__ownerID = ownerID;
  3559. this.__altered = false;
  3560. return this;
  3561. }
  3562. return makeStack(this.size, this._head, ownerID, this.__hash);
  3563. };
  3564. // @pragma Iteration
  3565. Stack.prototype.__iterate = function(fn, reverse) {
  3566. if (reverse) {
  3567. return this.reverse().__iterate(fn);
  3568. }
  3569. var iterations = 0;
  3570. var node = this._head;
  3571. while (node) {
  3572. if (fn(node.value, iterations++, this) === false) {
  3573. break;
  3574. }
  3575. node = node.next;
  3576. }
  3577. return iterations;
  3578. };
  3579. Stack.prototype.__iterator = function(type, reverse) {
  3580. if (reverse) {
  3581. return this.reverse().__iterator(type);
  3582. }
  3583. var iterations = 0;
  3584. var node = this._head;
  3585. return new Iterator(function() {
  3586. if (node) {
  3587. var value = node.value;
  3588. node = node.next;
  3589. return iteratorValue(type, iterations++, value);
  3590. }
  3591. return iteratorDone();
  3592. });
  3593. };
  3594. function isStack(maybeStack) {
  3595. return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]);
  3596. }
  3597. Stack.isStack = isStack;
  3598. var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@';
  3599. var StackPrototype = Stack.prototype;
  3600. StackPrototype[IS_STACK_SENTINEL] = true;
  3601. StackPrototype.withMutations = MapPrototype.withMutations;
  3602. StackPrototype.asMutable = MapPrototype.asMutable;
  3603. StackPrototype.asImmutable = MapPrototype.asImmutable;
  3604. StackPrototype.wasAltered = MapPrototype.wasAltered;
  3605. function makeStack(size, head, ownerID, hash) {
  3606. var map = Object.create(StackPrototype);
  3607. map.size = size;
  3608. map._head = head;
  3609. map.__ownerID = ownerID;
  3610. map.__hash = hash;
  3611. map.__altered = false;
  3612. return map;
  3613. }
  3614. var EMPTY_STACK;
  3615. function emptyStack() {
  3616. return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
  3617. }
  3618. /**
  3619. * Contributes additional methods to a constructor
  3620. */
  3621. function mixin(ctor, methods) {
  3622. var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; };
  3623. Object.keys(methods).forEach(keyCopier);
  3624. Object.getOwnPropertySymbols &&
  3625. Object.getOwnPropertySymbols(methods).forEach(keyCopier);
  3626. return ctor;
  3627. }
  3628. Iterable.Iterator = Iterator;
  3629. mixin(Iterable, {
  3630. // ### Conversion to other types
  3631. toArray: function() {
  3632. assertNotInfinite(this.size);
  3633. var array = new Array(this.size || 0);
  3634. this.valueSeq().__iterate(function(v, i) { array[i] = v; });
  3635. return array;
  3636. },
  3637. toIndexedSeq: function() {
  3638. return new ToIndexedSequence(this);
  3639. },
  3640. toJS: function() {
  3641. return this.toSeq().map(
  3642. function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value}
  3643. ).__toJS();
  3644. },
  3645. toJSON: function() {
  3646. return this.toSeq().map(
  3647. function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value}
  3648. ).__toJS();
  3649. },
  3650. toKeyedSeq: function() {
  3651. return new ToKeyedSequence(this, true);
  3652. },
  3653. toMap: function() {
  3654. // Use Late Binding here to solve the circular dependency.
  3655. return Map(this.toKeyedSeq());
  3656. },
  3657. toObject: function() {
  3658. assertNotInfinite(this.size);
  3659. var object = {};
  3660. this.__iterate(function(v, k) { object[k] = v; });
  3661. return object;
  3662. },
  3663. toOrderedMap: function() {
  3664. // Use Late Binding here to solve the circular dependency.
  3665. return OrderedMap(this.toKeyedSeq());
  3666. },
  3667. toOrderedSet: function() {
  3668. // Use Late Binding here to solve the circular dependency.
  3669. return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
  3670. },
  3671. toSet: function() {
  3672. // Use Late Binding here to solve the circular dependency.
  3673. return Set(isKeyed(this) ? this.valueSeq() : this);
  3674. },
  3675. toSetSeq: function() {
  3676. return new ToSetSequence(this);
  3677. },
  3678. toSeq: function() {
  3679. return isIndexed(this) ? this.toIndexedSeq() :
  3680. isKeyed(this) ? this.toKeyedSeq() :
  3681. this.toSetSeq();
  3682. },
  3683. toStack: function() {
  3684. // Use Late Binding here to solve the circular dependency.
  3685. return Stack(isKeyed(this) ? this.valueSeq() : this);
  3686. },
  3687. toList: function() {
  3688. // Use Late Binding here to solve the circular dependency.
  3689. return List(isKeyed(this) ? this.valueSeq() : this);
  3690. },
  3691. // ### Common JavaScript methods and properties
  3692. toString: function() {
  3693. return '[Iterable]';
  3694. },
  3695. __toString: function(head, tail) {
  3696. if (this.size === 0) {
  3697. return head + tail;
  3698. }
  3699. return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail;
  3700. },
  3701. // ### ES6 Collection methods (ES6 Array and Map)
  3702. concat: function() {var values = SLICE$0.call(arguments, 0);
  3703. return reify(this, concatFactory(this, values));
  3704. },
  3705. includes: function(searchValue) {
  3706. return this.some(function(value ) {return is(value, searchValue)});
  3707. },
  3708. entries: function() {
  3709. return this.__iterator(ITERATE_ENTRIES);
  3710. },
  3711. every: function(predicate, context) {
  3712. assertNotInfinite(this.size);
  3713. var returnValue = true;
  3714. this.__iterate(function(v, k, c) {
  3715. if (!predicate.call(context, v, k, c)) {
  3716. returnValue = false;
  3717. return false;
  3718. }
  3719. });
  3720. return returnValue;
  3721. },
  3722. filter: function(predicate, context) {
  3723. return reify(this, filterFactory(this, predicate, context, true));
  3724. },
  3725. find: function(predicate, context, notSetValue) {
  3726. var entry = this.findEntry(predicate, context);
  3727. return entry ? entry[1] : notSetValue;
  3728. },
  3729. forEach: function(sideEffect, context) {
  3730. assertNotInfinite(this.size);
  3731. return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
  3732. },
  3733. join: function(separator) {
  3734. assertNotInfinite(this.size);
  3735. separator = separator !== undefined ? '' + separator : ',';
  3736. var joined = '';
  3737. var isFirst = true;
  3738. this.__iterate(function(v ) {
  3739. isFirst ? (isFirst = false) : (joined += separator);
  3740. joined += v !== null && v !== undefined ? v.toString() : '';
  3741. });
  3742. return joined;
  3743. },
  3744. keys: function() {
  3745. return this.__iterator(ITERATE_KEYS);
  3746. },
  3747. map: function(mapper, context) {
  3748. return reify(this, mapFactory(this, mapper, context));
  3749. },
  3750. reduce: function(reducer, initialReduction, context) {
  3751. assertNotInfinite(this.size);
  3752. var reduction;
  3753. var useFirst;
  3754. if (arguments.length < 2) {
  3755. useFirst = true;
  3756. } else {
  3757. reduction = initialReduction;
  3758. }
  3759. this.__iterate(function(v, k, c) {
  3760. if (useFirst) {
  3761. useFirst = false;
  3762. reduction = v;
  3763. } else {
  3764. reduction = reducer.call(context, reduction, v, k, c);
  3765. }
  3766. });
  3767. return reduction;
  3768. },
  3769. reduceRight: function(reducer, initialReduction, context) {
  3770. var reversed = this.toKeyedSeq().reverse();
  3771. return reversed.reduce.apply(reversed, arguments);
  3772. },
  3773. reverse: function() {
  3774. return reify(this, reverseFactory(this, true));
  3775. },
  3776. slice: function(begin, end) {
  3777. return reify(this, sliceFactory(this, begin, end, true));
  3778. },
  3779. some: function(predicate, context) {
  3780. return !this.every(not(predicate), context);
  3781. },
  3782. sort: function(comparator) {
  3783. return reify(this, sortFactory(this, comparator));
  3784. },
  3785. values: function() {
  3786. return this.__iterator(ITERATE_VALUES);
  3787. },
  3788. // ### More sequential methods
  3789. butLast: function() {
  3790. return this.slice(0, -1);
  3791. },
  3792. isEmpty: function() {
  3793. return this.size !== undefined ? this.size === 0 : !this.some(function() {return true});
  3794. },
  3795. count: function(predicate, context) {
  3796. return ensureSize(
  3797. predicate ? this.toSeq().filter(predicate, context) : this
  3798. );
  3799. },
  3800. countBy: function(grouper, context) {
  3801. return countByFactory(this, grouper, context);
  3802. },
  3803. equals: function(other) {
  3804. return deepEqual(this, other);
  3805. },
  3806. entrySeq: function() {
  3807. var iterable = this;
  3808. if (iterable._cache) {
  3809. // We cache as an entries array, so we can just return the cache!
  3810. return new ArraySeq(iterable._cache);
  3811. }
  3812. var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq();
  3813. entriesSequence.fromEntrySeq = function() {return iterable.toSeq()};
  3814. return entriesSequence;
  3815. },
  3816. filterNot: function(predicate, context) {
  3817. return this.filter(not(predicate), context);
  3818. },
  3819. findEntry: function(predicate, context, notSetValue) {
  3820. var found = notSetValue;
  3821. this.__iterate(function(v, k, c) {
  3822. if (predicate.call(context, v, k, c)) {
  3823. found = [k, v];
  3824. return false;
  3825. }
  3826. });
  3827. return found;
  3828. },
  3829. findKey: function(predicate, context) {
  3830. var entry = this.findEntry(predicate, context);
  3831. return entry && entry[0];
  3832. },
  3833. findLast: function(predicate, context, notSetValue) {
  3834. return this.toKeyedSeq().reverse().find(predicate, context, notSetValue);
  3835. },
  3836. findLastEntry: function(predicate, context, notSetValue) {
  3837. return this.toKeyedSeq().reverse().findEntry(predicate, context, notSetValue);
  3838. },
  3839. findLastKey: function(predicate, context) {
  3840. return this.toKeyedSeq().reverse().findKey(predicate, context);
  3841. },
  3842. first: function() {
  3843. return this.find(returnTrue);
  3844. },
  3845. flatMap: function(mapper, context) {
  3846. return reify(this, flatMapFactory(this, mapper, context));
  3847. },
  3848. flatten: function(depth) {
  3849. return reify(this, flattenFactory(this, depth, true));
  3850. },
  3851. fromEntrySeq: function() {
  3852. return new FromEntriesSequence(this);
  3853. },
  3854. get: function(searchKey, notSetValue) {
  3855. return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue);
  3856. },
  3857. getIn: function(searchKeyPath, notSetValue) {
  3858. var nested = this;
  3859. // Note: in an ES6 environment, we would prefer:
  3860. // for (var key of searchKeyPath) {
  3861. var iter = forceIterator(searchKeyPath);
  3862. var step;
  3863. while (!(step = iter.next()).done) {
  3864. var key = step.value;
  3865. nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET;
  3866. if (nested === NOT_SET) {
  3867. return notSetValue;
  3868. }
  3869. }
  3870. return nested;
  3871. },
  3872. groupBy: function(grouper, context) {
  3873. return groupByFactory(this, grouper, context);
  3874. },
  3875. has: function(searchKey) {
  3876. return this.get(searchKey, NOT_SET) !== NOT_SET;
  3877. },
  3878. hasIn: function(searchKeyPath) {
  3879. return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET;
  3880. },
  3881. isSubset: function(iter) {
  3882. iter = typeof iter.includes === 'function' ? iter : Iterable(iter);
  3883. return this.every(function(value ) {return iter.includes(value)});
  3884. },
  3885. isSuperset: function(iter) {
  3886. iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter);
  3887. return iter.isSubset(this);
  3888. },
  3889. keyOf: function(searchValue) {
  3890. return this.findKey(function(value ) {return is(value, searchValue)});
  3891. },
  3892. keySeq: function() {
  3893. return this.toSeq().map(keyMapper).toIndexedSeq();
  3894. },
  3895. last: function() {
  3896. return this.toSeq().reverse().first();
  3897. },
  3898. lastKeyOf: function(searchValue) {
  3899. return this.toKeyedSeq().reverse().keyOf(searchValue);
  3900. },
  3901. max: function(comparator) {
  3902. return maxFactory(this, comparator);
  3903. },
  3904. maxBy: function(mapper, comparator) {
  3905. return maxFactory(this, comparator, mapper);
  3906. },
  3907. min: function(comparator) {
  3908. return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator);
  3909. },
  3910. minBy: function(mapper, comparator) {
  3911. return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper);
  3912. },
  3913. rest: function() {
  3914. return this.slice(1);
  3915. },
  3916. skip: function(amount) {
  3917. return this.slice(Math.max(0, amount));
  3918. },
  3919. skipLast: function(amount) {
  3920. return reify(this, this.toSeq().reverse().skip(amount).reverse());
  3921. },
  3922. skipWhile: function(predicate, context) {
  3923. return reify(this, skipWhileFactory(this, predicate, context, true));
  3924. },
  3925. skipUntil: function(predicate, context) {
  3926. return this.skipWhile(not(predicate), context);
  3927. },
  3928. sortBy: function(mapper, comparator) {
  3929. return reify(this, sortFactory(this, comparator, mapper));
  3930. },
  3931. take: function(amount) {
  3932. return this.slice(0, Math.max(0, amount));
  3933. },
  3934. takeLast: function(amount) {
  3935. return reify(this, this.toSeq().reverse().take(amount).reverse());
  3936. },
  3937. takeWhile: function(predicate, context) {
  3938. return reify(this, takeWhileFactory(this, predicate, context));
  3939. },
  3940. takeUntil: function(predicate, context) {
  3941. return this.takeWhile(not(predicate), context);
  3942. },
  3943. valueSeq: function() {
  3944. return this.toIndexedSeq();
  3945. },
  3946. // ### Hashable Object
  3947. hashCode: function() {
  3948. return this.__hash || (this.__hash = hashIterable(this));
  3949. }
  3950. // ### Internal
  3951. // abstract __iterate(fn, reverse)
  3952. // abstract __iterator(type, reverse)
  3953. });
  3954. // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  3955. // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  3956. // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  3957. // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';
  3958. var IterablePrototype = Iterable.prototype;
  3959. IterablePrototype[IS_ITERABLE_SENTINEL] = true;
  3960. IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values;
  3961. IterablePrototype.__toJS = IterablePrototype.toArray;
  3962. IterablePrototype.__toStringMapper = quoteString;
  3963. IterablePrototype.inspect =
  3964. IterablePrototype.toSource = function() { return this.toString(); };
  3965. IterablePrototype.chain = IterablePrototype.flatMap;
  3966. IterablePrototype.contains = IterablePrototype.includes;
  3967. mixin(KeyedIterable, {
  3968. // ### More sequential methods
  3969. flip: function() {
  3970. return reify(this, flipFactory(this));
  3971. },
  3972. mapEntries: function(mapper, context) {var this$0 = this;
  3973. var iterations = 0;
  3974. return reify(this,
  3975. this.toSeq().map(
  3976. function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)}
  3977. ).fromEntrySeq()
  3978. );
  3979. },
  3980. mapKeys: function(mapper, context) {var this$0 = this;
  3981. return reify(this,
  3982. this.toSeq().flip().map(
  3983. function(k, v) {return mapper.call(context, k, v, this$0)}
  3984. ).flip()
  3985. );
  3986. }
  3987. });
  3988. var KeyedIterablePrototype = KeyedIterable.prototype;
  3989. KeyedIterablePrototype[IS_KEYED_SENTINEL] = true;
  3990. KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries;
  3991. KeyedIterablePrototype.__toJS = IterablePrototype.toObject;
  3992. KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)};
  3993. mixin(IndexedIterable, {
  3994. // ### Conversion to other types
  3995. toKeyedSeq: function() {
  3996. return new ToKeyedSequence(this, false);
  3997. },
  3998. // ### ES6 Collection methods (ES6 Array and Map)
  3999. filter: function(predicate, context) {
  4000. return reify(this, filterFactory(this, predicate, context, false));
  4001. },
  4002. findIndex: function(predicate, context) {
  4003. var entry = this.findEntry(predicate, context);
  4004. return entry ? entry[0] : -1;
  4005. },
  4006. indexOf: function(searchValue) {
  4007. var key = this.keyOf(searchValue);
  4008. return key === undefined ? -1 : key;
  4009. },
  4010. lastIndexOf: function(searchValue) {
  4011. var key = this.lastKeyOf(searchValue);
  4012. return key === undefined ? -1 : key;
  4013. },
  4014. reverse: function() {
  4015. return reify(this, reverseFactory(this, false));
  4016. },
  4017. slice: function(begin, end) {
  4018. return reify(this, sliceFactory(this, begin, end, false));
  4019. },
  4020. splice: function(index, removeNum /*, ...values*/) {
  4021. var numArgs = arguments.length;
  4022. removeNum = Math.max(removeNum | 0, 0);
  4023. if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
  4024. return this;
  4025. }
  4026. // If index is negative, it should resolve relative to the size of the
  4027. // collection. However size may be expensive to compute if not cached, so
  4028. // only call count() if the number is in fact negative.
  4029. index = resolveBegin(index, index < 0 ? this.count() : this.size);
  4030. var spliced = this.slice(0, index);
  4031. return reify(
  4032. this,
  4033. numArgs === 1 ?
  4034. spliced :
  4035. spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
  4036. );
  4037. },
  4038. // ### More collection methods
  4039. findLastIndex: function(predicate, context) {
  4040. var entry = this.findLastEntry(predicate, context);
  4041. return entry ? entry[0] : -1;
  4042. },
  4043. first: function() {
  4044. return this.get(0);
  4045. },
  4046. flatten: function(depth) {
  4047. return reify(this, flattenFactory(this, depth, false));
  4048. },
  4049. get: function(index, notSetValue) {
  4050. index = wrapIndex(this, index);
  4051. return (index < 0 || (this.size === Infinity ||
  4052. (this.size !== undefined && index > this.size))) ?
  4053. notSetValue :
  4054. this.find(function(_, key) {return key === index}, undefined, notSetValue);
  4055. },
  4056. has: function(index) {
  4057. index = wrapIndex(this, index);
  4058. return index >= 0 && (this.size !== undefined ?
  4059. this.size === Infinity || index < this.size :
  4060. this.indexOf(index) !== -1
  4061. );
  4062. },
  4063. interpose: function(separator) {
  4064. return reify(this, interposeFactory(this, separator));
  4065. },
  4066. interleave: function(/*...iterables*/) {
  4067. var iterables = [this].concat(arrCopy(arguments));
  4068. var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables);
  4069. var interleaved = zipped.flatten(true);
  4070. if (zipped.size) {
  4071. interleaved.size = zipped.size * iterables.length;
  4072. }
  4073. return reify(this, interleaved);
  4074. },
  4075. keySeq: function() {
  4076. return Range(0, this.size);
  4077. },
  4078. last: function() {
  4079. return this.get(-1);
  4080. },
  4081. skipWhile: function(predicate, context) {
  4082. return reify(this, skipWhileFactory(this, predicate, context, false));
  4083. },
  4084. zip: function(/*, ...iterables */) {
  4085. var iterables = [this].concat(arrCopy(arguments));
  4086. return reify(this, zipWithFactory(this, defaultZipper, iterables));
  4087. },
  4088. zipWith: function(zipper/*, ...iterables */) {
  4089. var iterables = arrCopy(arguments);
  4090. iterables[0] = this;
  4091. return reify(this, zipWithFactory(this, zipper, iterables));
  4092. }
  4093. });
  4094. IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true;
  4095. IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true;
  4096. mixin(SetIterable, {
  4097. // ### ES6 Collection methods (ES6 Array and Map)
  4098. get: function(value, notSetValue) {
  4099. return this.has(value) ? value : notSetValue;
  4100. },
  4101. includes: function(value) {
  4102. return this.has(value);
  4103. },
  4104. // ### More sequential methods
  4105. keySeq: function() {
  4106. return this.valueSeq();
  4107. }
  4108. });
  4109. SetIterable.prototype.has = IterablePrototype.includes;
  4110. SetIterable.prototype.contains = SetIterable.prototype.includes;
  4111. // Mixin subclasses
  4112. mixin(KeyedSeq, KeyedIterable.prototype);
  4113. mixin(IndexedSeq, IndexedIterable.prototype);
  4114. mixin(SetSeq, SetIterable.prototype);
  4115. mixin(KeyedCollection, KeyedIterable.prototype);
  4116. mixin(IndexedCollection, IndexedIterable.prototype);
  4117. mixin(SetCollection, SetIterable.prototype);
  4118. // #pragma Helper functions
  4119. function keyMapper(v, k) {
  4120. return k;
  4121. }
  4122. function entryMapper(v, k) {
  4123. return [k, v];
  4124. }
  4125. function not(predicate) {
  4126. return function() {
  4127. return !predicate.apply(this, arguments);
  4128. }
  4129. }
  4130. function neg(predicate) {
  4131. return function() {
  4132. return -predicate.apply(this, arguments);
  4133. }
  4134. }
  4135. function quoteString(value) {
  4136. return typeof value === 'string' ? JSON.stringify(value) : String(value);
  4137. }
  4138. function defaultZipper() {
  4139. return arrCopy(arguments);
  4140. }
  4141. function defaultNegComparator(a, b) {
  4142. return a < b ? 1 : a > b ? -1 : 0;
  4143. }
  4144. function hashIterable(iterable) {
  4145. if (iterable.size === Infinity) {
  4146. return 0;
  4147. }
  4148. var ordered = isOrdered(iterable);
  4149. var keyed = isKeyed(iterable);
  4150. var h = ordered ? 1 : 0;
  4151. var size = iterable.__iterate(
  4152. keyed ?
  4153. ordered ?
  4154. function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } :
  4155. function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } :
  4156. ordered ?
  4157. function(v ) { h = 31 * h + hash(v) | 0; } :
  4158. function(v ) { h = h + hash(v) | 0; }
  4159. );
  4160. return murmurHashOfSize(size, h);
  4161. }
  4162. function murmurHashOfSize(size, h) {
  4163. h = imul(h, 0xCC9E2D51);
  4164. h = imul(h << 15 | h >>> -15, 0x1B873593);
  4165. h = imul(h << 13 | h >>> -13, 5);
  4166. h = (h + 0xE6546B64 | 0) ^ size;
  4167. h = imul(h ^ h >>> 16, 0x85EBCA6B);
  4168. h = imul(h ^ h >>> 13, 0xC2B2AE35);
  4169. h = smi(h ^ h >>> 16);
  4170. return h;
  4171. }
  4172. function hashMerge(a, b) {
  4173. return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int
  4174. }
  4175. var Immutable = {
  4176. Iterable: Iterable,
  4177. Seq: Seq,
  4178. Collection: Collection,
  4179. Map: Map,
  4180. OrderedMap: OrderedMap,
  4181. List: List,
  4182. Stack: Stack,
  4183. Set: Set,
  4184. OrderedSet: OrderedSet,
  4185. Record: Record,
  4186. Range: Range,
  4187. Repeat: Repeat,
  4188. is: is,
  4189. fromJS: fromJS
  4190. };
  4191. return Immutable;
  4192. }));