framer.js 347 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141
  1. ;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. var AnimatorClasses, BezierCurveAnimator, Config, Defaults, EventEmitter, Frame, LinearAnimator, SpringDHOAnimator, SpringRK4Animator, Utils, evaluateRelativeProperty, isRelativeProperty, numberRE, relativePropertyRE, _, _runningAnimations,
  3. __slice = [].slice,
  4. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  5. __hasProp = {}.hasOwnProperty,
  6. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  7. _ = require("./Underscore")._;
  8. Utils = require("./Utils");
  9. Config = require("./Config").Config;
  10. Defaults = require("./Defaults").Defaults;
  11. EventEmitter = require("./EventEmitter").EventEmitter;
  12. Frame = require("./Frame").Frame;
  13. LinearAnimator = require("./Animators/LinearAnimator").LinearAnimator;
  14. BezierCurveAnimator = require("./Animators/BezierCurveAnimator").BezierCurveAnimator;
  15. SpringRK4Animator = require("./Animators/SpringRK4Animator").SpringRK4Animator;
  16. SpringDHOAnimator = require("./Animators/SpringDHOAnimator").SpringDHOAnimator;
  17. AnimatorClasses = {
  18. "linear": LinearAnimator,
  19. "bezier-curve": BezierCurveAnimator,
  20. "spring-rk4": SpringRK4Animator,
  21. "spring-dho": SpringDHOAnimator
  22. };
  23. AnimatorClasses["spring"] = AnimatorClasses["spring-rk4"];
  24. AnimatorClasses["cubic-bezier"] = AnimatorClasses["bezier-curve"];
  25. numberRE = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/;
  26. relativePropertyRE = new RegExp('^(?:([+-])=|)(' + numberRE.source + ')([a-z%]*)$', 'i');
  27. isRelativeProperty = function(v) {
  28. return _.isString(v) && relativePropertyRE.test(v);
  29. };
  30. evaluateRelativeProperty = function(target, k, v) {
  31. var match, number, rest, sign, unit, _ref;
  32. _ref = relativePropertyRE.exec(v), match = _ref[0], sign = _ref[1], number = _ref[2], unit = _ref[3], rest = 5 <= _ref.length ? __slice.call(_ref, 4) : [];
  33. if (sign) {
  34. return target[k] + (sign + 1) * number;
  35. } else {
  36. return +number;
  37. }
  38. };
  39. _runningAnimations = [];
  40. exports.Animation = (function(_super) {
  41. __extends(Animation, _super);
  42. Animation.runningAnimations = function() {
  43. return _runningAnimations;
  44. };
  45. function Animation(options) {
  46. if (options == null) {
  47. options = {};
  48. }
  49. this.start = __bind(this.start, this);
  50. options = Defaults.getDefaults("Animation", options);
  51. Animation.__super__.constructor.call(this, options);
  52. this.options = Utils.setDefaultProperties(options, {
  53. layer: null,
  54. properties: {},
  55. curve: "linear",
  56. curveOptions: {},
  57. time: 1,
  58. repeat: 0,
  59. delay: 0,
  60. debug: false
  61. });
  62. if (options.origin) {
  63. console.warn("Animation.origin: please use layer.originX and layer.originY");
  64. }
  65. if (options.properties instanceof Frame) {
  66. option.properties = option.properties.properties;
  67. }
  68. this.options.properties = this._filterAnimatableProperties(this.options.properties);
  69. this._parseAnimatorOptions();
  70. this._originalState = this._currentState();
  71. this._repeatCounter = this.options.repeat;
  72. }
  73. Animation.prototype._filterAnimatableProperties = function(properties) {
  74. var animatableProperties, k, v;
  75. animatableProperties = {};
  76. for (k in properties) {
  77. v = properties[k];
  78. if (_.isNumber(v) || isRelativeProperty(v)) {
  79. animatableProperties[k] = v;
  80. }
  81. }
  82. return animatableProperties;
  83. };
  84. Animation.prototype._currentState = function() {
  85. return _.pick(this.options.layer, _.keys(this.options.properties));
  86. };
  87. Animation.prototype._animatorClass = function() {
  88. var animatorClassName, parsedCurve;
  89. parsedCurve = Utils.parseFunction(this.options.curve);
  90. animatorClassName = parsedCurve.name.toLowerCase();
  91. if (AnimatorClasses.hasOwnProperty(animatorClassName)) {
  92. return AnimatorClasses[animatorClassName];
  93. }
  94. return LinearAnimator;
  95. };
  96. Animation.prototype._parseAnimatorOptions = function() {
  97. var animatorClass, i, k, parsedCurve, value, _base, _i, _j, _len, _len1, _ref, _ref1, _results;
  98. animatorClass = this._animatorClass();
  99. parsedCurve = Utils.parseFunction(this.options.curve);
  100. if (animatorClass === LinearAnimator || animatorClass === BezierCurveAnimator) {
  101. if (_.isString(this.options.curveOptions) || _.isArray(this.options.curveOptions)) {
  102. this.options.curveOptions = {
  103. values: this.options.curveOptions
  104. };
  105. }
  106. if ((_base = this.options.curveOptions).time == null) {
  107. _base.time = this.options.time;
  108. }
  109. }
  110. if (parsedCurve.args.length) {
  111. if (animatorClass === BezierCurveAnimator) {
  112. this.options.curveOptions.values = parsedCurve.args.map(function(v) {
  113. return parseFloat(v) || 0;
  114. });
  115. }
  116. if (animatorClass === SpringRK4Animator) {
  117. _ref = ["tension", "friction", "velocity"];
  118. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  119. k = _ref[i];
  120. value = parseFloat(parsedCurve.args[i]);
  121. if (value) {
  122. this.options.curveOptions[k] = value;
  123. }
  124. }
  125. }
  126. if (animatorClass === SpringDHOAnimator) {
  127. _ref1 = ["stiffness", "damping", "mass", "tolerance"];
  128. _results = [];
  129. for (i = _j = 0, _len1 = _ref1.length; _j < _len1; i = ++_j) {
  130. k = _ref1[i];
  131. value = parseFloat(parsedCurve.args[i]);
  132. if (value) {
  133. _results.push(this.options.curveOptions[k] = value);
  134. } else {
  135. _results.push(void 0);
  136. }
  137. }
  138. return _results;
  139. }
  140. }
  141. };
  142. Animation.prototype.start = function() {
  143. var AnimatorClass, k, start, stateA, stateB, target, v, _ref,
  144. _this = this;
  145. if (this.options.layer === null) {
  146. console.error("Animation: missing layer");
  147. }
  148. AnimatorClass = this._animatorClass();
  149. if (this.options.debug) {
  150. console.log("Animation.start " + AnimatorClass.name, this.options.curveOptions);
  151. }
  152. this._animator = new AnimatorClass(this.options.curveOptions);
  153. target = this.options.layer;
  154. stateA = this._currentState();
  155. stateB = {};
  156. _ref = this.options.properties;
  157. for (k in _ref) {
  158. v = _ref[k];
  159. if (isRelativeProperty(v)) {
  160. v = evaluateRelativeProperty(target, k, v);
  161. }
  162. if (stateA[k] !== v) {
  163. stateB[k] = v;
  164. }
  165. }
  166. if (_.isEqual(stateA, stateB)) {
  167. console.warn("Nothing to animate");
  168. }
  169. if (this.options.debug) {
  170. console.log("Animation.start");
  171. for (k in stateB) {
  172. v = stateB[k];
  173. console.log("\t" + k + ": " + stateA[k] + " -> " + stateB[k]);
  174. }
  175. }
  176. this._animator.on("start", function() {
  177. return _this.emit("start");
  178. });
  179. this._animator.on("stop", function() {
  180. return _this.emit("stop");
  181. });
  182. this._animator.on("end", function() {
  183. return _this.emit("end");
  184. });
  185. if (this._repeatCounter > 0) {
  186. this._animator.on("end", function() {
  187. for (k in stateA) {
  188. v = stateA[k];
  189. target[k] = v;
  190. }
  191. _this._repeatCounter--;
  192. return _this.start();
  193. });
  194. }
  195. this._animator.on("tick", function(value) {
  196. for (k in stateB) {
  197. v = stateB[k];
  198. target[k] = Utils.mapRange(value, 0, 1, stateA[k], stateB[k]);
  199. }
  200. });
  201. start = function() {
  202. _runningAnimations.push(_this);
  203. return _this._animator.start();
  204. };
  205. if (this.options.delay) {
  206. return Utils.delay(this.options.delay, start);
  207. } else {
  208. return start();
  209. }
  210. };
  211. Animation.prototype.stop = function() {
  212. var _ref;
  213. if ((_ref = this._animator) != null) {
  214. _ref.stop();
  215. }
  216. return _runningAnimations = _.without(_runningAnimations, this);
  217. };
  218. Animation.prototype.reverse = function() {
  219. var animation, options;
  220. options = _.clone(this.options);
  221. options.properties = this._originalState;
  222. animation = new Animation(options);
  223. return animation;
  224. };
  225. Animation.prototype.revert = function() {
  226. return this.reverse();
  227. };
  228. Animation.prototype.inverse = function() {
  229. return this.reverse();
  230. };
  231. Animation.prototype.invert = function() {
  232. return this.reverse();
  233. };
  234. Animation.prototype.emit = function(event) {
  235. Animation.__super__.emit.apply(this, arguments);
  236. return this.options.layer.emit(event, this);
  237. };
  238. return Animation;
  239. })(EventEmitter);
  240. },{"./Animators/BezierCurveAnimator":4,"./Animators/LinearAnimator":5,"./Animators/SpringDHOAnimator":6,"./Animators/SpringRK4Animator":7,"./Config":11,"./Defaults":13,"./EventEmitter":14,"./Frame":18,"./Underscore":28,"./Utils":29}],2:[function(require,module,exports){
  241. var AnimationLoop, AnimationLoopIndexKey, Config, EventEmitter, Utils, _;
  242. _ = require("./Underscore")._;
  243. Utils = require("./Utils");
  244. Config = require("./Config").Config;
  245. EventEmitter = require("./EventEmitter").EventEmitter;
  246. AnimationLoopIndexKey = "_animationLoopIndex";
  247. AnimationLoop = {
  248. debug: false,
  249. _animators: [],
  250. _running: false,
  251. _frameCounter: 0,
  252. _sessionTime: 0,
  253. _start: function() {
  254. if (AnimationLoop._running) {
  255. return;
  256. }
  257. if (!AnimationLoop._animators.length) {
  258. return;
  259. }
  260. AnimationLoop._running = true;
  261. AnimationLoop._time = Utils.getTime();
  262. AnimationLoop._sessionTime = 0;
  263. return window.requestAnimationFrame(AnimationLoop._tick);
  264. },
  265. _stop: function() {
  266. return AnimationLoop._running = false;
  267. },
  268. _tick: function() {
  269. var animator, delta, removeAnimators, time, _i, _j, _len, _len1, _ref;
  270. if (!AnimationLoop._animators.length) {
  271. return AnimationLoop._stop();
  272. }
  273. AnimationLoop._frameCounter++;
  274. time = Utils.getTime();
  275. delta = time - AnimationLoop._time;
  276. AnimationLoop._sessionTime += delta;
  277. removeAnimators = [];
  278. _ref = AnimationLoop._animators;
  279. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  280. animator = _ref[_i];
  281. animator.emit("tick", animator.next(delta));
  282. if (animator.finished()) {
  283. animator.emit("tick", 1);
  284. removeAnimators.push(animator);
  285. }
  286. }
  287. AnimationLoop._time = time;
  288. for (_j = 0, _len1 = removeAnimators.length; _j < _len1; _j++) {
  289. animator = removeAnimators[_j];
  290. AnimationLoop.remove(animator);
  291. animator.emit("end");
  292. }
  293. window.requestAnimationFrame(AnimationLoop._tick);
  294. },
  295. add: function(animator) {
  296. if (animator.hasOwnProperty(AnimationLoopIndexKey)) {
  297. return;
  298. }
  299. animator[AnimationLoopIndexKey] = AnimationLoop._animators.push(animator);
  300. animator.emit("start");
  301. return AnimationLoop._start();
  302. },
  303. remove: function(animator) {
  304. AnimationLoop._animators = _.without(AnimationLoop._animators, animator);
  305. return animator.emit("stop");
  306. }
  307. };
  308. exports.AnimationLoop = AnimationLoop;
  309. },{"./Config":11,"./EventEmitter":14,"./Underscore":28,"./Utils":29}],3:[function(require,module,exports){
  310. var AnimationLoop, Config, EventEmitter, Utils,
  311. __hasProp = {}.hasOwnProperty,
  312. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  313. Utils = require("./Utils");
  314. Config = require("./Config").Config;
  315. EventEmitter = require("./EventEmitter").EventEmitter;
  316. AnimationLoop = require("./AnimationLoop").AnimationLoop;
  317. exports.Animator = (function(_super) {
  318. __extends(Animator, _super);
  319. "The animator class is a very simple class that\n - Takes a set of input values at setup({input values})\n - Emits an output value for progress (0 -> 1) in value(progress)";
  320. function Animator(options) {
  321. if (options == null) {
  322. options = {};
  323. }
  324. this.setup(options);
  325. }
  326. Animator.prototype.setup = function(options) {
  327. throw Error("Not implemented");
  328. };
  329. Animator.prototype.next = function(delta) {
  330. throw Error("Not implemented");
  331. };
  332. Animator.prototype.finished = function() {
  333. throw Error("Not implemented");
  334. };
  335. Animator.prototype.start = function() {
  336. return AnimationLoop.add(this);
  337. };
  338. Animator.prototype.stop = function() {
  339. return AnimationLoop.remove(this);
  340. };
  341. return Animator;
  342. })(EventEmitter);
  343. },{"./AnimationLoop":2,"./Config":11,"./EventEmitter":14,"./Utils":29}],4:[function(require,module,exports){
  344. var Animator, BezierCurveDefaults, UnitBezier, Utils, _, _ref,
  345. __hasProp = {}.hasOwnProperty,
  346. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  347. _ = require("../Underscore")._;
  348. Utils = require("../Utils");
  349. Animator = require("../Animator").Animator;
  350. BezierCurveDefaults = {
  351. "linear": [0, 0, 1, 1],
  352. "ease": [.25, .1, .25, 1],
  353. "ease-in": [.42, 0, 1, 1],
  354. "ease-out": [0, 0, .58, 1],
  355. "ease-in-out": [.42, 0, .58, 1]
  356. };
  357. exports.BezierCurveAnimator = (function(_super) {
  358. __extends(BezierCurveAnimator, _super);
  359. function BezierCurveAnimator() {
  360. _ref = BezierCurveAnimator.__super__.constructor.apply(this, arguments);
  361. return _ref;
  362. }
  363. BezierCurveAnimator.prototype.setup = function(options) {
  364. if (_.isString(options) && BezierCurveDefaults.hasOwnProperty(options.toLowerCase())) {
  365. options = {
  366. values: BezierCurveDefaults[options.toLowerCase()]
  367. };
  368. }
  369. if (options.values && _.isString(options.values) && BezierCurveDefaults.hasOwnProperty(options.values.toLowerCase())) {
  370. options = {
  371. values: BezierCurveDefaults[options.values.toLowerCase()],
  372. time: options.time
  373. };
  374. }
  375. if (_.isArray(options) && options.length === 4) {
  376. options = {
  377. values: options
  378. };
  379. }
  380. this.options = Utils.setDefaultProperties(options, {
  381. values: BezierCurveDefaults["ease-in-out"],
  382. time: 1
  383. });
  384. return this._unitBezier = new UnitBezier(this.options.values[0], this.options.values[1], this.options.values[2], this.options.values[3], this._time = 0);
  385. };
  386. BezierCurveAnimator.prototype.next = function(delta) {
  387. this._time += delta;
  388. if (this.finished()) {
  389. return 1;
  390. }
  391. return this._unitBezier.solve(this._time / this.options.time);
  392. };
  393. BezierCurveAnimator.prototype.finished = function() {
  394. return this._time >= this.options.time;
  395. };
  396. return BezierCurveAnimator;
  397. })(Animator);
  398. UnitBezier = (function() {
  399. UnitBezier.prototype.epsilon = 1e-6;
  400. function UnitBezier(p1x, p1y, p2x, p2y) {
  401. this.cx = 3.0 * p1x;
  402. this.bx = 3.0 * (p2x - p1x) - this.cx;
  403. this.ax = 1.0 - this.cx - this.bx;
  404. this.cy = 3.0 * p1y;
  405. this.by = 3.0 * (p2y - p1y) - this.cy;
  406. this.ay = 1.0 - this.cy - this.by;
  407. }
  408. UnitBezier.prototype.sampleCurveX = function(t) {
  409. return ((this.ax * t + this.bx) * t + this.cx) * t;
  410. };
  411. UnitBezier.prototype.sampleCurveY = function(t) {
  412. return ((this.ay * t + this.by) * t + this.cy) * t;
  413. };
  414. UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
  415. return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
  416. };
  417. UnitBezier.prototype.solveCurveX = function(x) {
  418. var d2, i, t0, t1, t2, x2;
  419. t2 = x;
  420. i = 0;
  421. while (i < 8) {
  422. x2 = this.sampleCurveX(t2) - x;
  423. if (Math.abs(x2) < this.epsilon) {
  424. return t2;
  425. }
  426. d2 = this.sampleCurveDerivativeX(t2);
  427. if (Math.abs(d2) < this.epsilon) {
  428. break;
  429. }
  430. t2 = t2 - x2 / d2;
  431. i++;
  432. }
  433. t0 = 0.0;
  434. t1 = 1.0;
  435. t2 = x;
  436. if (t2 < t0) {
  437. return t0;
  438. }
  439. if (t2 > t1) {
  440. return t1;
  441. }
  442. while (t0 < t1) {
  443. x2 = this.sampleCurveX(t2);
  444. if (Math.abs(x2 - x) < this.epsilon) {
  445. return t2;
  446. }
  447. if (x > x2) {
  448. t0 = t2;
  449. } else {
  450. t1 = t2;
  451. }
  452. t2 = (t1 - t0) * .5 + t0;
  453. }
  454. return t2;
  455. };
  456. UnitBezier.prototype.solve = function(x) {
  457. return this.sampleCurveY(this.solveCurveX(x));
  458. };
  459. return UnitBezier;
  460. })();
  461. },{"../Animator":3,"../Underscore":28,"../Utils":29}],5:[function(require,module,exports){
  462. var Animator, Utils, _ref,
  463. __hasProp = {}.hasOwnProperty,
  464. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  465. Utils = require("../Utils");
  466. Animator = require("../Animator").Animator;
  467. exports.LinearAnimator = (function(_super) {
  468. __extends(LinearAnimator, _super);
  469. function LinearAnimator() {
  470. _ref = LinearAnimator.__super__.constructor.apply(this, arguments);
  471. return _ref;
  472. }
  473. LinearAnimator.prototype.setup = function(options) {
  474. this.options = Utils.setDefaultProperties(options, {
  475. time: 1
  476. });
  477. return this._time = 0;
  478. };
  479. LinearAnimator.prototype.next = function(delta) {
  480. if (this.finished()) {
  481. return 1;
  482. }
  483. this._time += delta;
  484. return this._time / this.options.time;
  485. };
  486. LinearAnimator.prototype.finished = function() {
  487. return this._time >= this.options.time;
  488. };
  489. return LinearAnimator;
  490. })(Animator);
  491. },{"../Animator":3,"../Utils":29}],6:[function(require,module,exports){
  492. var Animator, Utils, _ref,
  493. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  494. __hasProp = {}.hasOwnProperty,
  495. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  496. Utils = require("../Utils");
  497. Animator = require("../Animator").Animator;
  498. exports.SpringDHOAnimator = (function(_super) {
  499. __extends(SpringDHOAnimator, _super);
  500. function SpringDHOAnimator() {
  501. this.finished = __bind(this.finished, this);
  502. _ref = SpringDHOAnimator.__super__.constructor.apply(this, arguments);
  503. return _ref;
  504. }
  505. SpringDHOAnimator.prototype.setup = function(options) {
  506. this.options = Utils.setDefaultProperties(options, {
  507. velocity: 0,
  508. tolerance: 1 / 10000,
  509. stiffness: 50,
  510. damping: 2,
  511. mass: 0.2,
  512. time: null
  513. });
  514. console.log("SpringDHOAnimator.options", this.options, options);
  515. this._time = 0;
  516. this._value = 0;
  517. return this._velocity = this.options.velocity;
  518. };
  519. SpringDHOAnimator.prototype.next = function(delta) {
  520. var F_damper, F_spring, b, k;
  521. if (this.finished()) {
  522. return 1;
  523. }
  524. this._time += delta;
  525. k = 0 - this.options.stiffness;
  526. b = 0 - this.options.damping;
  527. F_spring = k * (this._value - 1);
  528. F_damper = b * this._velocity;
  529. this._velocity += ((F_spring + F_damper) / this.options.mass) * delta;
  530. this._value += this._velocity * delta;
  531. return this._value;
  532. };
  533. SpringDHOAnimator.prototype.finished = function() {
  534. return this._time > 0 && Math.abs(this._velocity) < this.options.tolerance;
  535. };
  536. return SpringDHOAnimator;
  537. })(Animator);
  538. },{"../Animator":3,"../Utils":29}],7:[function(require,module,exports){
  539. var Animator, Utils, springAccelerationForState, springEvaluateState, springEvaluateStateWithDerivative, springIntegrateState, _ref,
  540. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  541. __hasProp = {}.hasOwnProperty,
  542. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  543. Utils = require("../Utils");
  544. Animator = require("../Animator").Animator;
  545. exports.SpringRK4Animator = (function(_super) {
  546. __extends(SpringRK4Animator, _super);
  547. function SpringRK4Animator() {
  548. this.finished = __bind(this.finished, this);
  549. _ref = SpringRK4Animator.__super__.constructor.apply(this, arguments);
  550. return _ref;
  551. }
  552. SpringRK4Animator.prototype.setup = function(options) {
  553. this.options = Utils.setDefaultProperties(options, {
  554. tension: 500,
  555. friction: 10,
  556. velocity: 0,
  557. tolerance: 1 / 10000,
  558. time: null
  559. });
  560. this._time = 0;
  561. this._value = 0;
  562. this._velocity = this.options.velocity;
  563. return this._stopSpring = false;
  564. };
  565. SpringRK4Animator.prototype.next = function(delta) {
  566. var finalVelocity, net1DVelocity, netFloat, netValueIsLow, netVelocityIsLow, stateAfter, stateBefore;
  567. if (this.finished()) {
  568. return 1;
  569. }
  570. this._time += delta;
  571. stateBefore = {};
  572. stateAfter = {};
  573. stateBefore.x = this._value - 1;
  574. stateBefore.v = this._velocity;
  575. stateBefore.tension = this.options.tension;
  576. stateBefore.friction = this.options.friction;
  577. stateAfter = springIntegrateState(stateBefore, delta);
  578. this._value = 1 + stateAfter.x;
  579. finalVelocity = stateAfter.v;
  580. netFloat = stateAfter.x;
  581. net1DVelocity = stateAfter.v;
  582. netValueIsLow = Math.abs(netFloat) < this.options.tolerance;
  583. netVelocityIsLow = Math.abs(net1DVelocity) < this.options.tolerance;
  584. this._stopSpring = netValueIsLow && netVelocityIsLow;
  585. this._velocity = finalVelocity;
  586. return this._value;
  587. };
  588. SpringRK4Animator.prototype.finished = function() {
  589. return this._stopSpring;
  590. };
  591. return SpringRK4Animator;
  592. })(Animator);
  593. springAccelerationForState = function(state) {
  594. return -state.tension * state.x - state.friction * state.v;
  595. };
  596. springEvaluateState = function(initialState) {
  597. var output;
  598. output = {};
  599. output.dx = initialState.v;
  600. output.dv = springAccelerationForState(initialState);
  601. return output;
  602. };
  603. springEvaluateStateWithDerivative = function(initialState, dt, derivative) {
  604. var output, state;
  605. state = {};
  606. state.x = initialState.x + derivative.dx * dt;
  607. state.v = initialState.v + derivative.dv * dt;
  608. state.tension = initialState.tension;
  609. state.friction = initialState.friction;
  610. output = {};
  611. output.dx = state.v;
  612. output.dv = springAccelerationForState(state);
  613. return output;
  614. };
  615. springIntegrateState = function(state, speed) {
  616. var a, b, c, d, dvdt, dxdt;
  617. a = springEvaluateState(state);
  618. b = springEvaluateStateWithDerivative(state, speed * 0.5, a);
  619. c = springEvaluateStateWithDerivative(state, speed * 0.5, b);
  620. d = springEvaluateStateWithDerivative(state, speed, c);
  621. dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx);
  622. dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);
  623. state.x = state.x + dxdt * speed;
  624. state.v = state.v + dvdt * speed;
  625. return state;
  626. };
  627. },{"../Animator":3,"../Utils":29}],8:[function(require,module,exports){
  628. var Layer,
  629. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  630. __hasProp = {}.hasOwnProperty,
  631. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  632. Layer = require("./Layer").Layer;
  633. "Todo: make it work in a parent layer";
  634. exports.BackgroundLayer = (function(_super) {
  635. __extends(BackgroundLayer, _super);
  636. function BackgroundLayer(options) {
  637. if (options == null) {
  638. options = {};
  639. }
  640. this.layout = __bind(this.layout, this);
  641. if (options.backgroundColor == null) {
  642. options.backgroundColor = "#fff";
  643. }
  644. options.name = "Background";
  645. BackgroundLayer.__super__.constructor.call(this, options);
  646. this.sendToBack();
  647. this.layout();
  648. Screen.on("resize", this.layout);
  649. }
  650. BackgroundLayer.prototype.layout = function() {
  651. this.width = Screen.width;
  652. return this.height = Screen.height;
  653. };
  654. return BackgroundLayer;
  655. })(Layer);
  656. },{"./Layer":21}],9:[function(require,module,exports){
  657. var CounterKey, DefinedPropertiesKey, DefinedPropertiesValuesKey, EventEmitter, Utils, _,
  658. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  659. __hasProp = {}.hasOwnProperty,
  660. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  661. _ = require("./Underscore")._;
  662. Utils = require("./Utils");
  663. EventEmitter = require("./EventEmitter").EventEmitter;
  664. CounterKey = "_ObjectCounter";
  665. DefinedPropertiesKey = "_DefinedPropertiesKey";
  666. DefinedPropertiesValuesKey = "_DefinedPropertiesValuesKey";
  667. exports.BaseClass = (function(_super) {
  668. __extends(BaseClass, _super);
  669. BaseClass.define = function(propertyName, descriptor) {
  670. if (this !== BaseClass && descriptor.exportable === true) {
  671. descriptor.propertyName = propertyName;
  672. if (this[DefinedPropertiesKey] == null) {
  673. this[DefinedPropertiesKey] = {};
  674. }
  675. this[DefinedPropertiesKey][propertyName] = descriptor;
  676. }
  677. Object.defineProperty(this.prototype, propertyName, descriptor);
  678. return Object.__;
  679. };
  680. BaseClass.simpleProperty = function(name, fallback, exportable) {
  681. if (exportable == null) {
  682. exportable = true;
  683. }
  684. return {
  685. exportable: exportable,
  686. "default": fallback,
  687. get: function() {
  688. return this._getPropertyValue(name);
  689. },
  690. set: function(value) {
  691. return this._setPropertyValue(name, value);
  692. }
  693. };
  694. };
  695. BaseClass.prototype._setPropertyValue = function(k, v) {
  696. return this[DefinedPropertiesValuesKey][k] = v;
  697. };
  698. BaseClass.prototype._getPropertyValue = function(k) {
  699. return Utils.valueOrDefault(this[DefinedPropertiesValuesKey][k], this._getPropertyDefaultValue(k));
  700. };
  701. BaseClass.prototype._getPropertyDefaultValue = function(k) {
  702. return this.constructor[DefinedPropertiesKey][k]["default"];
  703. };
  704. BaseClass.prototype._propertyList = function() {
  705. return this.constructor[DefinedPropertiesKey];
  706. };
  707. BaseClass.prototype.keys = function() {
  708. return _.keys(this.properties);
  709. };
  710. BaseClass.define("properties", {
  711. get: function() {
  712. var k, properties, v, _ref;
  713. properties = {};
  714. _ref = this.constructor[DefinedPropertiesKey];
  715. for (k in _ref) {
  716. v = _ref[k];
  717. if (v.exportable !== false) {
  718. properties[k] = this[k];
  719. }
  720. }
  721. return properties;
  722. },
  723. set: function(value) {
  724. var k, v, _results;
  725. _results = [];
  726. for (k in value) {
  727. v = value[k];
  728. if (this.constructor[DefinedPropertiesKey].hasOwnProperty(k)) {
  729. if (this.constructor[DefinedPropertiesKey].exportable !== false) {
  730. _results.push(this[k] = v);
  731. } else {
  732. _results.push(void 0);
  733. }
  734. } else {
  735. _results.push(void 0);
  736. }
  737. }
  738. return _results;
  739. }
  740. });
  741. BaseClass.define("id", {
  742. get: function() {
  743. return this._id;
  744. }
  745. });
  746. BaseClass.prototype.toString = function() {
  747. var properties;
  748. properties = _.map(this.properties, (function(v, k) {
  749. return "" + k + ":" + v;
  750. }), 4);
  751. return "[" + this.constructor.name + " id:" + this.id + " " + (properties.join(" ")) + "]";
  752. };
  753. function BaseClass(options) {
  754. var _base,
  755. _this = this;
  756. if (options == null) {
  757. options = {};
  758. }
  759. this.toString = __bind(this.toString, this);
  760. this._getPropertyValue = __bind(this._getPropertyValue, this);
  761. this._setPropertyValue = __bind(this._setPropertyValue, this);
  762. BaseClass.__super__.constructor.apply(this, arguments);
  763. this[DefinedPropertiesValuesKey] = {};
  764. if ((_base = this.constructor)[CounterKey] == null) {
  765. _base[CounterKey] = 0;
  766. }
  767. this.constructor[CounterKey] += 1;
  768. this._id = this.constructor[CounterKey];
  769. _.map(this.constructor[DefinedPropertiesKey], function(descriptor, name) {
  770. return _this[name] = Utils.valueOrDefault(options[name], _this._getPropertyDefaultValue(name));
  771. });
  772. }
  773. return BaseClass;
  774. })(EventEmitter);
  775. },{"./EventEmitter":14,"./Underscore":28,"./Utils":29}],10:[function(require,module,exports){
  776. var CompatImageView, CompatLayer, CompatScrollView, CompatView, Layer, compatProperty, compatWarning, _ref,
  777. __hasProp = {}.hasOwnProperty,
  778. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  779. Layer = require("./Layer").Layer;
  780. compatWarning = function(msg) {
  781. return console.warn(msg);
  782. };
  783. compatProperty = function(name, originalName) {
  784. return {
  785. exportable: false,
  786. get: function() {
  787. compatWarning("" + originalName + " is a deprecated property");
  788. return this[name];
  789. },
  790. set: function(value) {
  791. compatWarning("" + originalName + " is a deprecated property");
  792. return this[name] = value;
  793. }
  794. };
  795. };
  796. CompatLayer = (function(_super) {
  797. var addSubView, removeSubView;
  798. __extends(CompatLayer, _super);
  799. function CompatLayer(options) {
  800. if (options == null) {
  801. options = {};
  802. }
  803. if (options.hasOwnProperty("superView")) {
  804. options.superLayer = options.superView;
  805. }
  806. CompatLayer.__super__.constructor.call(this, options);
  807. }
  808. CompatLayer.define("superView", compatProperty("superLayer", "superView"));
  809. CompatLayer.define("subViews", compatProperty("subLayers", "subViews"));
  810. CompatLayer.define("siblingViews", compatProperty("siblingLayers", "siblingViews"));
  811. addSubView = function(layer) {
  812. return this.addSubLayer(layer);
  813. };
  814. removeSubView = function(layer) {
  815. return this.removeSubLayer(layer);
  816. };
  817. return CompatLayer;
  818. })(Layer);
  819. CompatView = (function(_super) {
  820. __extends(CompatView, _super);
  821. function CompatView(options) {
  822. if (options == null) {
  823. options = {};
  824. }
  825. compatWarning("Views are now called Layers");
  826. CompatView.__super__.constructor.call(this, options);
  827. }
  828. return CompatView;
  829. })(CompatLayer);
  830. CompatImageView = (function(_super) {
  831. __extends(CompatImageView, _super);
  832. function CompatImageView() {
  833. _ref = CompatImageView.__super__.constructor.apply(this, arguments);
  834. return _ref;
  835. }
  836. return CompatImageView;
  837. })(CompatView);
  838. CompatScrollView = (function(_super) {
  839. __extends(CompatScrollView, _super);
  840. function CompatScrollView() {
  841. CompatScrollView.__super__.constructor.apply(this, arguments);
  842. this.scroll = true;
  843. }
  844. return CompatScrollView;
  845. })(CompatView);
  846. window.Layer = CompatLayer;
  847. window.Framer.Layer = CompatLayer;
  848. window.View = CompatView;
  849. window.ImageView = CompatImageView;
  850. window.ScrollView = CompatScrollView;
  851. window.utils = window.Utils;
  852. },{"./Layer":21}],11:[function(require,module,exports){
  853. var Utils;
  854. Utils = require("./Utils");
  855. exports.Config = {
  856. targetFPS: 60,
  857. rootBaseCSS: {
  858. "-webkit-perspective": 1000,
  859. "position": "absolute",
  860. "left": 0,
  861. "top": 0,
  862. "right": 0,
  863. "bottom": 0
  864. },
  865. layerBaseCSS: {
  866. "display": "block",
  867. "position": "absolute",
  868. "-webkit-box-sizing": "border-box",
  869. "-webkit-user-select": "none",
  870. "background-repeat": "no-repeat",
  871. "background-size": "cover",
  872. "-webkit-overflow-scrolling": "touch"
  873. }
  874. };
  875. },{"./Utils":29}],12:[function(require,module,exports){
  876. var EventKeys, Utils, createDebugLayer, errorWarning, hideDebug, showDebug, toggleDebug, _debugLayers, _errorWarningLayer;
  877. Utils = require("./Utils");
  878. _debugLayers = null;
  879. createDebugLayer = function(layer) {
  880. var overLayer;
  881. overLayer = new Layer({
  882. frame: layer.screenFrame(),
  883. backgroundColor: "rgba(50,150,200,.35)"
  884. });
  885. overLayer.style = {
  886. textAlign: "center",
  887. color: "white",
  888. font: "10px/1em Monaco",
  889. lineHeight: "" + (overLayer.height + 1) + "px",
  890. boxShadow: "inset 0 0 0 1px rgba(255,255,255,.5)"
  891. };
  892. overLayer.html = layer.name || layer.id;
  893. overLayer.on(Events.Click, function(event, layer) {
  894. layer.scale = 0.8;
  895. return layer.animate({
  896. properties: {
  897. scale: 1
  898. },
  899. curve: "spring(1000,10,0)"
  900. });
  901. });
  902. return overLayer;
  903. };
  904. showDebug = function() {
  905. return _debugLayers = Layer.Layers().map(createDebugLayer);
  906. };
  907. hideDebug = function() {
  908. return _debugLayers.map(function(layer) {
  909. return layer.destroy();
  910. });
  911. };
  912. toggleDebug = Utils.toggle(showDebug, hideDebug);
  913. EventKeys = {
  914. Shift: 16,
  915. Escape: 27
  916. };
  917. window.document.onkeyup = function(event) {
  918. if (event.keyCode === EventKeys.Escape) {
  919. return toggleDebug()();
  920. }
  921. };
  922. _errorWarningLayer = null;
  923. errorWarning = function() {
  924. var layer;
  925. if (_errorWarningLayer) {
  926. return;
  927. }
  928. layer = new Layer({
  929. x: 20,
  930. y: -50,
  931. width: 300,
  932. height: 40
  933. });
  934. layer.states.add({
  935. visible: {
  936. x: 20,
  937. y: 20,
  938. width: 300,
  939. height: 40
  940. }
  941. });
  942. layer.html = "Javascript Error, see the console";
  943. layer.style = {
  944. font: "12px/1.35em Menlo",
  945. color: "white",
  946. textAlign: "center",
  947. lineHeight: "" + layer.height + "px",
  948. borderRadius: "5px",
  949. backgroundColor: "rgba(255,0,0,.8)"
  950. };
  951. layer.states.animationOptions = {
  952. curve: "spring",
  953. curveOptions: {
  954. tension: 1000,
  955. friction: 30
  956. }
  957. };
  958. layer.states["switch"]("visible");
  959. layer.on(Events.Click, function() {
  960. return this.states["switch"]("default");
  961. });
  962. return _errorWarningLayer = layer;
  963. };
  964. window.onerror = errorWarning;
  965. },{"./Utils":29}],13:[function(require,module,exports){
  966. var Originals, Utils, _;
  967. _ = require("./Underscore")._;
  968. Utils = require("./Utils");
  969. Originals = {
  970. Layer: {
  971. backgroundColor: "rgba(0,124,255,.5)",
  972. width: 100,
  973. height: 100
  974. },
  975. Animation: {
  976. curve: "linear",
  977. time: 1
  978. }
  979. };
  980. exports.Defaults = {
  981. getDefaults: function(className, options) {
  982. var defaults, k, v, _ref;
  983. defaults = _.clone(Originals[className]);
  984. _ref = Framer.Defaults[className];
  985. for (k in _ref) {
  986. v = _ref[k];
  987. defaults[k] = _.isFunction(v) ? v() : v;
  988. }
  989. for (k in defaults) {
  990. v = defaults[k];
  991. if (!options.hasOwnProperty(k)) {
  992. options[k] = v;
  993. }
  994. }
  995. return options;
  996. },
  997. reset: function() {
  998. return window.Framer.Defaults = _.clone(Originals);
  999. }
  1000. };
  1001. },{"./Underscore":28,"./Utils":29}],14:[function(require,module,exports){
  1002. var EventEmitterEventsKey, _,
  1003. __slice = [].slice;
  1004. _ = require("./Underscore")._;
  1005. EventEmitterEventsKey = "_events";
  1006. exports.EventEmitter = (function() {
  1007. function EventEmitter() {
  1008. this[EventEmitterEventsKey] = {};
  1009. }
  1010. EventEmitter.prototype._eventCheck = function(event, method) {
  1011. if (!event) {
  1012. return console.warn("" + this.constructor.name + "." + method + " missing event (like 'click')");
  1013. }
  1014. };
  1015. EventEmitter.prototype.emit = function() {
  1016. var args, event, listener, _i, _len, _ref, _ref1;
  1017. event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
  1018. if (!((_ref = this[EventEmitterEventsKey]) != null ? _ref[event] : void 0)) {
  1019. return;
  1020. }
  1021. _ref1 = this[EventEmitterEventsKey][event];
  1022. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  1023. listener = _ref1[_i];
  1024. listener.apply(null, args);
  1025. }
  1026. };
  1027. EventEmitter.prototype.addListener = function(event, listener) {
  1028. var _base;
  1029. this._eventCheck(event, "addListener");
  1030. if (this[EventEmitterEventsKey] == null) {
  1031. this[EventEmitterEventsKey] = {};
  1032. }
  1033. if ((_base = this[EventEmitterEventsKey])[event] == null) {
  1034. _base[event] = [];
  1035. }
  1036. return this[EventEmitterEventsKey][event].push(listener);
  1037. };
  1038. EventEmitter.prototype.removeListener = function(event, listener) {
  1039. this._eventCheck(event, "removeListener");
  1040. if (!this[EventEmitterEventsKey]) {
  1041. return;
  1042. }
  1043. if (!this[EventEmitterEventsKey][event]) {
  1044. return;
  1045. }
  1046. this[EventEmitterEventsKey][event] = _.without(this[EventEmitterEventsKey][event], listener);
  1047. };
  1048. EventEmitter.prototype.once = function(event, listener) {
  1049. var fn,
  1050. _this = this;
  1051. fn = function() {
  1052. _this.removeListener(event, fn);
  1053. return listener.apply(null, arguments);
  1054. };
  1055. return this.on(event, fn);
  1056. };
  1057. EventEmitter.prototype.removeAllListeners = function(event) {
  1058. var listener, _i, _len, _ref;
  1059. if (!this[EventEmitterEventsKey]) {
  1060. return;
  1061. }
  1062. if (!this[EventEmitterEventsKey][event]) {
  1063. return;
  1064. }
  1065. _ref = this[EventEmitterEventsKey][event];
  1066. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1067. listener = _ref[_i];
  1068. this.removeListener(event, listener);
  1069. }
  1070. };
  1071. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  1072. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  1073. return EventEmitter;
  1074. })();
  1075. },{"./Underscore":28}],15:[function(require,module,exports){
  1076. var Events, Utils, _;
  1077. _ = require("./Underscore")._;
  1078. Utils = require("./Utils");
  1079. Events = {};
  1080. if (Utils.isTouch()) {
  1081. Events.TouchStart = "touchstart";
  1082. Events.TouchEnd = "touchend";
  1083. Events.TouchMove = "touchmove";
  1084. } else {
  1085. Events.TouchStart = "mousedown";
  1086. Events.TouchEnd = "mouseup";
  1087. Events.TouchMove = "mousemove";
  1088. }
  1089. Events.Click = Events.TouchEnd;
  1090. Events.MouseOver = "mouseover";
  1091. Events.MouseOut = "mouseout";
  1092. Events.AnimationStart = "start";
  1093. Events.AnimationStop = "stop";
  1094. Events.AnimationEnd = "end";
  1095. Events.Scroll = "scroll";
  1096. Events.touchEvent = function(event) {
  1097. var touchEvent, _ref, _ref1;
  1098. touchEvent = (_ref = event.touches) != null ? _ref[0] : void 0;
  1099. if (touchEvent == null) {
  1100. touchEvent = (_ref1 = event.changedTouches) != null ? _ref1[0] : void 0;
  1101. }
  1102. if (touchEvent == null) {
  1103. touchEvent = event;
  1104. }
  1105. return touchEvent;
  1106. };
  1107. exports.Events = Events;
  1108. },{"./Underscore":28,"./Utils":29}],16:[function(require,module,exports){
  1109. exports.MobileScrollFix = require("./MobileScrollFix");
  1110. },{"./MobileScrollFix":17}],17:[function(require,module,exports){
  1111. var Utils,
  1112. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  1113. __hasProp = {}.hasOwnProperty,
  1114. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  1115. Utils = require("../Utils");
  1116. exports.enable = function() {
  1117. var MobileScrollFixLayer, handleScrollingLayerTouchMove, handleScrollingLayerTouchStart;
  1118. handleScrollingLayerTouchMove = function(event) {
  1119. return event.stopPropagation();
  1120. };
  1121. handleScrollingLayerTouchStart = function(event) {
  1122. var element, startTopScroll;
  1123. element = this._element;
  1124. startTopScroll = element.scrollTop;
  1125. if (startTopScroll <= 0) {
  1126. element.scrollTop = 1;
  1127. }
  1128. if (startTopScroll + element.offsetHeight >= element.scrollHeight) {
  1129. return element.scrollTop = element.scrollHeight - element.offsetHeight - 1;
  1130. }
  1131. };
  1132. MobileScrollFixLayer = (function(_super) {
  1133. __extends(MobileScrollFixLayer, _super);
  1134. function MobileScrollFixLayer(options) {
  1135. this.__createRootElement = __bind(this.__createRootElement, this);
  1136. this._updateScrollListeners = __bind(this._updateScrollListeners, this);
  1137. MobileScrollFixLayer.__super__.constructor.call(this, options);
  1138. this.on("change:scrollVertical", this._updateScrollListeners);
  1139. this._updateScrollListeners();
  1140. }
  1141. MobileScrollFixLayer.prototype._updateScrollListeners = function() {
  1142. if (this.scrollVertical === true) {
  1143. this.on("touchmove", handleScrollingLayerTouchMove);
  1144. return this.on("touchstart", handleScrollingLayerTouchStart);
  1145. } else {
  1146. this.off("touchmove", handleScrollingLayerTouchMove);
  1147. return this.off("touchstart", handleScrollingLayerTouchStart);
  1148. }
  1149. };
  1150. MobileScrollFixLayer.prototype.__createRootElement = function() {
  1151. var rootElement;
  1152. rootElement = MobileScrollFixLayer.__super__.__createRootElement.apply(this, arguments);
  1153. rootElement.addEventListener("touchmove", function(event) {
  1154. return event.preventDefault();
  1155. });
  1156. return rootElement;
  1157. };
  1158. return MobileScrollFixLayer;
  1159. })(Framer.Layer);
  1160. return window.Layer = window.Framer.Layer = MobileScrollFixLayer;
  1161. };
  1162. },{"../Utils":29}],18:[function(require,module,exports){
  1163. var BaseClass,
  1164. __hasProp = {}.hasOwnProperty,
  1165. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  1166. BaseClass = require("./BaseClass").BaseClass;
  1167. exports.Frame = (function(_super) {
  1168. __extends(Frame, _super);
  1169. Frame.define("x", Frame.simpleProperty("x", 0));
  1170. Frame.define("y", Frame.simpleProperty("y", 0));
  1171. Frame.define("width", Frame.simpleProperty("width", 0));
  1172. Frame.define("height", Frame.simpleProperty("height", 0));
  1173. Frame.define("minX", Frame.simpleProperty("x", 0, false));
  1174. Frame.define("minY", Frame.simpleProperty("y", 0, false));
  1175. function Frame(options) {
  1176. var k, _i, _len, _ref;
  1177. if (options == null) {
  1178. options = {};
  1179. }
  1180. Frame.__super__.constructor.call(this, options);
  1181. _ref = ["minX", "midX", "maxX", "minY", "midY", "maxY"];
  1182. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1183. k = _ref[_i];
  1184. if (options.hasOwnProperty(k)) {
  1185. this[k] = options[k];
  1186. }
  1187. }
  1188. }
  1189. Frame.define("midX", {
  1190. get: function() {
  1191. return Utils.frameGetMidX(this);
  1192. },
  1193. set: function(value) {
  1194. return Utils.frameSetMidX(this, value);
  1195. }
  1196. });
  1197. Frame.define("maxX", {
  1198. get: function() {
  1199. return Utils.frameGetMaxX(this);
  1200. },
  1201. set: function(value) {
  1202. return Utils.frameSetMaxX(this, value);
  1203. }
  1204. });
  1205. Frame.define("midY", {
  1206. get: function() {
  1207. return Utils.frameGetMidY(this);
  1208. },
  1209. set: function(value) {
  1210. return Utils.frameSetMidY(this, value);
  1211. }
  1212. });
  1213. Frame.define("maxY", {
  1214. get: function() {
  1215. return Utils.frameGetMaxY(this);
  1216. },
  1217. set: function(value) {
  1218. return Utils.frameSetMaxY(this, value);
  1219. }
  1220. });
  1221. return Frame;
  1222. })(BaseClass);
  1223. },{"./BaseClass":9}],19:[function(require,module,exports){
  1224. var Defaults, Framer, _;
  1225. _ = require("./Underscore")._;
  1226. Framer = {};
  1227. Framer._ = _;
  1228. Framer.Utils = require("./Utils");
  1229. Framer.Frame = (require("./Frame")).Frame;
  1230. Framer.Layer = (require("./Layer")).Layer;
  1231. Framer.BackgroundLayer = (require("./BackgroundLayer")).BackgroundLayer;
  1232. Framer.VideoLayer = (require("./VideoLayer")).VideoLayer;
  1233. Framer.Events = (require("./Events")).Events;
  1234. Framer.Animation = (require("./Animation")).Animation;
  1235. Framer.Screen = (require("./Screen")).Screen;
  1236. Framer.print = (require("./Print")).print;
  1237. if (window) {
  1238. _.extend(window, Framer);
  1239. }
  1240. Framer.Config = (require("./Config")).Config;
  1241. Framer.EventEmitter = (require("./EventEmitter")).EventEmitter;
  1242. Framer.BaseClass = (require("./BaseClass")).BaseClass;
  1243. Framer.LayerStyle = (require("./LayerStyle")).LayerStyle;
  1244. Framer.AnimationLoop = (require("./AnimationLoop")).AnimationLoop;
  1245. Framer.LinearAnimator = (require("./Animators/LinearAnimator")).LinearAnimator;
  1246. Framer.BezierCurveAnimator = (require("./Animators/BezierCurveAnimator")).BezierCurveAnimator;
  1247. Framer.SpringDHOAnimator = (require("./Animators/SpringDHOAnimator")).SpringDHOAnimator;
  1248. Framer.SpringRK4Animator = (require("./Animators/SpringRK4Animator")).SpringRK4Animator;
  1249. Framer.Importer = (require("./Importer")).Importer;
  1250. Framer.Debug = (require("./Debug")).Debug;
  1251. Framer.Session = (require("./Session")).Session;
  1252. Framer.Extras = require("./Extras/Extras");
  1253. if (window) {
  1254. window.Framer = Framer;
  1255. }
  1256. require("./Compat");
  1257. if (Utils.isMobile()) {
  1258. Framer.Extras.MobileScrollFix.enable();
  1259. }
  1260. Defaults = (require("./Defaults")).Defaults;
  1261. Framer.resetDefaults = Defaults.reset;
  1262. Framer.resetDefaults();
  1263. },{"./Animation":1,"./AnimationLoop":2,"./Animators/BezierCurveAnimator":4,"./Animators/LinearAnimator":5,"./Animators/SpringDHOAnimator":6,"./Animators/SpringRK4Animator":7,"./BackgroundLayer":8,"./BaseClass":9,"./Compat":10,"./Config":11,"./Debug":12,"./Defaults":13,"./EventEmitter":14,"./Events":15,"./Extras/Extras":16,"./Frame":18,"./Importer":20,"./Layer":21,"./LayerStyle":24,"./Print":25,"./Screen":26,"./Session":27,"./Underscore":28,"./Utils":29,"./VideoLayer":30}],20:[function(require,module,exports){
  1264. var ChromeAlert, Utils, _;
  1265. _ = require("./Underscore")._;
  1266. Utils = require("./Utils");
  1267. ChromeAlert = "Importing layers is currently only supported on Safari. If you really want it to work with Chrome quit it, open a terminal and run:\nopen -a Google\ Chrome -–allow-file-access-from-files";
  1268. exports.Importer = (function() {
  1269. function Importer(path, extraLayerProperties) {
  1270. this.path = path;
  1271. this.extraLayerProperties = extraLayerProperties != null ? extraLayerProperties : {};
  1272. this.paths = {
  1273. layerInfo: Utils.pathJoin(this.path, "layers.json"),
  1274. images: Utils.pathJoin(this.path, "images"),
  1275. documentName: this.path.split("/").pop()
  1276. };
  1277. this._createdLayers = [];
  1278. this._createdLayersByName = {};
  1279. }
  1280. Importer.prototype.load = function() {
  1281. var layer, layerInfo, layersByName, _i, _j, _len, _len1, _ref, _ref1,
  1282. _this = this;
  1283. layersByName = {};
  1284. layerInfo = this._loadlayerInfo();
  1285. layerInfo.map(function(layerItemInfo) {
  1286. return _this._createLayer(layerItemInfo);
  1287. });
  1288. _ref = this._createdLayers;
  1289. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1290. layer = _ref[_i];
  1291. this._correctLayer(layer);
  1292. }
  1293. _ref1 = this._createdLayers;
  1294. for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
  1295. layer = _ref1[_j];
  1296. if (!layer.superLayer) {
  1297. layer.superLayer = null;
  1298. }
  1299. }
  1300. return this._createdLayersByName;
  1301. };
  1302. Importer.prototype._loadlayerInfo = function() {
  1303. var importedKey, _ref;
  1304. importedKey = "" + this.paths.documentName + "/layers.json.js";
  1305. if ((_ref = window.__imported__) != null ? _ref.hasOwnProperty(importedKey) : void 0) {
  1306. return window.__imported__[importedKey];
  1307. }
  1308. return Framer.Utils.domLoadJSONSync(this.paths.layerInfo);
  1309. };
  1310. Importer.prototype._createLayer = function(info, superLayer) {
  1311. var LayerClass, layer, layerInfo, _ref,
  1312. _this = this;
  1313. LayerClass = Layer;
  1314. layerInfo = {
  1315. shadow: true,
  1316. name: info.name,
  1317. frame: info.layerFrame,
  1318. clip: false,
  1319. backgroundColor: null,
  1320. visible: (_ref = info.visible) != null ? _ref : true
  1321. };
  1322. _.extend(layerInfo, this.extraLayerProperties);
  1323. if (info.image) {
  1324. layerInfo.frame = info.image.frame;
  1325. layerInfo.image = Utils.pathJoin(this.path, info.image.path);
  1326. }
  1327. if (info.maskFrame) {
  1328. layerInfo.frame = info.maskFrame;
  1329. layerInfo.clip = true;
  1330. }
  1331. if (superLayer != null ? superLayer.contentLayer : void 0) {
  1332. layerInfo.superLayer = superLayer.contentLayer;
  1333. } else if (superLayer) {
  1334. layerInfo.superLayer = superLayer;
  1335. }
  1336. layer = new LayerClass(layerInfo);
  1337. layer.name = layerInfo.name;
  1338. if (!layer.image && !info.children.length && !info.maskFrame) {
  1339. layer.frame = new Frame;
  1340. }
  1341. info.children.reverse().map(function(info) {
  1342. return _this._createLayer(info, layer);
  1343. });
  1344. if (!layer.image && !info.maskFrame) {
  1345. layer.frame = layer.contentFrame();
  1346. }
  1347. layer._info = info;
  1348. this._createdLayers.push(layer);
  1349. return this._createdLayersByName[layer.name] = layer;
  1350. };
  1351. Importer.prototype._correctLayer = function(layer) {
  1352. var traverse;
  1353. traverse = function(layer) {
  1354. var subLayer, _i, _len, _ref, _results;
  1355. if (layer.superLayer) {
  1356. layer.frame = Utils.convertPoint(layer.frame, null, layer.superLayer);
  1357. }
  1358. _ref = layer.subLayers;
  1359. _results = [];
  1360. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1361. subLayer = _ref[_i];
  1362. _results.push(traverse(subLayer));
  1363. }
  1364. return _results;
  1365. };
  1366. if (!layer.superLayer) {
  1367. return traverse(layer);
  1368. }
  1369. };
  1370. return Importer;
  1371. })();
  1372. exports.Importer.load = function(path) {
  1373. var importer;
  1374. importer = new exports.Importer(path);
  1375. return importer.load();
  1376. };
  1377. },{"./Underscore":28,"./Utils":29}],21:[function(require,module,exports){
  1378. var Animation, BaseClass, Config, Defaults, EventEmitter, Frame, LayerDraggable, LayerStates, LayerStyle, Session, Utils, frameProperty, layerProperty, layerStyleProperty, _,
  1379. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  1380. __hasProp = {}.hasOwnProperty,
  1381. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  1382. __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
  1383. __slice = [].slice;
  1384. _ = require("./Underscore")._;
  1385. Utils = require("./Utils");
  1386. Config = require("./Config").Config;
  1387. Defaults = require("./Defaults").Defaults;
  1388. Session = require("./Session").Session;
  1389. BaseClass = require("./BaseClass").BaseClass;
  1390. EventEmitter = require("./EventEmitter").EventEmitter;
  1391. Animation = require("./Animation").Animation;
  1392. Frame = require("./Frame").Frame;
  1393. LayerStyle = require("./LayerStyle").LayerStyle;
  1394. LayerStates = require("./LayerStates").LayerStates;
  1395. LayerDraggable = require("./LayerDraggable").LayerDraggable;
  1396. Session._RootElement = null;
  1397. Session._LayerList = [];
  1398. layerProperty = function(name, cssProperty, fallback, validator, set) {
  1399. return {
  1400. exportable: true,
  1401. "default": fallback,
  1402. get: function() {
  1403. return this._getPropertyValue(name);
  1404. },
  1405. set: function(value) {
  1406. if ((typeof validator === "function" ? validator(value) : void 0) === false) {
  1407. throw Error("value '" + value + "' of type " + (typeof value) + " is not valid for a Layer." + name + " property");
  1408. }
  1409. this._setPropertyValue(name, value);
  1410. this.style[cssProperty] = LayerStyle[cssProperty](this);
  1411. this.emit("change:" + name, value);
  1412. if (set) {
  1413. return set(this, value);
  1414. }
  1415. }
  1416. };
  1417. };
  1418. layerStyleProperty = function(cssProperty) {
  1419. return {
  1420. exportable: true,
  1421. get: function() {
  1422. return this.style[cssProperty];
  1423. },
  1424. set: function(value) {
  1425. this.style[cssProperty] = value;
  1426. return this.emit("change:" + cssProperty, value);
  1427. }
  1428. };
  1429. };
  1430. frameProperty = function(name) {
  1431. return {
  1432. exportable: false,
  1433. get: function() {
  1434. return this.frame[name];
  1435. },
  1436. set: function(value) {
  1437. var frame;
  1438. frame = this.frame;
  1439. frame[name] = value;
  1440. return this.frame = frame;
  1441. }
  1442. };
  1443. };
  1444. exports.Layer = (function(_super) {
  1445. __extends(Layer, _super);
  1446. function Layer(options) {
  1447. var frame;
  1448. if (options == null) {
  1449. options = {};
  1450. }
  1451. this.addListener = __bind(this.addListener, this);
  1452. this.__insertElement = __bind(this.__insertElement, this);
  1453. this.__createRootElement = __bind(this.__createRootElement, this);
  1454. Session._LayerList.push(this);
  1455. this._prefer2d = false;
  1456. this._createElement();
  1457. this._setDefaultCSS();
  1458. options = Defaults.getDefaults("Layer", options);
  1459. Layer.__super__.constructor.call(this, options);
  1460. this._element.id = "FramerLayer-" + this.id;
  1461. if (options.hasOwnProperty("frame")) {
  1462. frame = new Frame(options.frame);
  1463. } else {
  1464. frame = new Frame(options);
  1465. }
  1466. this.frame = frame;
  1467. if (!options.superLayer) {
  1468. this.bringToFront();
  1469. if (!options.shadow) {
  1470. this._insertElement();
  1471. }
  1472. } else {
  1473. this.superLayer = options.superLayer;
  1474. }
  1475. this._subLayers = [];
  1476. }
  1477. Layer.define("width", layerProperty("width", "width", 100, _.isNumber));
  1478. Layer.define("height", layerProperty("height", "height", 100, _.isNumber));
  1479. Layer.define("visible", layerProperty("visible", "display", true, _.isBool));
  1480. Layer.define("opacity", layerProperty("opacity", "opacity", 1, _.isNumber));
  1481. Layer.define("index", layerProperty("index", "zIndex", 0, _.isNumber));
  1482. Layer.define("clip", layerProperty("clip", "overflow", true, _.isBool));
  1483. Layer.define("scrollHorizontal", layerProperty("scrollHorizontal", "overflowX", false, _.isBool, function(layer, value) {
  1484. if (value === true) {
  1485. return layer.ignoreEvents = false;
  1486. }
  1487. }));
  1488. Layer.define("scrollVertical", layerProperty("scrollVertical", "overflowY", false, _.isBool, function(layer, value) {
  1489. if (value === true) {
  1490. return layer.ignoreEvents = false;
  1491. }
  1492. }));
  1493. Layer.define("scroll", {
  1494. get: function() {
  1495. return this.scrollHorizontal === true || this.scrollVertical === true;
  1496. },
  1497. set: function(value) {
  1498. return this.scrollHorizontal = this.scrollVertical = true;
  1499. }
  1500. });
  1501. Layer.define("ignoreEvents", layerProperty("ignoreEvents", "pointerEvents", true, _.isBool));
  1502. Layer.define("x", layerProperty("x", "webkitTransform", 0, _.isNumber));
  1503. Layer.define("y", layerProperty("y", "webkitTransform", 0, _.isNumber));
  1504. Layer.define("z", layerProperty("z", "webkitTransform", 0, _.isNumber));
  1505. Layer.define("scaleX", layerProperty("scaleX", "webkitTransform", 1, _.isNumber));
  1506. Layer.define("scaleY", layerProperty("scaleY", "webkitTransform", 1, _.isNumber));
  1507. Layer.define("scaleZ", layerProperty("scaleZ", "webkitTransform", 1, _.isNumber));
  1508. Layer.define("scale", layerProperty("scale", "webkitTransform", 1, _.isNumber));
  1509. Layer.define("skewX", layerProperty("skewX", "webkitTransform", 0, _.isNumber));
  1510. Layer.define("skewY", layerProperty("skewY", "webkitTransform", 0, _.isNumber));
  1511. Layer.define("skew", layerProperty("skew", "webkitTransform", 0, _.isNumber));
  1512. Layer.define("originX", layerProperty("originX", "webkitTransformOrigin", 0.5, _.isNumber));
  1513. Layer.define("originY", layerProperty("originY", "webkitTransformOrigin", 0.5, _.isNumber));
  1514. Layer.define("rotationX", layerProperty("rotationX", "webkitTransform", 0, _.isNumber));
  1515. Layer.define("rotationY", layerProperty("rotationY", "webkitTransform", 0, _.isNumber));
  1516. Layer.define("rotationZ", layerProperty("rotationZ", "webkitTransform", 0, _.isNumber));
  1517. Layer.define("rotation", layerProperty("rotationZ", "webkitTransform", 0, _.isNumber));
  1518. Layer.define("blur", layerProperty("blur", "webkitFilter", 0, _.isNumber));
  1519. Layer.define("brightness", layerProperty("brightness", "webkitFilter", 100, _.isNumber));
  1520. Layer.define("saturate", layerProperty("saturate", "webkitFilter", 100, _.isNumber));
  1521. Layer.define("hueRotate", layerProperty("hueRotate", "webkitFilter", 0, _.isNumber));
  1522. Layer.define("contrast", layerProperty("contrast", "webkitFilter", 100, _.isNumber));
  1523. Layer.define("invert", layerProperty("invert", "webkitFilter", 0, _.isNumber));
  1524. Layer.define("grayscale", layerProperty("grayscale", "webkitFilter", 0, _.isNumber));
  1525. Layer.define("sepia", layerProperty("sepia", "webkitFilter", 0, _.isNumber));
  1526. Layer.define("shadowX", layerProperty("shadowX", "boxShadow", 0, _.isNumber));
  1527. Layer.define("shadowY", layerProperty("shadowY", "boxShadow", 0, _.isNumber));
  1528. Layer.define("shadowBlur", layerProperty("shadowBlur", "boxShadow", 0, _.isNumber));
  1529. Layer.define("shadowSpread", layerProperty("shadowSpread", "boxShadow", 0, _.isNumber));
  1530. Layer.define("shadowColor", layerProperty("shadowColor", "boxShadow", ""));
  1531. Layer.define("backgroundColor", layerStyleProperty("backgroundColor"));
  1532. Layer.define("color", layerStyleProperty("color"));
  1533. Layer.define("borderRadius", layerStyleProperty("borderRadius"));
  1534. Layer.define("borderColor", layerStyleProperty("borderColor"));
  1535. Layer.define("borderWidth", layerStyleProperty("borderWidth"));
  1536. Layer.define("name", {
  1537. exportable: true,
  1538. "default": "",
  1539. get: function() {
  1540. return this._getPropertyValue("name");
  1541. },
  1542. set: function(value) {
  1543. this._setPropertyValue("name", value);
  1544. return this._element.setAttribute("name", value);
  1545. }
  1546. });
  1547. Layer.define("frame", {
  1548. get: function() {
  1549. return new Frame(this);
  1550. },
  1551. set: function(frame) {
  1552. var k, _i, _len, _ref, _results;
  1553. if (!frame) {
  1554. return;
  1555. }
  1556. _ref = ["x", "y", "width", "height"];
  1557. _results = [];
  1558. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1559. k = _ref[_i];
  1560. _results.push(this[k] = frame[k]);
  1561. }
  1562. return _results;
  1563. }
  1564. });
  1565. Layer.define("minX", frameProperty("minX"));
  1566. Layer.define("midX", frameProperty("midX"));
  1567. Layer.define("maxX", frameProperty("maxX"));
  1568. Layer.define("minY", frameProperty("minY"));
  1569. Layer.define("midY", frameProperty("midY"));
  1570. Layer.define("maxY", frameProperty("maxY"));
  1571. Layer.prototype.convertPoint = function(point) {
  1572. return Utils.convertPoint(point, null, this);
  1573. };
  1574. Layer.prototype.screenFrame = function() {
  1575. return Utils.convertPoint(this.frame, this, null);
  1576. };
  1577. Layer.prototype.contentFrame = function() {
  1578. return Utils.frameMerge(this.subLayers.map(function(layer) {
  1579. return layer.frame.properties;
  1580. }));
  1581. };
  1582. Layer.prototype.centerFrame = function() {
  1583. var frame;
  1584. if (this.superLayer) {
  1585. frame = this.frame;
  1586. frame.midX = parseInt(this.superLayer.width / 2.0);
  1587. frame.midY = parseInt(this.superLayer.height / 2.0);
  1588. return frame;
  1589. } else {
  1590. frame = this.frame;
  1591. frame.midX = parseInt(window.innerWidth / 2.0);
  1592. frame.midY = parseInt(window.innerHeight / 2.0);
  1593. return frame;
  1594. }
  1595. };
  1596. Layer.prototype.center = function() {
  1597. return this.frame = this.centerFrame();
  1598. };
  1599. Layer.prototype.centerX = function() {
  1600. return this.x = this.centerFrame().x;
  1601. };
  1602. Layer.prototype.centerY = function() {
  1603. return this.y = this.centerFrame().y;
  1604. };
  1605. Layer.prototype.pixelAlign = function() {
  1606. this.x = parseInt(this.x);
  1607. return this.y = parseInt(this.y);
  1608. };
  1609. Layer.define("style", {
  1610. get: function() {
  1611. return this._element.style;
  1612. },
  1613. set: function(value) {
  1614. _.extend(this._element.style, value);
  1615. return this.emit("change:style");
  1616. }
  1617. });
  1618. Layer.define("html", {
  1619. get: function() {
  1620. var _ref;
  1621. return (_ref = this._elementHTML) != null ? _ref.innerHTML : void 0;
  1622. },
  1623. set: function(value) {
  1624. if (!this._elementHTML) {
  1625. this._elementHTML = document.createElement("div");
  1626. this._element.appendChild(this._elementHTML);
  1627. }
  1628. this._elementHTML.innerHTML = value;
  1629. if (!(this._elementHTML.childNodes.length === 1 && this._elementHTML.childNodes[0].nodeName === "#text")) {
  1630. this.ignoreEvents = false;
  1631. }
  1632. return this.emit("change:html");
  1633. }
  1634. });
  1635. Layer.prototype.computedStyle = function() {
  1636. return document.defaultView.getComputedStyle(this._element);
  1637. };
  1638. Layer.prototype._setDefaultCSS = function() {
  1639. return this.style = Config.layerBaseCSS;
  1640. };
  1641. Layer.define("classList", {
  1642. get: function() {
  1643. return this._element.classList;
  1644. }
  1645. });
  1646. Layer.prototype._createElement = function() {
  1647. if (this._element != null) {
  1648. return;
  1649. }
  1650. return this._element = document.createElement("div");
  1651. };
  1652. Layer.prototype._insertElement = function() {
  1653. return Utils.domComplete(this.__insertElement);
  1654. };
  1655. Layer.prototype.__createRootElement = function() {
  1656. var element;
  1657. element = document.createElement("div");
  1658. element.id = "FramerRoot";
  1659. _.extend(element.style, Config.rootBaseCSS);
  1660. $("#gamemain").append(element);
  1661. return element;
  1662. };
  1663. Layer.prototype.__insertElement = function() {
  1664. if (Session._RootElement == null) {
  1665. Session._RootElement = this.__createRootElement();
  1666. }
  1667. return Session._RootElement.appendChild(this._element);
  1668. };
  1669. Layer.prototype.destroy = function() {
  1670. var _ref;
  1671. if (this.superLayer) {
  1672. this.superLayer._subLayers = _.without(this.superLayer._subLayers, this);
  1673. }
  1674. if ((_ref = this._element.parentNode) != null) {
  1675. _ref.removeChild(this._element);
  1676. }
  1677. this.removeAllListeners();
  1678. return Session._LayerList = _.without(Session._LayerList, this);
  1679. };
  1680. Layer.prototype.copy = function() {
  1681. var copiedSublayer, layer, subLayer, _i, _len, _ref;
  1682. layer = this.copySingle();
  1683. _ref = this.subLayers;
  1684. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1685. subLayer = _ref[_i];
  1686. copiedSublayer = subLayer.copy();
  1687. copiedSublayer.superLayer = layer;
  1688. }
  1689. return layer;
  1690. };
  1691. Layer.prototype.copySingle = function() {
  1692. return new Layer(this.properties);
  1693. };
  1694. Layer.prototype.animate = function(options) {
  1695. var animation;
  1696. options.layer = this;
  1697. options.curveOptions = options;
  1698. animation = new Animation(options);
  1699. animation.start();
  1700. return animation;
  1701. };
  1702. Layer.define("image", {
  1703. exportable: true,
  1704. "default": "",
  1705. get: function() {
  1706. return this._getPropertyValue("image");
  1707. },
  1708. set: function(value) {
  1709. var currentValue, imageUrl, loader, _ref, _ref1,
  1710. _this = this;
  1711. currentValue = this._getPropertyValue("image");
  1712. if (currentValue === value) {
  1713. return this.emit("load");
  1714. }
  1715. this.backgroundColor = null;
  1716. this._setPropertyValue("image", value);
  1717. imageUrl = value;
  1718. if (Utils.isLocal() && !imageUrl.match(/^https?:\/\//)) {
  1719. imageUrl += "?nocache=" + (Date.now());
  1720. }
  1721. if ((_ref = this.events) != null ? _ref.hasOwnProperty("load" || ((_ref1 = this.events) != null ? _ref1.hasOwnProperty("error") : void 0)) : void 0) {
  1722. loader = new Image();
  1723. loader.name = imageUrl;
  1724. loader.src = imageUrl;
  1725. loader.onload = function() {
  1726. _this.style["background-image"] = "url('" + imageUrl + "')";
  1727. return _this.emit("load", loader);
  1728. };
  1729. return loader.onerror = function() {
  1730. return _this.emit("error", loader);
  1731. };
  1732. } else {
  1733. return this.style["background-image"] = "url('" + imageUrl + "')";
  1734. }
  1735. }
  1736. });
  1737. Layer.define("superLayer", {
  1738. exportable: false,
  1739. get: function() {
  1740. return this._superLayer || null;
  1741. },
  1742. set: function(layer) {
  1743. if (layer === this._superLayer) {
  1744. return;
  1745. }
  1746. if (!layer instanceof Layer) {
  1747. throw Error("Layer.superLayer needs to be a Layer object");
  1748. }
  1749. Utils.domCompleteCancel(this.__insertElement);
  1750. if (this._superLayer) {
  1751. this._superLayer._subLayers = _.without(this._superLayer._subLayers, this);
  1752. this._superLayer._element.removeChild(this._element);
  1753. this._superLayer.emit("change:subLayers", {
  1754. added: [],
  1755. removed: [this]
  1756. });
  1757. }
  1758. if (layer) {
  1759. layer._element.appendChild(this._element);
  1760. layer._subLayers.push(this);
  1761. layer.emit("change:subLayers", {
  1762. added: [this],
  1763. removed: []
  1764. });
  1765. } else {
  1766. this._insertElement();
  1767. }
  1768. this._superLayer = layer;
  1769. this.bringToFront();
  1770. return this.emit("change:superLayer");
  1771. }
  1772. });
  1773. Layer.prototype.superLayers = function() {
  1774. var recurse, superLayers;
  1775. superLayers = [];
  1776. recurse = function(layer) {
  1777. if (!layer.superLayer) {
  1778. return;
  1779. }
  1780. superLayers.push(layer.superLayer);
  1781. return recurse(layer.superLayer);
  1782. };
  1783. recurse(this);
  1784. return superLayers;
  1785. };
  1786. Layer.define("subLayers", {
  1787. exportable: false,
  1788. get: function() {
  1789. return _.clone(this._subLayers);
  1790. }
  1791. });
  1792. Layer.define("siblingLayers", {
  1793. exportable: false,
  1794. get: function() {
  1795. var _this = this;
  1796. if (this.superLayer === null) {
  1797. return _.filter(Session._LayerList, function(layer) {
  1798. return layer !== _this && layer.superLayer === null;
  1799. });
  1800. }
  1801. return _.without(this.superLayer.subLayers, this);
  1802. }
  1803. });
  1804. Layer.prototype.addSubLayer = function(layer) {
  1805. return layer.superLayer = this;
  1806. };
  1807. Layer.prototype.removeSubLayer = function(layer) {
  1808. if (__indexOf.call(this.subLayers, layer) < 0) {
  1809. return;
  1810. }
  1811. return layer.superLayer = null;
  1812. };
  1813. Layer.prototype.subLayersByName = function(name) {
  1814. return _.filter(this.subLayers, function(layer) {
  1815. return layer.name === name;
  1816. });
  1817. };
  1818. Layer.prototype.animate = function(options) {
  1819. var animation, start;
  1820. start = options.start;
  1821. if (start == null) {
  1822. start = true;
  1823. }
  1824. delete options.start;
  1825. options.layer = this;
  1826. animation = new Animation(options);
  1827. if (start) {
  1828. animation.start();
  1829. }
  1830. return animation;
  1831. };
  1832. Layer.prototype.animations = function() {
  1833. var _this = this;
  1834. return _.filter(Animation.runningAnimations(), function(a) {
  1835. return a.options.layer === _this;
  1836. });
  1837. };
  1838. Layer.prototype.animateStop = function() {
  1839. return _.invoke(this.animations(), "stop");
  1840. };
  1841. Layer.prototype.bringToFront = function() {
  1842. return this.index = _.max(_.union([0], this.siblingLayers.map(function(layer) {
  1843. return layer.index;
  1844. }))) + 1;
  1845. };
  1846. Layer.prototype.sendToBack = function() {
  1847. return this.index = _.min(_.union([0], this.siblingLayers.map(function(layer) {
  1848. return layer.index;
  1849. }))) - 1;
  1850. };
  1851. Layer.prototype.placeBefore = function(layer) {
  1852. var l, _i, _len, _ref;
  1853. if (__indexOf.call(this.siblingLayers, layer) < 0) {
  1854. return;
  1855. }
  1856. _ref = this.siblingLayers;
  1857. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1858. l = _ref[_i];
  1859. if (l.index <= layer.index) {
  1860. l.index -= 1;
  1861. }
  1862. }
  1863. return this.index = layer.index + 1;
  1864. };
  1865. Layer.prototype.placeBehind = function(layer) {
  1866. var l, _i, _len, _ref;
  1867. if (__indexOf.call(this.siblingLayers, layer) < 0) {
  1868. return;
  1869. }
  1870. _ref = this.siblingLayers;
  1871. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1872. l = _ref[_i];
  1873. if (l.index >= layer.index) {
  1874. l.index += 1;
  1875. }
  1876. }
  1877. return this.index = layer.index - 1;
  1878. };
  1879. Layer.define("states", {
  1880. get: function() {
  1881. return this._states != null ? this._states : this._states = new LayerStates(this);
  1882. }
  1883. });
  1884. Layer.define("draggable", {
  1885. get: function() {
  1886. if (this._draggable == null) {
  1887. this._draggable = new LayerDraggable(this);
  1888. }
  1889. return this._draggable;
  1890. }
  1891. });
  1892. Layer.define("scrollFrame", {
  1893. get: function() {
  1894. return new Frame({
  1895. x: this.scrollX,
  1896. y: this.scrollY,
  1897. width: this.width,
  1898. height: this.height
  1899. });
  1900. },
  1901. set: function(frame) {
  1902. this.scrollX = frame.x;
  1903. return this.scrollY = frame.y;
  1904. }
  1905. });
  1906. Layer.define("scrollX", {
  1907. get: function() {
  1908. return this._element.scrollLeft;
  1909. },
  1910. set: function(value) {
  1911. return this._element.scrollLeft = value;
  1912. }
  1913. });
  1914. Layer.define("scrollY", {
  1915. get: function() {
  1916. return this._element.scrollTop;
  1917. },
  1918. set: function(value) {
  1919. return this._element.scrollTop = value;
  1920. }
  1921. });
  1922. Layer.prototype.addListener = function(eventName, originalListener) {
  1923. var listener, _base,
  1924. _this = this;
  1925. listener = function() {
  1926. var args;
  1927. args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  1928. return originalListener.call.apply(originalListener, [_this].concat(__slice.call(args), [_this]));
  1929. };
  1930. originalListener.modifiedListener = listener;
  1931. Layer.__super__.addListener.call(this, eventName, listener);
  1932. this._element.addEventListener(eventName, listener);
  1933. if (this._eventListeners == null) {
  1934. this._eventListeners = {};
  1935. }
  1936. if ((_base = this._eventListeners)[eventName] == null) {
  1937. _base[eventName] = [];
  1938. }
  1939. this._eventListeners[eventName].push(listener);
  1940. if (!_.startsWith(eventName, "change:")) {
  1941. return this.ignoreEvents = false;
  1942. }
  1943. };
  1944. Layer.prototype.removeListener = function(eventName, listener) {
  1945. if (listener.modifiedListener) {
  1946. listener = listener.modifiedListener;
  1947. }
  1948. Layer.__super__.removeListener.call(this, eventName, listener);
  1949. this._element.removeEventListener(eventName, listener);
  1950. if (this._eventListeners) {
  1951. return this._eventListeners[eventName] = _.without(this._eventListeners[eventName], listener);
  1952. }
  1953. };
  1954. Layer.prototype.removeAllListeners = function() {
  1955. var eventName, listener, listeners, _ref, _results;
  1956. if (!this._eventListeners) {
  1957. return;
  1958. }
  1959. _ref = this._eventListeners;
  1960. _results = [];
  1961. for (eventName in _ref) {
  1962. listeners = _ref[eventName];
  1963. _results.push((function() {
  1964. var _i, _len, _results1;
  1965. _results1 = [];
  1966. for (_i = 0, _len = listeners.length; _i < _len; _i++) {
  1967. listener = listeners[_i];
  1968. _results1.push(this.removeListener(eventName, listener));
  1969. }
  1970. return _results1;
  1971. }).call(this));
  1972. }
  1973. return _results;
  1974. };
  1975. Layer.prototype.on = Layer.prototype.addListener;
  1976. Layer.prototype.off = Layer.prototype.removeListener;
  1977. return Layer;
  1978. })(BaseClass);
  1979. exports.Layer.Layers = function() {
  1980. return _.clone(Session._LayerList);
  1981. };
  1982. },{"./Animation":1,"./BaseClass":9,"./Config":11,"./Defaults":13,"./EventEmitter":14,"./Frame":18,"./LayerDraggable":22,"./LayerStates":23,"./LayerStyle":24,"./Session":27,"./Underscore":28,"./Utils":29}],22:[function(require,module,exports){
  1983. var EventEmitter, Events, Utils, _,
  1984. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  1985. __hasProp = {}.hasOwnProperty,
  1986. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  1987. _ = require("./Underscore")._;
  1988. Utils = require("./Utils");
  1989. EventEmitter = require("./EventEmitter").EventEmitter;
  1990. Events = require("./Events").Events;
  1991. Events.DragStart = "dragstart";
  1992. Events.DragMove = "dragmove";
  1993. Events.DragEnd = "dragend";
  1994. "This takes any layer and makes it draggable by the user on mobile or desktop.\n\nSome interesting things are:\n\n- The draggable.calculateVelocity().x|y contains the current average speed \n in the last 100ms (defined with VelocityTimeOut).\n- You can enable/disable or slowdown/speedup scrolling with\n draggable.speed.x|y\n";
  1995. exports.LayerDraggable = (function(_super) {
  1996. __extends(LayerDraggable, _super);
  1997. LayerDraggable.VelocityTimeOut = 100;
  1998. function LayerDraggable(layer) {
  1999. this.layer = layer;
  2000. this._touchEnd = __bind(this._touchEnd, this);
  2001. this._touchStart = __bind(this._touchStart, this);
  2002. this._updatePosition = __bind(this._updatePosition, this);
  2003. this._deltas = [];
  2004. this._isDragging = false;
  2005. this.enabled = true;
  2006. this.speedX = 1.0;
  2007. this.speedY = 1.0;
  2008. this.maxDragFrame = null;
  2009. this.attach();
  2010. }
  2011. LayerDraggable.prototype.attach = function() {
  2012. return this.layer.on(Events.TouchStart, this._touchStart);
  2013. };
  2014. LayerDraggable.prototype.remove = function() {
  2015. return this.layer.off(Events.TouchStart, this._touchStart);
  2016. };
  2017. LayerDraggable.prototype.emit = function(eventName, event) {
  2018. this.layer.emit(eventName, event);
  2019. return LayerDraggable.__super__.emit.call(this, eventName, event);
  2020. };
  2021. LayerDraggable.prototype.calculateVelocity = function() {
  2022. var curr, prev, time, timeSinceLastMove, velocity;
  2023. if (this._deltas.length < 2) {
  2024. return {
  2025. x: 0,
  2026. y: 0
  2027. };
  2028. }
  2029. curr = this._deltas.slice(-1)[0];
  2030. prev = this._deltas.slice(-2, -1)[0];
  2031. time = curr.t - prev.t;
  2032. timeSinceLastMove = new Date().getTime() - prev.t;
  2033. if (timeSinceLastMove > this.VelocityTimeOut) {
  2034. return {
  2035. x: 0,
  2036. y: 0
  2037. };
  2038. }
  2039. velocity = {
  2040. x: (curr.x - prev.x) / time,
  2041. y: (curr.y - prev.y) / time
  2042. };
  2043. if (velocity.x === Infinity) {
  2044. velocity.x = 0;
  2045. }
  2046. if (velocity.y === Infinity) {
  2047. velocity.y = 0;
  2048. }
  2049. return velocity;
  2050. };
  2051. LayerDraggable.prototype._updatePosition = function(event) {
  2052. var correctedDelta, delta, maxDragFrame, maxX, maxY, minX, minY, newX, newY, touchEvent,
  2053. _this = this;
  2054. if (this.enabled === false) {
  2055. return;
  2056. }
  2057. this.emit(Events.DragMove, event);
  2058. touchEvent = Events.touchEvent(event);
  2059. delta = {
  2060. x: touchEvent.clientX - this._start.x,
  2061. y: touchEvent.clientY - this._start.y
  2062. };
  2063. correctedDelta = {
  2064. x: delta.x * this.speedX,
  2065. y: delta.y * this.speedY,
  2066. t: event.timeStamp
  2067. };
  2068. newX = this._start.x + correctedDelta.x - this._offset.x;
  2069. newY = this._start.y + correctedDelta.y - this._offset.y;
  2070. if (this.maxDragFrame) {
  2071. maxDragFrame = this.maxDragFrame;
  2072. if (_.isFunction(maxDragFrame)) {
  2073. maxDragFrame = maxDragFrame();
  2074. }
  2075. minX = Utils.frameGetMinX(this.maxDragFrame);
  2076. maxX = Utils.frameGetMaxX(this.maxDragFrame) - this.layer.width;
  2077. minY = Utils.frameGetMinY(this.maxDragFrame);
  2078. maxY = Utils.frameGetMaxY(this.maxDragFrame) - this.layer.height;
  2079. if (newX < minX) {
  2080. newX = minX;
  2081. }
  2082. if (newX > maxX) {
  2083. newX = maxX;
  2084. }
  2085. if (newY < minY) {
  2086. newY = minY;
  2087. }
  2088. if (newY > maxY) {
  2089. newY = maxY;
  2090. }
  2091. }
  2092. window.requestAnimationFrame(function() {
  2093. _this.layer.x = newX;
  2094. return _this.layer.y = newY;
  2095. });
  2096. this._deltas.push(correctedDelta);
  2097. return this.emit(Events.DragMove, event);
  2098. };
  2099. LayerDraggable.prototype._touchStart = function(event) {
  2100. var touchEvent;
  2101. this.layer.animateStop();
  2102. this._isDragging = true;
  2103. touchEvent = Events.touchEvent(event);
  2104. this._start = {
  2105. x: touchEvent.clientX,
  2106. y: touchEvent.clientY
  2107. };
  2108. this._offset = {
  2109. x: touchEvent.clientX - this.layer.x,
  2110. y: touchEvent.clientY - this.layer.y
  2111. };
  2112. document.addEventListener(Events.TouchMove, this._updatePosition);
  2113. document.addEventListener(Events.TouchEnd, this._touchEnd);
  2114. return this.emit(Events.DragStart, event);
  2115. };
  2116. LayerDraggable.prototype._touchEnd = function(event) {
  2117. this._isDragging = false;
  2118. document.removeEventListener(Events.TouchMove, this._updatePosition);
  2119. document.removeEventListener(Events.TouchEnd, this._touchEnd);
  2120. this.emit(Events.DragEnd, event);
  2121. return this._deltas = [];
  2122. };
  2123. return LayerDraggable;
  2124. })(EventEmitter);
  2125. },{"./EventEmitter":14,"./Events":15,"./Underscore":28,"./Utils":29}],23:[function(require,module,exports){
  2126. var BaseClass, Defaults, Events, LayerStatesIgnoredKeys, _,
  2127. __hasProp = {}.hasOwnProperty,
  2128. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  2129. __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
  2130. _ = require("./Underscore")._;
  2131. Events = require("./Events").Events;
  2132. BaseClass = require("./BaseClass").BaseClass;
  2133. Defaults = require("./Defaults").Defaults;
  2134. LayerStatesIgnoredKeys = ["ignoreEvents"];
  2135. Events.StateWillSwitch = "willSwitch";
  2136. Events.StateDidSwitch = "didSwitch";
  2137. exports.LayerStates = (function(_super) {
  2138. __extends(LayerStates, _super);
  2139. function LayerStates(layer) {
  2140. this.layer = layer;
  2141. this._states = {};
  2142. this._orderedStates = [];
  2143. this.animationOptions = {};
  2144. this.add("default", this.layer.properties);
  2145. this._currentState = "default";
  2146. this._previousStates = [];
  2147. LayerStates.__super__.constructor.apply(this, arguments);
  2148. }
  2149. LayerStates.prototype.add = function(stateName, properties) {
  2150. var error, k, v;
  2151. if (_.isObject(stateName)) {
  2152. for (k in stateName) {
  2153. v = stateName[k];
  2154. this.add(k, v);
  2155. }
  2156. return;
  2157. }
  2158. error = function() {
  2159. throw Error("Usage example: layer.states.add(\"someName\", {x:500})");
  2160. };
  2161. if (!_.isString(stateName)) {
  2162. error();
  2163. }
  2164. if (!_.isObject(properties)) {
  2165. error();
  2166. }
  2167. this._orderedStates.push(stateName);
  2168. return this._states[stateName] = properties;
  2169. };
  2170. LayerStates.prototype.remove = function(stateName) {
  2171. if (!this._states.hasOwnProperty(stateName)) {
  2172. return;
  2173. }
  2174. delete this._states[stateName];
  2175. return this._orderedStates = _.without(this._orderedStates, stateName);
  2176. };
  2177. LayerStates.prototype["switch"] = function(stateName, animationOptions, instant) {
  2178. var animatingKeys, properties, propertyName, value, _ref,
  2179. _this = this;
  2180. if (instant == null) {
  2181. instant = false;
  2182. }
  2183. if (!this._states.hasOwnProperty(stateName)) {
  2184. throw Error("No such state: '" + stateName + "'");
  2185. }
  2186. this.emit(Events.StateWillSwitch, this._currentState, stateName, this);
  2187. this._previousStates.push(this._currentState);
  2188. this._currentState = stateName;
  2189. properties = {};
  2190. animatingKeys = this.animatingKeys();
  2191. _ref = this._states[stateName];
  2192. for (propertyName in _ref) {
  2193. value = _ref[propertyName];
  2194. if (__indexOf.call(LayerStatesIgnoredKeys, propertyName) >= 0) {
  2195. continue;
  2196. }
  2197. if (__indexOf.call(animatingKeys, propertyName) < 0) {
  2198. continue;
  2199. }
  2200. if (_.isFunction(value)) {
  2201. value = value.call(this.layer, this.layer, stateName);
  2202. }
  2203. properties[propertyName] = value;
  2204. }
  2205. if (instant === true) {
  2206. this.layer.properties = properties;
  2207. return this.emit(Events.StateDidSwitch, _.last(this._previousStates), stateName, this);
  2208. } else {
  2209. if (animationOptions == null) {
  2210. animationOptions = this.animationOptions;
  2211. }
  2212. animationOptions.properties = properties;
  2213. this._animation = this.layer.animate(animationOptions);
  2214. return this._animation.on("stop", function() {
  2215. return _this.emit(Events.StateDidSwitch, _.last(_this._previousStates), stateName, _this);
  2216. });
  2217. }
  2218. };
  2219. LayerStates.prototype.switchInstant = function(stateName) {
  2220. return this["switch"](stateName, null, true);
  2221. };
  2222. LayerStates.define("state", {
  2223. get: function() {
  2224. return this._currentState;
  2225. }
  2226. });
  2227. LayerStates.define("current", {
  2228. get: function() {
  2229. return this._currentState;
  2230. }
  2231. });
  2232. LayerStates.prototype.states = function() {
  2233. return _.clone(this._orderedStates);
  2234. };
  2235. LayerStates.prototype.animatingKeys = function() {
  2236. var keys, state, stateName, _ref;
  2237. keys = [];
  2238. _ref = this._states;
  2239. for (stateName in _ref) {
  2240. state = _ref[stateName];
  2241. if (stateName === "default") {
  2242. continue;
  2243. }
  2244. keys = _.union(keys, _.keys(state));
  2245. }
  2246. return keys;
  2247. };
  2248. LayerStates.prototype.previous = function(states, animationOptions) {
  2249. if (states == null) {
  2250. states = this.states();
  2251. }
  2252. return this["switch"](Utils.arrayPrev(states, this._currentState), animationOptions);
  2253. };
  2254. LayerStates.prototype.next = function() {
  2255. var states;
  2256. states = Utils.arrayFromArguments(arguments);
  2257. if (!states.length) {
  2258. states = this.states();
  2259. }
  2260. return this["switch"](Utils.arrayNext(states, this._currentState));
  2261. };
  2262. LayerStates.prototype.last = function(animationOptions) {
  2263. return this["switch"](_.last(this._previousStates), animationOptions);
  2264. };
  2265. return LayerStates;
  2266. })(BaseClass);
  2267. },{"./BaseClass":9,"./Defaults":13,"./Events":15,"./Underscore":28}],24:[function(require,module,exports){
  2268. var filterFormat, _WebkitProperties;
  2269. filterFormat = function(value, unit) {
  2270. return "" + (Utils.round(value, 2)) + unit;
  2271. };
  2272. _WebkitProperties = [["blur", "blur", 0, "px"], ["brightness", "brightness", 100, "%"], ["saturate", "saturate", 100, "%"], ["hue-rotate", "hueRotate", 0, "deg"], ["contrast", "contrast", 100, "%"], ["invert", "invert", 0, "%"], ["grayscale", "grayscale", 0, "%"], ["sepia", "sepia", 0, "%"]];
  2273. exports.LayerStyle = {
  2274. width: function(layer) {
  2275. return layer.width + "px";
  2276. },
  2277. height: function(layer) {
  2278. return layer.height + "px";
  2279. },
  2280. display: function(layer) {
  2281. if (layer.visible === true) {
  2282. return "block";
  2283. }
  2284. return "none";
  2285. },
  2286. opacity: function(layer) {
  2287. return layer.opacity;
  2288. },
  2289. overflow: function(layer) {
  2290. if (layer.scrollHorizontal === true || layer.scrollVertical === true) {
  2291. return "auto";
  2292. }
  2293. if (layer.clip === true) {
  2294. return "hidden";
  2295. }
  2296. return "visible";
  2297. },
  2298. overflowX: function(layer) {
  2299. if (layer.scrollHorizontal === true) {
  2300. return "scroll";
  2301. }
  2302. if (layer.clip === true) {
  2303. return "hidden";
  2304. }
  2305. return "visible";
  2306. },
  2307. overflowY: function(layer) {
  2308. if (layer.scrollVertical === true) {
  2309. return "scroll";
  2310. }
  2311. if (layer.clip === true) {
  2312. return "hidden";
  2313. }
  2314. return "visible";
  2315. },
  2316. zIndex: function(layer) {
  2317. return layer.index;
  2318. },
  2319. webkitFilter: function(layer) {
  2320. var css, cssName, fallback, layerName, unit, _i, _len, _ref;
  2321. css = [];
  2322. for (_i = 0, _len = _WebkitProperties.length; _i < _len; _i++) {
  2323. _ref = _WebkitProperties[_i], cssName = _ref[0], layerName = _ref[1], fallback = _ref[2], unit = _ref[3];
  2324. if (layer[layerName] !== fallback) {
  2325. css.push("" + cssName + "(" + (filterFormat(layer[layerName], unit)) + ")");
  2326. }
  2327. }
  2328. return css.join(" ");
  2329. },
  2330. webkitTransform: function(layer) {
  2331. if (layer._prefer2d) {
  2332. return exports.LayerStyle.webkitTransformPrefer2d(layer);
  2333. }
  2334. return " translate3d(" + layer.x + "px," + layer.y + "px," + layer.z + "px) scale(" + layer.scale + ") scale3d(" + layer.scaleX + "," + layer.scaleY + "," + layer.scaleZ + ") skew(" + layer.skew + "deg," + layer.skew + "deg) skewX(" + layer.skewX + "deg) skewY(" + layer.skewY + "deg) rotateX(" + layer.rotationX + "deg) rotateY(" + layer.rotationY + "deg) rotateZ(" + layer.rotationZ + "deg) ";
  2335. },
  2336. webkitTransformPrefer2d: function(layer) {
  2337. var css;
  2338. css = [];
  2339. if (layer.z !== 0) {
  2340. css.push("translate3d(" + layer.x + "px," + layer.y + "px," + layer.z + "px)");
  2341. } else {
  2342. css.push("translate(" + layer.x + "px," + layer.y + "px)");
  2343. }
  2344. if (layer.scale !== 1) {
  2345. css.push("scale(" + layer.scale + ")");
  2346. }
  2347. if (layer.scaleX !== 1 || layer.scaleY !== 1 || layer.scaleZ !== 1) {
  2348. css.push("scale3d(" + layer.scaleX + "," + layer.scaleY + "," + layer.scaleZ + ")");
  2349. }
  2350. if (layer.skew) {
  2351. css.push("skew(" + layer.skew + "deg," + layer.skew + "deg)");
  2352. }
  2353. if (layer.skewX) {
  2354. css.push("skewX(" + layer.skewX + "deg)");
  2355. }
  2356. if (layer.skewY) {
  2357. css.push("skewY(" + layer.skewY + "deg)");
  2358. }
  2359. if (layer.rotationX) {
  2360. css.push("rotateX(" + layer.rotationX + "deg)");
  2361. }
  2362. if (layer.rotationY) {
  2363. css.push("rotateY(" + layer.rotationY + "deg)");
  2364. }
  2365. if (layer.rotationZ) {
  2366. css.push("rotateZ(" + layer.rotationZ + "deg)");
  2367. }
  2368. return css.join(" ");
  2369. },
  2370. webkitTransformOrigin: function(layer) {
  2371. return "" + (layer.originX * 100) + "% " + (layer.originY * 100) + "%";
  2372. },
  2373. pointerEvents: function(layer) {
  2374. if (layer.ignoreEvents) {
  2375. return "none";
  2376. } else {
  2377. return "auto";
  2378. }
  2379. },
  2380. boxShadow: function(layer) {
  2381. if (!layer.shadowColor) {
  2382. return "";
  2383. }
  2384. return "" + layer.shadowX + "px " + layer.shadowY + "px " + layer.shadowBlur + "px " + layer.shadowSpread + "px " + layer.shadowColor;
  2385. }
  2386. };
  2387. },{}],25:[function(require,module,exports){
  2388. var Session, Utils,
  2389. __slice = [].slice;
  2390. Utils = require("./Utils");
  2391. Session = require("./Session").Session;
  2392. "\nTodo:\n- Better looks\n- Resizable\n- Live in own space on top of all Framer stuff\n";
  2393. exports.print = function() {
  2394. var args, printLayer, printNode;
  2395. args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  2396. printLayer = Framer.Session.printLayer;
  2397. if (!printLayer) {
  2398. printLayer = new Layer;
  2399. printLayer.scrollVertical = true;
  2400. printLayer.ignoreEvents = false;
  2401. printLayer.html = "";
  2402. printLayer.style = {
  2403. "font": "12px/1.35em Menlo",
  2404. "color": "rgba(0,0,0,.7)",
  2405. "padding": "8px",
  2406. "padding-bottom": "30px",
  2407. "border-top": "1px solid #d9d9d9"
  2408. };
  2409. printLayer.opacity = 0.9;
  2410. printLayer.style.zIndex = 999;
  2411. printLayer.visible = true;
  2412. printLayer.backgroundColor = "white";
  2413. printLayer.width = window.innerWidth;
  2414. printLayer.height = 160;
  2415. printLayer.maxY = window.innerHeight;
  2416. }
  2417. printNode = document.createElement("div");
  2418. printNode.innerHTML = "&raquo; " + args.map(Utils.stringify).join(", ") + "<br>";
  2419. printNode.style["-webkit-user-select"] = "text";
  2420. printNode.style["cursor"] = "auto";
  2421. printLayer._element.appendChild(printNode);
  2422. Framer.Session.printLayer = printLayer;
  2423. return Utils.delay(0, function() {
  2424. return printLayer._element.scrollTop = printLayer._element.scrollHeight;
  2425. });
  2426. };
  2427. },{"./Session":27,"./Utils":29}],26:[function(require,module,exports){
  2428. var BaseClass, ScreenClass,
  2429. __hasProp = {}.hasOwnProperty,
  2430. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  2431. BaseClass = require("./BaseClass").BaseClass;
  2432. ScreenClass = (function(_super) {
  2433. __extends(ScreenClass, _super);
  2434. function ScreenClass(options) {
  2435. ScreenClass.__super__.constructor.call(this, options);
  2436. this._setupResizeListener();
  2437. }
  2438. ScreenClass.define("width", {
  2439. get: function() {
  2440. return window.innerWidth;
  2441. }
  2442. });
  2443. ScreenClass.define("height", {
  2444. get: function() {
  2445. return window.innerHeight;
  2446. }
  2447. });
  2448. ScreenClass.prototype._setupResizeListener = function() {
  2449. var oldResizeFunction,
  2450. _this = this;
  2451. oldResizeFunction = window.onresize;
  2452. return window.onresize = function() {
  2453. _this.emit("resize", _this);
  2454. return typeof oldResizeFunction === "function" ? oldResizeFunction() : void 0;
  2455. };
  2456. };
  2457. return ScreenClass;
  2458. })(BaseClass);
  2459. exports.Screen = new ScreenClass;
  2460. },{"./BaseClass":9}],27:[function(require,module,exports){
  2461. exports.Session = {};
  2462. },{}],28:[function(require,module,exports){
  2463. var _;
  2464. _ = require("lodash");
  2465. _.str = require('underscore.string');
  2466. _.mixin(_.str.exports());
  2467. _.isBool = function(v) {
  2468. return typeof v === 'boolean';
  2469. };
  2470. exports._ = _;
  2471. },{"lodash":31,"underscore.string":32}],29:[function(require,module,exports){
  2472. var Screen, Session, Utils, _, __domComplete, __domReady,
  2473. __slice = [].slice,
  2474. _this = this;
  2475. _ = require("./Underscore")._;
  2476. Session = require("./Session").Session;
  2477. Screen = require("./Screen").Screen;
  2478. Utils = {};
  2479. Utils.reset = function() {
  2480. var delayInterval, delayTimer, layer, __domComplete, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _ref3;
  2481. if (__domReady === false) {
  2482. return;
  2483. }
  2484. __domComplete = [];
  2485. Session.printLayer = null;
  2486. if (Session._LayerList) {
  2487. _ref = Session._LayerList;
  2488. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  2489. layer = _ref[_i];
  2490. layer.removeAllListeners();
  2491. }
  2492. }
  2493. Session._LayerList = [];
  2494. if ((_ref1 = Session._RootElement) != null) {
  2495. _ref1.innerHTML = "";
  2496. }
  2497. if (Session._delayTimers) {
  2498. _ref2 = Session._delayTimers;
  2499. for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
  2500. delayTimer = _ref2[_j];
  2501. clearTimeout(delayTimer);
  2502. }
  2503. Session._delayTimers = [];
  2504. }
  2505. if (Session._delayIntervals) {
  2506. _ref3 = Session._delayIntervals;
  2507. for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) {
  2508. delayInterval = _ref3[_k];
  2509. clearInterval(delayInterval);
  2510. }
  2511. return Session._delayIntervals = [];
  2512. }
  2513. };
  2514. Utils.getValue = function(value) {
  2515. if (_.isFunction(value)) {
  2516. return value();
  2517. }
  2518. return value;
  2519. };
  2520. Utils.setDefaultProperties = function(obj, defaults, warn) {
  2521. var k, result, v;
  2522. if (warn == null) {
  2523. warn = true;
  2524. }
  2525. result = {};
  2526. for (k in defaults) {
  2527. v = defaults[k];
  2528. if (obj.hasOwnProperty(k)) {
  2529. result[k] = obj[k];
  2530. } else {
  2531. result[k] = defaults[k];
  2532. }
  2533. }
  2534. if (warn) {
  2535. for (k in obj) {
  2536. v = obj[k];
  2537. if (!defaults.hasOwnProperty(k)) {
  2538. console.warn("Utils.setDefaultProperties: got unexpected option: '" + k + " -> " + v + "'", obj);
  2539. }
  2540. }
  2541. }
  2542. return result;
  2543. };
  2544. Utils.valueOrDefault = function(value, defaultValue) {
  2545. if (value === (void 0) || value === null) {
  2546. value = defaultValue;
  2547. }
  2548. return value;
  2549. };
  2550. Utils.arrayToObject = function(arr) {
  2551. var item, obj, _i, _len;
  2552. obj = {};
  2553. for (_i = 0, _len = arr.length; _i < _len; _i++) {
  2554. item = arr[_i];
  2555. obj[item[0]] = item[1];
  2556. }
  2557. return obj;
  2558. };
  2559. Utils.arrayNext = function(arr, item) {
  2560. return arr[arr.indexOf(item) + 1] || _.first(arr);
  2561. };
  2562. Utils.arrayPrev = function(arr, item) {
  2563. return arr[arr.indexOf(item) - 1] || _.last(arr);
  2564. };
  2565. if (window.requestAnimationFrame == null) {
  2566. window.requestAnimationFrame = window.webkitRequestAnimationFrame;
  2567. }
  2568. if (window.requestAnimationFrame == null) {
  2569. window.requestAnimationFrame = function(f) {
  2570. return Utils.delay(1 / 60, f);
  2571. };
  2572. }
  2573. Utils.getTime = function() {
  2574. return Date.now() / 1000;
  2575. };
  2576. Utils.delay = function(time, f) {
  2577. var timer;
  2578. timer = setTimeout(f, time * 1000);
  2579. if (Session._delayTimers == null) {
  2580. Session._delayTimers = [];
  2581. }
  2582. Session._delayTimers.push(timer);
  2583. return timer;
  2584. };
  2585. Utils.interval = function(time, f) {
  2586. var timer;
  2587. timer = setInterval(f, time * 1000);
  2588. if (Session._delayIntervals == null) {
  2589. Session._delayIntervals = [];
  2590. }
  2591. Session._delayIntervals.push(timer);
  2592. return timer;
  2593. };
  2594. Utils.debounce = function(threshold, fn, immediate) {
  2595. var timeout;
  2596. if (threshold == null) {
  2597. threshold = 0.1;
  2598. }
  2599. timeout = null;
  2600. threshold *= 1000;
  2601. return function() {
  2602. var args, delayed, obj;
  2603. args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  2604. obj = this;
  2605. delayed = function() {
  2606. if (!immediate) {
  2607. fn.apply(obj, args);
  2608. }
  2609. return timeout = null;
  2610. };
  2611. if (timeout) {
  2612. clearTimeout(timeout);
  2613. } else if (immediate) {
  2614. fn.apply(obj, args);
  2615. }
  2616. return timeout = setTimeout(delayed, threshold);
  2617. };
  2618. };
  2619. Utils.throttle = function(delay, fn) {
  2620. var timer;
  2621. if (delay === 0) {
  2622. return fn;
  2623. }
  2624. delay *= 1000;
  2625. timer = false;
  2626. return function() {
  2627. if (timer) {
  2628. return;
  2629. }
  2630. timer = true;
  2631. if (delay !== -1) {
  2632. setTimeout((function() {
  2633. return timer = false;
  2634. }), delay);
  2635. }
  2636. return fn.apply(null, arguments);
  2637. };
  2638. };
  2639. Utils.randomColor = function(alpha) {
  2640. var c;
  2641. if (alpha == null) {
  2642. alpha = 1.0;
  2643. }
  2644. c = function() {
  2645. return parseInt(Math.random() * 255);
  2646. };
  2647. return "rgba(" + (c()) + ", " + (c()) + ", " + (c()) + ", " + alpha + ")";
  2648. };
  2649. Utils.randomChoice = function(arr) {
  2650. return arr[Math.floor(Math.random() * arr.length)];
  2651. };
  2652. Utils.randomNumber = function(a, b) {
  2653. if (a == null) {
  2654. a = 0;
  2655. }
  2656. if (b == null) {
  2657. b = 1;
  2658. }
  2659. return Utils.mapRange(Math.random(), 0, 1, a, b);
  2660. };
  2661. Utils.labelLayer = function(layer, text, style) {
  2662. if (style == null) {
  2663. style = {};
  2664. }
  2665. style = _.extend({
  2666. font: "10px/1em Menlo",
  2667. lineHeight: "" + layer.height + "px",
  2668. textAlign: "center",
  2669. color: "#fff"
  2670. }, style);
  2671. layer.style = style;
  2672. return layer.html = text;
  2673. };
  2674. Utils.stringify = function(obj) {
  2675. try {
  2676. if (_.isObject(obj)) {
  2677. return JSON.stringify(obj);
  2678. }
  2679. } catch (_error) {
  2680. "";
  2681. }
  2682. if (obj === void 0) {
  2683. return "undefined";
  2684. }
  2685. if (obj.toString) {
  2686. return obj.toString();
  2687. }
  2688. return obj;
  2689. };
  2690. Utils.uuid = function() {
  2691. var chars, digit, output, r, random, _i;
  2692. chars = "0123456789abcdefghijklmnopqrstuvwxyz".split("");
  2693. output = new Array(36);
  2694. random = 0;
  2695. for (digit = _i = 1; _i <= 32; digit = ++_i) {
  2696. if (random <= 0x02) {
  2697. random = 0x2000000 + (Math.random() * 0x1000000) | 0;
  2698. }
  2699. r = random & 0xf;
  2700. random = random >> 4;
  2701. output[digit] = chars[digit === 19 ? (r & 0x3) | 0x8 : r];
  2702. }
  2703. return output.join("");
  2704. };
  2705. Utils.arrayFromArguments = function(args) {
  2706. if (_.isArray(args[0])) {
  2707. return args[0];
  2708. }
  2709. return Array.prototype.slice.call(args);
  2710. };
  2711. Utils.cycle = function() {
  2712. var args, curr;
  2713. args = Utils.arrayFromArguments(arguments);
  2714. curr = -1;
  2715. return function() {
  2716. curr++;
  2717. if (curr >= args.length) {
  2718. curr = 0;
  2719. }
  2720. return args[curr];
  2721. };
  2722. };
  2723. Utils.toggle = Utils.cycle;
  2724. Utils.isWebKit = function() {
  2725. return window.WebKitCSSMatrix !== null;
  2726. };
  2727. Utils.isTouch = function() {
  2728. return window.ontouchstart === null;
  2729. };
  2730. Utils.isMobile = function() {
  2731. return /iphone|ipod|ipad|android|ie|blackberry|fennec/.test(navigator.userAgent.toLowerCase());
  2732. };
  2733. Utils.isChrome = function() {
  2734. return /chrome/.test(navigator.userAgent.toLowerCase());
  2735. };
  2736. Utils.isLocal = function() {
  2737. return Utils.isLocalUrl(window.location.href);
  2738. };
  2739. Utils.isLocalUrl = function(url) {
  2740. return url.slice(0, 7) === "file://";
  2741. };
  2742. Utils.devicePixelRatio = function() {
  2743. return window.devicePixelRatio;
  2744. };
  2745. Utils.pathJoin = function() {
  2746. return Utils.arrayFromArguments(arguments).join("/");
  2747. };
  2748. Utils.round = function(value, decimals) {
  2749. var d;
  2750. d = Math.pow(10, decimals);
  2751. return Math.round(value * d) / d;
  2752. };
  2753. Utils.mapRange = function(value, fromLow, fromHigh, toLow, toHigh) {
  2754. return toLow + (((value - fromLow) / (fromHigh - fromLow)) * (toHigh - toLow));
  2755. };
  2756. Utils.modulate = function(value, rangeA, rangeB, limit) {
  2757. var fromHigh, fromLow, result, toHigh, toLow;
  2758. if (limit == null) {
  2759. limit = false;
  2760. }
  2761. fromLow = rangeA[0], fromHigh = rangeA[1];
  2762. toLow = rangeB[0], toHigh = rangeB[1];
  2763. result = toLow + (((value - fromLow) / (fromHigh - fromLow)) * (toHigh - toLow));
  2764. if (limit === true) {
  2765. if (result < toLow) {
  2766. return toLow;
  2767. }
  2768. if (result > toHigh) {
  2769. return toHigh;
  2770. }
  2771. }
  2772. return result;
  2773. };
  2774. Utils.parseFunction = function(str) {
  2775. var result;
  2776. result = {
  2777. name: "",
  2778. args: []
  2779. };
  2780. if (_.endsWith(str, ")")) {
  2781. result.name = str.split("(")[0];
  2782. result.args = str.split("(")[1].split(",").map(function(a) {
  2783. return _.trim(_.rtrim(a, ")"));
  2784. });
  2785. } else {
  2786. result.name = str;
  2787. }
  2788. return result;
  2789. };
  2790. __domComplete = [];
  2791. __domReady = false;
  2792. if (typeof document !== "undefined" && document !== null) {
  2793. document.onreadystatechange = function(event) {
  2794. var f, _results;
  2795. if (document.readyState === "complete") {
  2796. __domReady = true;
  2797. _results = [];
  2798. while (__domComplete.length) {
  2799. _results.push(f = __domComplete.shift()());
  2800. }
  2801. return _results;
  2802. }
  2803. };
  2804. }
  2805. Utils.domComplete = function(f) {
  2806. if (document.readyState === "complete") {
  2807. return f();
  2808. } else {
  2809. return __domComplete.push(f);
  2810. }
  2811. };
  2812. Utils.domCompleteCancel = function(f) {
  2813. return __domComplete = _.without(__domComplete, f);
  2814. };
  2815. Utils.domLoadScript = function(url, callback) {
  2816. var head, script;
  2817. script = document.createElement("script");
  2818. script.type = "text/javascript";
  2819. script.src = url;
  2820. script.onload = callback;
  2821. head = document.getElementsByTagName("head")[0];
  2822. head.appendChild(script);
  2823. return script;
  2824. };
  2825. Utils.domLoadData = function(path, callback) {
  2826. var request;
  2827. request = new XMLHttpRequest();
  2828. request.addEventListener("load", function() {
  2829. return callback(null, request.responseText);
  2830. }, false);
  2831. request.addEventListener("error", function() {
  2832. return callback(true, null);
  2833. }, false);
  2834. request.open("GET", path, true);
  2835. return request.send(null);
  2836. };
  2837. Utils.domLoadJSON = function(path, callback) {
  2838. return Utils.domLoadData(path, function(err, data) {
  2839. return callback(err, JSON.parse(data));
  2840. });
  2841. };
  2842. Utils.domLoadDataSync = function(path) {
  2843. var data, e, request;
  2844. request = new XMLHttpRequest();
  2845. request.open("GET", path, false);
  2846. try {
  2847. request.send(null);
  2848. } catch (_error) {
  2849. e = _error;
  2850. console.debug("XMLHttpRequest.error", e);
  2851. }
  2852. data = request.responseText;
  2853. if (!data) {
  2854. throw Error("Utils.domLoadDataSync: no data was loaded (url not found?)");
  2855. }
  2856. return request.responseText;
  2857. };
  2858. Utils.domLoadJSONSync = function(path) {
  2859. return JSON.parse(Utils.domLoadDataSync(path));
  2860. };
  2861. Utils.domLoadScriptSync = function(path) {
  2862. var scriptData;
  2863. scriptData = Utils.domLoadDataSync(path);
  2864. eval(scriptData);
  2865. return scriptData;
  2866. };
  2867. Utils.pointMin = function() {
  2868. var point, points;
  2869. points = Utils.arrayFromArguments(arguments);
  2870. return point = {
  2871. x: _.min(point.map(function(size) {
  2872. return size.x;
  2873. })),
  2874. y: _.min(point.map(function(size) {
  2875. return size.y;
  2876. }))
  2877. };
  2878. };
  2879. Utils.pointMax = function() {
  2880. var point, points;
  2881. points = Utils.arrayFromArguments(arguments);
  2882. return point = {
  2883. x: _.max(point.map(function(size) {
  2884. return size.x;
  2885. })),
  2886. y: _.max(point.map(function(size) {
  2887. return size.y;
  2888. }))
  2889. };
  2890. };
  2891. Utils.pointDistance = function(pointA, pointB) {
  2892. var distance;
  2893. return distance = {
  2894. x: Math.abs(pointB.x - pointA.x),
  2895. y: Math.abs(pointB.y - pointA.y)
  2896. };
  2897. };
  2898. Utils.pointInvert = function(point) {
  2899. return point = {
  2900. x: 0 - point.x,
  2901. y: 0 - point.y
  2902. };
  2903. };
  2904. Utils.pointTotal = function(point) {
  2905. return point.x + point.y;
  2906. };
  2907. Utils.pointAbs = function(point) {
  2908. return point = {
  2909. x: Math.abs(point.x),
  2910. y: Math.abs(point.y)
  2911. };
  2912. };
  2913. Utils.pointInFrame = function(point, frame) {
  2914. if (point.x < frame.minX || point.x > frame.maxX) {
  2915. return false;
  2916. }
  2917. if (point.y < frame.minY || point.y > frame.maxY) {
  2918. return false;
  2919. }
  2920. return true;
  2921. };
  2922. Utils.sizeMin = function() {
  2923. var size, sizes;
  2924. sizes = Utils.arrayFromArguments(arguments);
  2925. return size = {
  2926. width: _.min(sizes.map(function(size) {
  2927. return size.width;
  2928. })),
  2929. height: _.min(sizes.map(function(size) {
  2930. return size.height;
  2931. }))
  2932. };
  2933. };
  2934. Utils.sizeMax = function() {
  2935. var size, sizes;
  2936. sizes = Utils.arrayFromArguments(arguments);
  2937. return size = {
  2938. width: _.max(sizes.map(function(size) {
  2939. return size.width;
  2940. })),
  2941. height: _.max(sizes.map(function(size) {
  2942. return size.height;
  2943. }))
  2944. };
  2945. };
  2946. Utils.frameGetMinX = function(frame) {
  2947. return frame.x;
  2948. };
  2949. Utils.frameSetMinX = function(frame, value) {
  2950. return frame.x = value;
  2951. };
  2952. Utils.frameGetMidX = function(frame) {
  2953. if (frame.width === 0) {
  2954. return 0;
  2955. } else {
  2956. return frame.x + (frame.width / 2.0);
  2957. }
  2958. };
  2959. Utils.frameSetMidX = function(frame, value) {
  2960. return frame.x = frame.width === 0 ? 0 : value - (frame.width / 2.0);
  2961. };
  2962. Utils.frameGetMaxX = function(frame) {
  2963. if (frame.width === 0) {
  2964. return 0;
  2965. } else {
  2966. return frame.x + frame.width;
  2967. }
  2968. };
  2969. Utils.frameSetMaxX = function(frame, value) {
  2970. return frame.x = frame.width === 0 ? 0 : value - frame.width;
  2971. };
  2972. Utils.frameGetMinY = function(frame) {
  2973. return frame.y;
  2974. };
  2975. Utils.frameSetMinY = function(frame, value) {
  2976. return frame.y = value;
  2977. };
  2978. Utils.frameGetMidY = function(frame) {
  2979. if (frame.height === 0) {
  2980. return 0;
  2981. } else {
  2982. return frame.y + (frame.height / 2.0);
  2983. }
  2984. };
  2985. Utils.frameSetMidY = function(frame, value) {
  2986. return frame.y = frame.height === 0 ? 0 : value - (frame.height / 2.0);
  2987. };
  2988. Utils.frameGetMaxY = function(frame) {
  2989. if (frame.height === 0) {
  2990. return 0;
  2991. } else {
  2992. return frame.y + frame.height;
  2993. }
  2994. };
  2995. Utils.frameSetMaxY = function(frame, value) {
  2996. return frame.y = frame.height === 0 ? 0 : value - frame.height;
  2997. };
  2998. Utils.frameSize = function(frame) {
  2999. var size;
  3000. return size = {
  3001. width: frame.width,
  3002. height: frame.height
  3003. };
  3004. };
  3005. Utils.framePoint = function(frame) {
  3006. var point;
  3007. return point = {
  3008. x: frame.x,
  3009. y: frame.y
  3010. };
  3011. };
  3012. Utils.frameMerge = function() {
  3013. var frame, frames;
  3014. frames = Utils.arrayFromArguments(arguments);
  3015. frame = {
  3016. x: _.min(frames.map(Utils.frameGetMinX)),
  3017. y: _.min(frames.map(Utils.frameGetMinY))
  3018. };
  3019. frame.width = _.max(frames.map(Utils.frameGetMaxX)) - frame.x;
  3020. frame.height = _.max(frames.map(Utils.frameGetMaxY)) - frame.y;
  3021. return frame;
  3022. };
  3023. Utils.convertPoint = function(input, layerA, layerB) {
  3024. var k, layer, point, superLayersA, superLayersB, _i, _j, _k, _len, _len1, _len2, _ref;
  3025. point = {};
  3026. _ref = ["x", "y", "width", "height"];
  3027. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  3028. k = _ref[_i];
  3029. point[k] = input[k];
  3030. }
  3031. superLayersA = (layerA != null ? layerA.superLayers() : void 0) || [];
  3032. superLayersB = (layerB != null ? layerB.superLayers() : void 0) || [];
  3033. if (layerB) {
  3034. superLayersB.push(layerB);
  3035. }
  3036. for (_j = 0, _len1 = superLayersA.length; _j < _len1; _j++) {
  3037. layer = superLayersA[_j];
  3038. point.x += layer.x - layer.scrollFrame.x;
  3039. point.y += layer.y - layer.scrollFrame.y;
  3040. }
  3041. for (_k = 0, _len2 = superLayersB.length; _k < _len2; _k++) {
  3042. layer = superLayersB[_k];
  3043. point.x -= layer.x + layer.scrollFrame.x;
  3044. point.y -= layer.y + layer.scrollFrame.y;
  3045. }
  3046. return point;
  3047. };
  3048. _.extend(exports, Utils);
  3049. },{"./Screen":26,"./Session":27,"./Underscore":28}],30:[function(require,module,exports){
  3050. var Layer,
  3051. __hasProp = {}.hasOwnProperty,
  3052. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  3053. Layer = require("./Layer").Layer;
  3054. exports.VideoLayer = (function(_super) {
  3055. __extends(VideoLayer, _super);
  3056. function VideoLayer(options) {
  3057. if (options == null) {
  3058. options = {};
  3059. }
  3060. VideoLayer.__super__.constructor.call(this, options);
  3061. this.player = document.createElement("video");
  3062. this.player.style.width = "100%";
  3063. this.player.style.height = "100%";
  3064. this.player.on = this.player.addEventListener;
  3065. this.player.off = this.player.removeEventListener;
  3066. this.video = options.video;
  3067. this._element.appendChild(this.player);
  3068. }
  3069. VideoLayer.define("video", {
  3070. get: function() {
  3071. return this.player.src;
  3072. },
  3073. set: function(video) {
  3074. return this.player.src = video;
  3075. }
  3076. });
  3077. return VideoLayer;
  3078. })(Layer);
  3079. },{"./Layer":21}],31:[function(require,module,exports){
  3080. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
  3081. * @license
  3082. * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
  3083. * Build: `lodash modern -o ./dist/lodash.js`
  3084. * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
  3085. * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
  3086. * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  3087. * Available under MIT license <http://lodash.com/license>
  3088. */
  3089. ;(function() {
  3090. /** Used as a safe reference for `undefined` in pre ES5 environments */
  3091. var undefined;
  3092. /** Used to pool arrays and objects used internally */
  3093. var arrayPool = [],
  3094. objectPool = [];
  3095. /** Used to generate unique IDs */
  3096. var idCounter = 0;
  3097. /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
  3098. var keyPrefix = +new Date + '';
  3099. /** Used as the size when optimizations are enabled for large arrays */
  3100. var largeArraySize = 75;
  3101. /** Used as the max size of the `arrayPool` and `objectPool` */
  3102. var maxPoolSize = 40;
  3103. /** Used to detect and test whitespace */
  3104. var whitespace = (
  3105. // whitespace
  3106. ' \t\x0B\f\xA0\ufeff' +
  3107. // line terminators
  3108. '\n\r\u2028\u2029' +
  3109. // unicode category "Zs" space separators
  3110. '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
  3111. );
  3112. /** Used to match empty string literals in compiled template source */
  3113. var reEmptyStringLeading = /\b__p \+= '';/g,
  3114. reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
  3115. reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
  3116. /**
  3117. * Used to match ES6 template delimiters
  3118. * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals
  3119. */
  3120. var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
  3121. /** Used to match regexp flags from their coerced string values */
  3122. var reFlags = /\w*$/;
  3123. /** Used to detected named functions */
  3124. var reFuncName = /^\s*function[ \n\r\t]+\w/;
  3125. /** Used to match "interpolate" template delimiters */
  3126. var reInterpolate = /<%=([\s\S]+?)%>/g;
  3127. /** Used to match leading whitespace and zeros to be removed */
  3128. var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');
  3129. /** Used to ensure capturing order of template delimiters */
  3130. var reNoMatch = /($^)/;
  3131. /** Used to detect functions containing a `this` reference */
  3132. var reThis = /\bthis\b/;
  3133. /** Used to match unescaped characters in compiled string literals */
  3134. var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
  3135. /** Used to assign default `context` object properties */
  3136. var contextProps = [
  3137. 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object',
  3138. 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN',
  3139. 'parseInt', 'setTimeout'
  3140. ];
  3141. /** Used to make template sourceURLs easier to identify */
  3142. var templateCounter = 0;
  3143. /** `Object#toString` result shortcuts */
  3144. var argsClass = '[object Arguments]',
  3145. arrayClass = '[object Array]',
  3146. boolClass = '[object Boolean]',
  3147. dateClass = '[object Date]',
  3148. funcClass = '[object Function]',
  3149. numberClass = '[object Number]',
  3150. objectClass = '[object Object]',
  3151. regexpClass = '[object RegExp]',
  3152. stringClass = '[object String]';
  3153. /** Used to identify object classifications that `_.clone` supports */
  3154. var cloneableClasses = {};
  3155. cloneableClasses[funcClass] = false;
  3156. cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
  3157. cloneableClasses[boolClass] = cloneableClasses[dateClass] =
  3158. cloneableClasses[numberClass] = cloneableClasses[objectClass] =
  3159. cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;
  3160. /** Used as an internal `_.debounce` options object */
  3161. var debounceOptions = {
  3162. 'leading': false,
  3163. 'maxWait': 0,
  3164. 'trailing': false
  3165. };
  3166. /** Used as the property descriptor for `__bindData__` */
  3167. var descriptor = {
  3168. 'configurable': false,
  3169. 'enumerable': false,
  3170. 'value': null,
  3171. 'writable': false
  3172. };
  3173. /** Used to determine if values are of the language type Object */
  3174. var objectTypes = {
  3175. 'boolean': false,
  3176. 'function': true,
  3177. 'object': true,
  3178. 'number': false,
  3179. 'string': false,
  3180. 'undefined': false
  3181. };
  3182. /** Used to escape characters for inclusion in compiled string literals */
  3183. var stringEscapes = {
  3184. '\\': '\\',
  3185. "'": "'",
  3186. '\n': 'n',
  3187. '\r': 'r',
  3188. '\t': 't',
  3189. '\u2028': 'u2028',
  3190. '\u2029': 'u2029'
  3191. };
  3192. /** Used as a reference to the global object */
  3193. var root = (objectTypes[typeof window] && window) || this;
  3194. /** Detect free variable `exports` */
  3195. var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
  3196. /** Detect free variable `module` */
  3197. var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
  3198. /** Detect the popular CommonJS extension `module.exports` */
  3199. var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
  3200. /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
  3201. var freeGlobal = objectTypes[typeof global] && global;
  3202. if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
  3203. root = freeGlobal;
  3204. }
  3205. /*--------------------------------------------------------------------------*/
  3206. /**
  3207. * The base implementation of `_.indexOf` without support for binary searches
  3208. * or `fromIndex` constraints.
  3209. *
  3210. * @private
  3211. * @param {Array} array The array to search.
  3212. * @param {*} value The value to search for.
  3213. * @param {number} [fromIndex=0] The index to search from.
  3214. * @returns {number} Returns the index of the matched value or `-1`.
  3215. */
  3216. function baseIndexOf(array, value, fromIndex) {
  3217. var index = (fromIndex || 0) - 1,
  3218. length = array ? array.length : 0;
  3219. while (++index < length) {
  3220. if (array[index] === value) {
  3221. return index;
  3222. }
  3223. }
  3224. return -1;
  3225. }
  3226. /**
  3227. * An implementation of `_.contains` for cache objects that mimics the return
  3228. * signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
  3229. *
  3230. * @private
  3231. * @param {Object} cache The cache object to inspect.
  3232. * @param {*} value The value to search for.
  3233. * @returns {number} Returns `0` if `value` is found, else `-1`.
  3234. */
  3235. function cacheIndexOf(cache, value) {
  3236. var type = typeof value;
  3237. cache = cache.cache;
  3238. if (type == 'boolean' || value == null) {
  3239. return cache[value] ? 0 : -1;
  3240. }
  3241. if (type != 'number' && type != 'string') {
  3242. type = 'object';
  3243. }
  3244. var key = type == 'number' ? value : keyPrefix + value;
  3245. cache = (cache = cache[type]) && cache[key];
  3246. return type == 'object'
  3247. ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
  3248. : (cache ? 0 : -1);
  3249. }
  3250. /**
  3251. * Adds a given value to the corresponding cache object.
  3252. *
  3253. * @private
  3254. * @param {*} value The value to add to the cache.
  3255. */
  3256. function cachePush(value) {
  3257. var cache = this.cache,
  3258. type = typeof value;
  3259. if (type == 'boolean' || value == null) {
  3260. cache[value] = true;
  3261. } else {
  3262. if (type != 'number' && type != 'string') {
  3263. type = 'object';
  3264. }
  3265. var key = type == 'number' ? value : keyPrefix + value,
  3266. typeCache = cache[type] || (cache[type] = {});
  3267. if (type == 'object') {
  3268. (typeCache[key] || (typeCache[key] = [])).push(value);
  3269. } else {
  3270. typeCache[key] = true;
  3271. }
  3272. }
  3273. }
  3274. /**
  3275. * Used by `_.max` and `_.min` as the default callback when a given
  3276. * collection is a string value.
  3277. *
  3278. * @private
  3279. * @param {string} value The character to inspect.
  3280. * @returns {number} Returns the code unit of given character.
  3281. */
  3282. function charAtCallback(value) {
  3283. return value.charCodeAt(0);
  3284. }
  3285. /**
  3286. * Used by `sortBy` to compare transformed `collection` elements, stable sorting
  3287. * them in ascending order.
  3288. *
  3289. * @private
  3290. * @param {Object} a The object to compare to `b`.
  3291. * @param {Object} b The object to compare to `a`.
  3292. * @returns {number} Returns the sort order indicator of `1` or `-1`.
  3293. */
  3294. function compareAscending(a, b) {
  3295. var ac = a.criteria,
  3296. bc = b.criteria,
  3297. index = -1,
  3298. length = ac.length;
  3299. while (++index < length) {
  3300. var value = ac[index],
  3301. other = bc[index];
  3302. if (value !== other) {
  3303. if (value > other || typeof value == 'undefined') {
  3304. return 1;
  3305. }
  3306. if (value < other || typeof other == 'undefined') {
  3307. return -1;
  3308. }
  3309. }
  3310. }
  3311. // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
  3312. // that causes it, under certain circumstances, to return the same value for
  3313. // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247
  3314. //
  3315. // This also ensures a stable sort in V8 and other engines.
  3316. // See http://code.google.com/p/v8/issues/detail?id=90
  3317. return a.index - b.index;
  3318. }
  3319. /**
  3320. * Creates a cache object to optimize linear searches of large arrays.
  3321. *
  3322. * @private
  3323. * @param {Array} [array=[]] The array to search.
  3324. * @returns {null|Object} Returns the cache object or `null` if caching should not be used.
  3325. */
  3326. function createCache(array) {
  3327. var index = -1,
  3328. length = array.length,
  3329. first = array[0],
  3330. mid = array[(length / 2) | 0],
  3331. last = array[length - 1];
  3332. if (first && typeof first == 'object' &&
  3333. mid && typeof mid == 'object' && last && typeof last == 'object') {
  3334. return false;
  3335. }
  3336. var cache = getObject();
  3337. cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
  3338. var result = getObject();
  3339. result.array = array;
  3340. result.cache = cache;
  3341. result.push = cachePush;
  3342. while (++index < length) {
  3343. result.push(array[index]);
  3344. }
  3345. return result;
  3346. }
  3347. /**
  3348. * Used by `template` to escape characters for inclusion in compiled
  3349. * string literals.
  3350. *
  3351. * @private
  3352. * @param {string} match The matched character to escape.
  3353. * @returns {string} Returns the escaped character.
  3354. */
  3355. function escapeStringChar(match) {
  3356. return '\\' + stringEscapes[match];
  3357. }
  3358. /**
  3359. * Gets an array from the array pool or creates a new one if the pool is empty.
  3360. *
  3361. * @private
  3362. * @returns {Array} The array from the pool.
  3363. */
  3364. function getArray() {
  3365. return arrayPool.pop() || [];
  3366. }
  3367. /**
  3368. * Gets an object from the object pool or creates a new one if the pool is empty.
  3369. *
  3370. * @private
  3371. * @returns {Object} The object from the pool.
  3372. */
  3373. function getObject() {
  3374. return objectPool.pop() || {
  3375. 'array': null,
  3376. 'cache': null,
  3377. 'criteria': null,
  3378. 'false': false,
  3379. 'index': 0,
  3380. 'null': false,
  3381. 'number': null,
  3382. 'object': null,
  3383. 'push': null,
  3384. 'string': null,
  3385. 'true': false,
  3386. 'undefined': false,
  3387. 'value': null
  3388. };
  3389. }
  3390. /**
  3391. * Releases the given array back to the array pool.
  3392. *
  3393. * @private
  3394. * @param {Array} [array] The array to release.
  3395. */
  3396. function releaseArray(array) {
  3397. array.length = 0;
  3398. if (arrayPool.length < maxPoolSize) {
  3399. arrayPool.push(array);
  3400. }
  3401. }
  3402. /**
  3403. * Releases the given object back to the object pool.
  3404. *
  3405. * @private
  3406. * @param {Object} [object] The object to release.
  3407. */
  3408. function releaseObject(object) {
  3409. var cache = object.cache;
  3410. if (cache) {
  3411. releaseObject(cache);
  3412. }
  3413. object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
  3414. if (objectPool.length < maxPoolSize) {
  3415. objectPool.push(object);
  3416. }
  3417. }
  3418. /**
  3419. * Slices the `collection` from the `start` index up to, but not including,
  3420. * the `end` index.
  3421. *
  3422. * Note: This function is used instead of `Array#slice` to support node lists
  3423. * in IE < 9 and to ensure dense arrays are returned.
  3424. *
  3425. * @private
  3426. * @param {Array|Object|string} collection The collection to slice.
  3427. * @param {number} start The start index.
  3428. * @param {number} end The end index.
  3429. * @returns {Array} Returns the new array.
  3430. */
  3431. function slice(array, start, end) {
  3432. start || (start = 0);
  3433. if (typeof end == 'undefined') {
  3434. end = array ? array.length : 0;
  3435. }
  3436. var index = -1,
  3437. length = end - start || 0,
  3438. result = Array(length < 0 ? 0 : length);
  3439. while (++index < length) {
  3440. result[index] = array[start + index];
  3441. }
  3442. return result;
  3443. }
  3444. /*--------------------------------------------------------------------------*/
  3445. /**
  3446. * Create a new `lodash` function using the given context object.
  3447. *
  3448. * @static
  3449. * @memberOf _
  3450. * @category Utilities
  3451. * @param {Object} [context=root] The context object.
  3452. * @returns {Function} Returns the `lodash` function.
  3453. */
  3454. function runInContext(context) {
  3455. // Avoid issues with some ES3 environments that attempt to use values, named
  3456. // after built-in constructors like `Object`, for the creation of literals.
  3457. // ES5 clears this up by stating that literals must use built-in constructors.
  3458. // See http://es5.github.io/#x11.1.5.
  3459. context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
  3460. /** Native constructor references */
  3461. var Array = context.Array,
  3462. Boolean = context.Boolean,
  3463. Date = context.Date,
  3464. Function = context.Function,
  3465. Math = context.Math,
  3466. Number = context.Number,
  3467. Object = context.Object,
  3468. RegExp = context.RegExp,
  3469. String = context.String,
  3470. TypeError = context.TypeError;
  3471. /**
  3472. * Used for `Array` method references.
  3473. *
  3474. * Normally `Array.prototype` would suffice, however, using an array literal
  3475. * avoids issues in Narwhal.
  3476. */
  3477. var arrayRef = [];
  3478. /** Used for native method references */
  3479. var objectProto = Object.prototype;
  3480. /** Used to restore the original `_` reference in `noConflict` */
  3481. var oldDash = context._;
  3482. /** Used to resolve the internal [[Class]] of values */
  3483. var toString = objectProto.toString;
  3484. /** Used to detect if a method is native */
  3485. var reNative = RegExp('^' +
  3486. String(toString)
  3487. .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  3488. .replace(/toString| for [^\]]+/g, '.*?') + '$'
  3489. );
  3490. /** Native method shortcuts */
  3491. var ceil = Math.ceil,
  3492. clearTimeout = context.clearTimeout,
  3493. floor = Math.floor,
  3494. fnToString = Function.prototype.toString,
  3495. getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
  3496. hasOwnProperty = objectProto.hasOwnProperty,
  3497. push = arrayRef.push,
  3498. setTimeout = context.setTimeout,
  3499. splice = arrayRef.splice,
  3500. unshift = arrayRef.unshift;
  3501. /** Used to set meta data on functions */
  3502. var defineProperty = (function() {
  3503. // IE 8 only accepts DOM elements
  3504. try {
  3505. var o = {},
  3506. func = isNative(func = Object.defineProperty) && func,
  3507. result = func(o, o, o) && func;
  3508. } catch(e) { }
  3509. return result;
  3510. }());
  3511. /* Native method shortcuts for methods with the same name as other `lodash` methods */
  3512. var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,
  3513. nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,
  3514. nativeIsFinite = context.isFinite,
  3515. nativeIsNaN = context.isNaN,
  3516. nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,
  3517. nativeMax = Math.max,
  3518. nativeMin = Math.min,
  3519. nativeParseInt = context.parseInt,
  3520. nativeRandom = Math.random;
  3521. /** Used to lookup a built-in constructor by [[Class]] */
  3522. var ctorByClass = {};
  3523. ctorByClass[arrayClass] = Array;
  3524. ctorByClass[boolClass] = Boolean;
  3525. ctorByClass[dateClass] = Date;
  3526. ctorByClass[funcClass] = Function;
  3527. ctorByClass[objectClass] = Object;
  3528. ctorByClass[numberClass] = Number;
  3529. ctorByClass[regexpClass] = RegExp;
  3530. ctorByClass[stringClass] = String;
  3531. /*--------------------------------------------------------------------------*/
  3532. /**
  3533. * Creates a `lodash` object which wraps the given value to enable intuitive
  3534. * method chaining.
  3535. *
  3536. * In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
  3537. * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
  3538. * and `unshift`
  3539. *
  3540. * Chaining is supported in custom builds as long as the `value` method is
  3541. * implicitly or explicitly included in the build.
  3542. *
  3543. * The chainable wrapper functions are:
  3544. * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
  3545. * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`,
  3546. * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`,
  3547. * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
  3548. * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
  3549. * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
  3550. * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`,
  3551. * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`,
  3552. * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`,
  3553. * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`,
  3554. * and `zip`
  3555. *
  3556. * The non-chainable wrapper functions are:
  3557. * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
  3558. * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
  3559. * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
  3560. * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
  3561. * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
  3562. * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
  3563. * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
  3564. * `template`, `unescape`, `uniqueId`, and `value`
  3565. *
  3566. * The wrapper functions `first` and `last` return wrapped values when `n` is
  3567. * provided, otherwise they return unwrapped values.
  3568. *
  3569. * Explicit chaining can be enabled by using the `_.chain` method.
  3570. *
  3571. * @name _
  3572. * @constructor
  3573. * @category Chaining
  3574. * @param {*} value The value to wrap in a `lodash` instance.
  3575. * @returns {Object} Returns a `lodash` instance.
  3576. * @example
  3577. *
  3578. * var wrapped = _([1, 2, 3]);
  3579. *
  3580. * // returns an unwrapped value
  3581. * wrapped.reduce(function(sum, num) {
  3582. * return sum + num;
  3583. * });
  3584. * // => 6
  3585. *
  3586. * // returns a wrapped value
  3587. * var squares = wrapped.map(function(num) {
  3588. * return num * num;
  3589. * });
  3590. *
  3591. * _.isArray(squares);
  3592. * // => false
  3593. *
  3594. * _.isArray(squares.value());
  3595. * // => true
  3596. */
  3597. function lodash(value) {
  3598. // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
  3599. return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
  3600. ? value
  3601. : new lodashWrapper(value);
  3602. }
  3603. /**
  3604. * A fast path for creating `lodash` wrapper objects.
  3605. *
  3606. * @private
  3607. * @param {*} value The value to wrap in a `lodash` instance.
  3608. * @param {boolean} chainAll A flag to enable chaining for all methods
  3609. * @returns {Object} Returns a `lodash` instance.
  3610. */
  3611. function lodashWrapper(value, chainAll) {
  3612. this.__chain__ = !!chainAll;
  3613. this.__wrapped__ = value;
  3614. }
  3615. // ensure `new lodashWrapper` is an instance of `lodash`
  3616. lodashWrapper.prototype = lodash.prototype;
  3617. /**
  3618. * An object used to flag environments features.
  3619. *
  3620. * @static
  3621. * @memberOf _
  3622. * @type Object
  3623. */
  3624. var support = lodash.support = {};
  3625. /**
  3626. * Detect if functions can be decompiled by `Function#toString`
  3627. * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
  3628. *
  3629. * @memberOf _.support
  3630. * @type boolean
  3631. */
  3632. support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext);
  3633. /**
  3634. * Detect if `Function#name` is supported (all but IE).
  3635. *
  3636. * @memberOf _.support
  3637. * @type boolean
  3638. */
  3639. support.funcNames = typeof Function.name == 'string';
  3640. /**
  3641. * By default, the template delimiters used by Lo-Dash are similar to those in
  3642. * embedded Ruby (ERB). Change the following template settings to use alternative
  3643. * delimiters.
  3644. *
  3645. * @static
  3646. * @memberOf _
  3647. * @type Object
  3648. */
  3649. lodash.templateSettings = {
  3650. /**
  3651. * Used to detect `data` property values to be HTML-escaped.
  3652. *
  3653. * @memberOf _.templateSettings
  3654. * @type RegExp
  3655. */
  3656. 'escape': /<%-([\s\S]+?)%>/g,
  3657. /**
  3658. * Used to detect code to be evaluated.
  3659. *
  3660. * @memberOf _.templateSettings
  3661. * @type RegExp
  3662. */
  3663. 'evaluate': /<%([\s\S]+?)%>/g,
  3664. /**
  3665. * Used to detect `data` property values to inject.
  3666. *
  3667. * @memberOf _.templateSettings
  3668. * @type RegExp
  3669. */
  3670. 'interpolate': reInterpolate,
  3671. /**
  3672. * Used to reference the data object in the template text.
  3673. *
  3674. * @memberOf _.templateSettings
  3675. * @type string
  3676. */
  3677. 'variable': '',
  3678. /**
  3679. * Used to import variables into the compiled template.
  3680. *
  3681. * @memberOf _.templateSettings
  3682. * @type Object
  3683. */
  3684. 'imports': {
  3685. /**
  3686. * A reference to the `lodash` function.
  3687. *
  3688. * @memberOf _.templateSettings.imports
  3689. * @type Function
  3690. */
  3691. '_': lodash
  3692. }
  3693. };
  3694. /*--------------------------------------------------------------------------*/
  3695. /**
  3696. * The base implementation of `_.bind` that creates the bound function and
  3697. * sets its meta data.
  3698. *
  3699. * @private
  3700. * @param {Array} bindData The bind data array.
  3701. * @returns {Function} Returns the new bound function.
  3702. */
  3703. function baseBind(bindData) {
  3704. var func = bindData[0],
  3705. partialArgs = bindData[2],
  3706. thisArg = bindData[4];
  3707. function bound() {
  3708. // `Function#bind` spec
  3709. // http://es5.github.io/#x15.3.4.5
  3710. if (partialArgs) {
  3711. // avoid `arguments` object deoptimizations by using `slice` instead
  3712. // of `Array.prototype.slice.call` and not assigning `arguments` to a
  3713. // variable as a ternary expression
  3714. var args = slice(partialArgs);
  3715. push.apply(args, arguments);
  3716. }
  3717. // mimic the constructor's `return` behavior
  3718. // http://es5.github.io/#x13.2.2
  3719. if (this instanceof bound) {
  3720. // ensure `new bound` is an instance of `func`
  3721. var thisBinding = baseCreate(func.prototype),
  3722. result = func.apply(thisBinding, args || arguments);
  3723. return isObject(result) ? result : thisBinding;
  3724. }
  3725. return func.apply(thisArg, args || arguments);
  3726. }
  3727. setBindData(bound, bindData);
  3728. return bound;
  3729. }
  3730. /**
  3731. * The base implementation of `_.clone` without argument juggling or support
  3732. * for `thisArg` binding.
  3733. *
  3734. * @private
  3735. * @param {*} value The value to clone.
  3736. * @param {boolean} [isDeep=false] Specify a deep clone.
  3737. * @param {Function} [callback] The function to customize cloning values.
  3738. * @param {Array} [stackA=[]] Tracks traversed source objects.
  3739. * @param {Array} [stackB=[]] Associates clones with source counterparts.
  3740. * @returns {*} Returns the cloned value.
  3741. */
  3742. function baseClone(value, isDeep, callback, stackA, stackB) {
  3743. if (callback) {
  3744. var result = callback(value);
  3745. if (typeof result != 'undefined') {
  3746. return result;
  3747. }
  3748. }
  3749. // inspect [[Class]]
  3750. var isObj = isObject(value);
  3751. if (isObj) {
  3752. var className = toString.call(value);
  3753. if (!cloneableClasses[className]) {
  3754. return value;
  3755. }
  3756. var ctor = ctorByClass[className];
  3757. switch (className) {
  3758. case boolClass:
  3759. case dateClass:
  3760. return new ctor(+value);
  3761. case numberClass:
  3762. case stringClass:
  3763. return new ctor(value);
  3764. case regexpClass:
  3765. result = ctor(value.source, reFlags.exec(value));
  3766. result.lastIndex = value.lastIndex;
  3767. return result;
  3768. }
  3769. } else {
  3770. return value;
  3771. }
  3772. var isArr = isArray(value);
  3773. if (isDeep) {
  3774. // check for circular references and return corresponding clone
  3775. var initedStack = !stackA;
  3776. stackA || (stackA = getArray());
  3777. stackB || (stackB = getArray());
  3778. var length = stackA.length;
  3779. while (length--) {
  3780. if (stackA[length] == value) {
  3781. return stackB[length];
  3782. }
  3783. }
  3784. result = isArr ? ctor(value.length) : {};
  3785. }
  3786. else {
  3787. result = isArr ? slice(value) : assign({}, value);
  3788. }
  3789. // add array properties assigned by `RegExp#exec`
  3790. if (isArr) {
  3791. if (hasOwnProperty.call(value, 'index')) {
  3792. result.index = value.index;
  3793. }
  3794. if (hasOwnProperty.call(value, 'input')) {
  3795. result.input = value.input;
  3796. }
  3797. }
  3798. // exit for shallow clone
  3799. if (!isDeep) {
  3800. return result;
  3801. }
  3802. // add the source value to the stack of traversed objects
  3803. // and associate it with its clone
  3804. stackA.push(value);
  3805. stackB.push(result);
  3806. // recursively populate clone (susceptible to call stack limits)
  3807. (isArr ? forEach : forOwn)(value, function(objValue, key) {
  3808. result[key] = baseClone(objValue, isDeep, callback, stackA, stackB);
  3809. });
  3810. if (initedStack) {
  3811. releaseArray(stackA);
  3812. releaseArray(stackB);
  3813. }
  3814. return result;
  3815. }
  3816. /**
  3817. * The base implementation of `_.create` without support for assigning
  3818. * properties to the created object.
  3819. *
  3820. * @private
  3821. * @param {Object} prototype The object to inherit from.
  3822. * @returns {Object} Returns the new object.
  3823. */
  3824. function baseCreate(prototype, properties) {
  3825. return isObject(prototype) ? nativeCreate(prototype) : {};
  3826. }
  3827. // fallback for browsers without `Object.create`
  3828. if (!nativeCreate) {
  3829. baseCreate = (function() {
  3830. function Object() {}
  3831. return function(prototype) {
  3832. if (isObject(prototype)) {
  3833. Object.prototype = prototype;
  3834. var result = new Object;
  3835. Object.prototype = null;
  3836. }
  3837. return result || context.Object();
  3838. };
  3839. }());
  3840. }
  3841. /**
  3842. * The base implementation of `_.createCallback` without support for creating
  3843. * "_.pluck" or "_.where" style callbacks.
  3844. *
  3845. * @private
  3846. * @param {*} [func=identity] The value to convert to a callback.
  3847. * @param {*} [thisArg] The `this` binding of the created callback.
  3848. * @param {number} [argCount] The number of arguments the callback accepts.
  3849. * @returns {Function} Returns a callback function.
  3850. */
  3851. function baseCreateCallback(func, thisArg, argCount) {
  3852. if (typeof func != 'function') {
  3853. return identity;
  3854. }
  3855. // exit early for no `thisArg` or already bound by `Function#bind`
  3856. if (typeof thisArg == 'undefined' || !('prototype' in func)) {
  3857. return func;
  3858. }
  3859. var bindData = func.__bindData__;
  3860. if (typeof bindData == 'undefined') {
  3861. if (support.funcNames) {
  3862. bindData = !func.name;
  3863. }
  3864. bindData = bindData || !support.funcDecomp;
  3865. if (!bindData) {
  3866. var source = fnToString.call(func);
  3867. if (!support.funcNames) {
  3868. bindData = !reFuncName.test(source);
  3869. }
  3870. if (!bindData) {
  3871. // checks if `func` references the `this` keyword and stores the result
  3872. bindData = reThis.test(source);
  3873. setBindData(func, bindData);
  3874. }
  3875. }
  3876. }
  3877. // exit early if there are no `this` references or `func` is bound
  3878. if (bindData === false || (bindData !== true && bindData[1] & 1)) {
  3879. return func;
  3880. }
  3881. switch (argCount) {
  3882. case 1: return function(value) {
  3883. return func.call(thisArg, value);
  3884. };
  3885. case 2: return function(a, b) {
  3886. return func.call(thisArg, a, b);
  3887. };
  3888. case 3: return function(value, index, collection) {
  3889. return func.call(thisArg, value, index, collection);
  3890. };
  3891. case 4: return function(accumulator, value, index, collection) {
  3892. return func.call(thisArg, accumulator, value, index, collection);
  3893. };
  3894. }
  3895. return bind(func, thisArg);
  3896. }
  3897. /**
  3898. * The base implementation of `createWrapper` that creates the wrapper and
  3899. * sets its meta data.
  3900. *
  3901. * @private
  3902. * @param {Array} bindData The bind data array.
  3903. * @returns {Function} Returns the new function.
  3904. */
  3905. function baseCreateWrapper(bindData) {
  3906. var func = bindData[0],
  3907. bitmask = bindData[1],
  3908. partialArgs = bindData[2],
  3909. partialRightArgs = bindData[3],
  3910. thisArg = bindData[4],
  3911. arity = bindData[5];
  3912. var isBind = bitmask & 1,
  3913. isBindKey = bitmask & 2,
  3914. isCurry = bitmask & 4,
  3915. isCurryBound = bitmask & 8,
  3916. key = func;
  3917. function bound() {
  3918. var thisBinding = isBind ? thisArg : this;
  3919. if (partialArgs) {
  3920. var args = slice(partialArgs);
  3921. push.apply(args, arguments);
  3922. }
  3923. if (partialRightArgs || isCurry) {
  3924. args || (args = slice(arguments));
  3925. if (partialRightArgs) {
  3926. push.apply(args, partialRightArgs);
  3927. }
  3928. if (isCurry && args.length < arity) {
  3929. bitmask |= 16 & ~32;
  3930. return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
  3931. }
  3932. }
  3933. args || (args = arguments);
  3934. if (isBindKey) {
  3935. func = thisBinding[key];
  3936. }
  3937. if (this instanceof bound) {
  3938. thisBinding = baseCreate(func.prototype);
  3939. var result = func.apply(thisBinding, args);
  3940. return isObject(result) ? result : thisBinding;
  3941. }
  3942. return func.apply(thisBinding, args);
  3943. }
  3944. setBindData(bound, bindData);
  3945. return bound;
  3946. }
  3947. /**
  3948. * The base implementation of `_.difference` that accepts a single array
  3949. * of values to exclude.
  3950. *
  3951. * @private
  3952. * @param {Array} array The array to process.
  3953. * @param {Array} [values] The array of values to exclude.
  3954. * @returns {Array} Returns a new array of filtered values.
  3955. */
  3956. function baseDifference(array, values) {
  3957. var index = -1,
  3958. indexOf = getIndexOf(),
  3959. length = array ? array.length : 0,
  3960. isLarge = length >= largeArraySize && indexOf === baseIndexOf,
  3961. result = [];
  3962. if (isLarge) {
  3963. var cache = createCache(values);
  3964. if (cache) {
  3965. indexOf = cacheIndexOf;
  3966. values = cache;
  3967. } else {
  3968. isLarge = false;
  3969. }
  3970. }
  3971. while (++index < length) {
  3972. var value = array[index];
  3973. if (indexOf(values, value) < 0) {
  3974. result.push(value);
  3975. }
  3976. }
  3977. if (isLarge) {
  3978. releaseObject(values);
  3979. }
  3980. return result;
  3981. }
  3982. /**
  3983. * The base implementation of `_.flatten` without support for callback
  3984. * shorthands or `thisArg` binding.
  3985. *
  3986. * @private
  3987. * @param {Array} array The array to flatten.
  3988. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
  3989. * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects.
  3990. * @param {number} [fromIndex=0] The index to start from.
  3991. * @returns {Array} Returns a new flattened array.
  3992. */
  3993. function baseFlatten(array, isShallow, isStrict, fromIndex) {
  3994. var index = (fromIndex || 0) - 1,
  3995. length = array ? array.length : 0,
  3996. result = [];
  3997. while (++index < length) {
  3998. var value = array[index];
  3999. if (value && typeof value == 'object' && typeof value.length == 'number'
  4000. && (isArray(value) || isArguments(value))) {
  4001. // recursively flatten arrays (susceptible to call stack limits)
  4002. if (!isShallow) {
  4003. value = baseFlatten(value, isShallow, isStrict);
  4004. }
  4005. var valIndex = -1,
  4006. valLength = value.length,
  4007. resIndex = result.length;
  4008. result.length += valLength;
  4009. while (++valIndex < valLength) {
  4010. result[resIndex++] = value[valIndex];
  4011. }
  4012. } else if (!isStrict) {
  4013. result.push(value);
  4014. }
  4015. }
  4016. return result;
  4017. }
  4018. /**
  4019. * The base implementation of `_.isEqual`, without support for `thisArg` binding,
  4020. * that allows partial "_.where" style comparisons.
  4021. *
  4022. * @private
  4023. * @param {*} a The value to compare.
  4024. * @param {*} b The other value to compare.
  4025. * @param {Function} [callback] The function to customize comparing values.
  4026. * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
  4027. * @param {Array} [stackA=[]] Tracks traversed `a` objects.
  4028. * @param {Array} [stackB=[]] Tracks traversed `b` objects.
  4029. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  4030. */
  4031. function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
  4032. // used to indicate that when comparing objects, `a` has at least the properties of `b`
  4033. if (callback) {
  4034. var result = callback(a, b);
  4035. if (typeof result != 'undefined') {
  4036. return !!result;
  4037. }
  4038. }
  4039. // exit early for identical values
  4040. if (a === b) {
  4041. // treat `+0` vs. `-0` as not equal
  4042. return a !== 0 || (1 / a == 1 / b);
  4043. }
  4044. var type = typeof a,
  4045. otherType = typeof b;
  4046. // exit early for unlike primitive values
  4047. if (a === a &&
  4048. !(a && objectTypes[type]) &&
  4049. !(b && objectTypes[otherType])) {
  4050. return false;
  4051. }
  4052. // exit early for `null` and `undefined` avoiding ES3's Function#call behavior
  4053. // http://es5.github.io/#x15.3.4.4
  4054. if (a == null || b == null) {
  4055. return a === b;
  4056. }
  4057. // compare [[Class]] names
  4058. var className = toString.call(a),
  4059. otherClass = toString.call(b);
  4060. if (className == argsClass) {
  4061. className = objectClass;
  4062. }
  4063. if (otherClass == argsClass) {
  4064. otherClass = objectClass;
  4065. }
  4066. if (className != otherClass) {
  4067. return false;
  4068. }
  4069. switch (className) {
  4070. case boolClass:
  4071. case dateClass:
  4072. // coerce dates and booleans to numbers, dates to milliseconds and booleans
  4073. // to `1` or `0` treating invalid dates coerced to `NaN` as not equal
  4074. return +a == +b;
  4075. case numberClass:
  4076. // treat `NaN` vs. `NaN` as equal
  4077. return (a != +a)
  4078. ? b != +b
  4079. // but treat `+0` vs. `-0` as not equal
  4080. : (a == 0 ? (1 / a == 1 / b) : a == +b);
  4081. case regexpClass:
  4082. case stringClass:
  4083. // coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
  4084. // treat string primitives and their corresponding object instances as equal
  4085. return a == String(b);
  4086. }
  4087. var isArr = className == arrayClass;
  4088. if (!isArr) {
  4089. // unwrap any `lodash` wrapped values
  4090. var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
  4091. bWrapped = hasOwnProperty.call(b, '__wrapped__');
  4092. if (aWrapped || bWrapped) {
  4093. return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
  4094. }
  4095. // exit for functions and DOM nodes
  4096. if (className != objectClass) {
  4097. return false;
  4098. }
  4099. // in older versions of Opera, `arguments` objects have `Array` constructors
  4100. var ctorA = a.constructor,
  4101. ctorB = b.constructor;
  4102. // non `Object` object instances with different constructors are not equal
  4103. if (ctorA != ctorB &&
  4104. !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
  4105. ('constructor' in a && 'constructor' in b)
  4106. ) {
  4107. return false;
  4108. }
  4109. }
  4110. // assume cyclic structures are equal
  4111. // the algorithm for detecting cyclic structures is adapted from ES 5.1
  4112. // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
  4113. var initedStack = !stackA;
  4114. stackA || (stackA = getArray());
  4115. stackB || (stackB = getArray());
  4116. var length = stackA.length;
  4117. while (length--) {
  4118. if (stackA[length] == a) {
  4119. return stackB[length] == b;
  4120. }
  4121. }
  4122. var size = 0;
  4123. result = true;
  4124. // add `a` and `b` to the stack of traversed objects
  4125. stackA.push(a);
  4126. stackB.push(b);
  4127. // recursively compare objects and arrays (susceptible to call stack limits)
  4128. if (isArr) {
  4129. // compare lengths to determine if a deep comparison is necessary
  4130. length = a.length;
  4131. size = b.length;
  4132. result = size == length;
  4133. if (result || isWhere) {
  4134. // deep compare the contents, ignoring non-numeric properties
  4135. while (size--) {
  4136. var index = length,
  4137. value = b[size];
  4138. if (isWhere) {
  4139. while (index--) {
  4140. if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
  4141. break;
  4142. }
  4143. }
  4144. } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
  4145. break;
  4146. }
  4147. }
  4148. }
  4149. }
  4150. else {
  4151. // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
  4152. // which, in this case, is more costly
  4153. forIn(b, function(value, key, b) {
  4154. if (hasOwnProperty.call(b, key)) {
  4155. // count the number of properties.
  4156. size++;
  4157. // deep compare each property value.
  4158. return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
  4159. }
  4160. });
  4161. if (result && !isWhere) {
  4162. // ensure both objects have the same number of properties
  4163. forIn(a, function(value, key, a) {
  4164. if (hasOwnProperty.call(a, key)) {
  4165. // `size` will be `-1` if `a` has more properties than `b`
  4166. return (result = --size > -1);
  4167. }
  4168. });
  4169. }
  4170. }
  4171. stackA.pop();
  4172. stackB.pop();
  4173. if (initedStack) {
  4174. releaseArray(stackA);
  4175. releaseArray(stackB);
  4176. }
  4177. return result;
  4178. }
  4179. /**
  4180. * The base implementation of `_.merge` without argument juggling or support
  4181. * for `thisArg` binding.
  4182. *
  4183. * @private
  4184. * @param {Object} object The destination object.
  4185. * @param {Object} source The source object.
  4186. * @param {Function} [callback] The function to customize merging properties.
  4187. * @param {Array} [stackA=[]] Tracks traversed source objects.
  4188. * @param {Array} [stackB=[]] Associates values with source counterparts.
  4189. */
  4190. function baseMerge(object, source, callback, stackA, stackB) {
  4191. (isArray(source) ? forEach : forOwn)(source, function(source, key) {
  4192. var found,
  4193. isArr,
  4194. result = source,
  4195. value = object[key];
  4196. if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
  4197. // avoid merging previously merged cyclic sources
  4198. var stackLength = stackA.length;
  4199. while (stackLength--) {
  4200. if ((found = stackA[stackLength] == source)) {
  4201. value = stackB[stackLength];
  4202. break;
  4203. }
  4204. }
  4205. if (!found) {
  4206. var isShallow;
  4207. if (callback) {
  4208. result = callback(value, source);
  4209. if ((isShallow = typeof result != 'undefined')) {
  4210. value = result;
  4211. }
  4212. }
  4213. if (!isShallow) {
  4214. value = isArr
  4215. ? (isArray(value) ? value : [])
  4216. : (isPlainObject(value) ? value : {});
  4217. }
  4218. // add `source` and associated `value` to the stack of traversed objects
  4219. stackA.push(source);
  4220. stackB.push(value);
  4221. // recursively merge objects and arrays (susceptible to call stack limits)
  4222. if (!isShallow) {
  4223. baseMerge(value, source, callback, stackA, stackB);
  4224. }
  4225. }
  4226. }
  4227. else {
  4228. if (callback) {
  4229. result = callback(value, source);
  4230. if (typeof result == 'undefined') {
  4231. result = source;
  4232. }
  4233. }
  4234. if (typeof result != 'undefined') {
  4235. value = result;
  4236. }
  4237. }
  4238. object[key] = value;
  4239. });
  4240. }
  4241. /**
  4242. * The base implementation of `_.random` without argument juggling or support
  4243. * for returning floating-point numbers.
  4244. *
  4245. * @private
  4246. * @param {number} min The minimum possible value.
  4247. * @param {number} max The maximum possible value.
  4248. * @returns {number} Returns a random number.
  4249. */
  4250. function baseRandom(min, max) {
  4251. return min + floor(nativeRandom() * (max - min + 1));
  4252. }
  4253. /**
  4254. * The base implementation of `_.uniq` without support for callback shorthands
  4255. * or `thisArg` binding.
  4256. *
  4257. * @private
  4258. * @param {Array} array The array to process.
  4259. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
  4260. * @param {Function} [callback] The function called per iteration.
  4261. * @returns {Array} Returns a duplicate-value-free array.
  4262. */
  4263. function baseUniq(array, isSorted, callback) {
  4264. var index = -1,
  4265. indexOf = getIndexOf(),
  4266. length = array ? array.length : 0,
  4267. result = [];
  4268. var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf,
  4269. seen = (callback || isLarge) ? getArray() : result;
  4270. if (isLarge) {
  4271. var cache = createCache(seen);
  4272. indexOf = cacheIndexOf;
  4273. seen = cache;
  4274. }
  4275. while (++index < length) {
  4276. var value = array[index],
  4277. computed = callback ? callback(value, index, array) : value;
  4278. if (isSorted
  4279. ? !index || seen[seen.length - 1] !== computed
  4280. : indexOf(seen, computed) < 0
  4281. ) {
  4282. if (callback || isLarge) {
  4283. seen.push(computed);
  4284. }
  4285. result.push(value);
  4286. }
  4287. }
  4288. if (isLarge) {
  4289. releaseArray(seen.array);
  4290. releaseObject(seen);
  4291. } else if (callback) {
  4292. releaseArray(seen);
  4293. }
  4294. return result;
  4295. }
  4296. /**
  4297. * Creates a function that aggregates a collection, creating an object composed
  4298. * of keys generated from the results of running each element of the collection
  4299. * through a callback. The given `setter` function sets the keys and values
  4300. * of the composed object.
  4301. *
  4302. * @private
  4303. * @param {Function} setter The setter function.
  4304. * @returns {Function} Returns the new aggregator function.
  4305. */
  4306. function createAggregator(setter) {
  4307. return function(collection, callback, thisArg) {
  4308. var result = {};
  4309. callback = lodash.createCallback(callback, thisArg, 3);
  4310. var index = -1,
  4311. length = collection ? collection.length : 0;
  4312. if (typeof length == 'number') {
  4313. while (++index < length) {
  4314. var value = collection[index];
  4315. setter(result, value, callback(value, index, collection), collection);
  4316. }
  4317. } else {
  4318. forOwn(collection, function(value, key, collection) {
  4319. setter(result, value, callback(value, key, collection), collection);
  4320. });
  4321. }
  4322. return result;
  4323. };
  4324. }
  4325. /**
  4326. * Creates a function that, when called, either curries or invokes `func`
  4327. * with an optional `this` binding and partially applied arguments.
  4328. *
  4329. * @private
  4330. * @param {Function|string} func The function or method name to reference.
  4331. * @param {number} bitmask The bitmask of method flags to compose.
  4332. * The bitmask may be composed of the following flags:
  4333. * 1 - `_.bind`
  4334. * 2 - `_.bindKey`
  4335. * 4 - `_.curry`
  4336. * 8 - `_.curry` (bound)
  4337. * 16 - `_.partial`
  4338. * 32 - `_.partialRight`
  4339. * @param {Array} [partialArgs] An array of arguments to prepend to those
  4340. * provided to the new function.
  4341. * @param {Array} [partialRightArgs] An array of arguments to append to those
  4342. * provided to the new function.
  4343. * @param {*} [thisArg] The `this` binding of `func`.
  4344. * @param {number} [arity] The arity of `func`.
  4345. * @returns {Function} Returns the new function.
  4346. */
  4347. function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
  4348. var isBind = bitmask & 1,
  4349. isBindKey = bitmask & 2,
  4350. isCurry = bitmask & 4,
  4351. isCurryBound = bitmask & 8,
  4352. isPartial = bitmask & 16,
  4353. isPartialRight = bitmask & 32;
  4354. if (!isBindKey && !isFunction(func)) {
  4355. throw new TypeError;
  4356. }
  4357. if (isPartial && !partialArgs.length) {
  4358. bitmask &= ~16;
  4359. isPartial = partialArgs = false;
  4360. }
  4361. if (isPartialRight && !partialRightArgs.length) {
  4362. bitmask &= ~32;
  4363. isPartialRight = partialRightArgs = false;
  4364. }
  4365. var bindData = func && func.__bindData__;
  4366. if (bindData && bindData !== true) {
  4367. // clone `bindData`
  4368. bindData = slice(bindData);
  4369. if (bindData[2]) {
  4370. bindData[2] = slice(bindData[2]);
  4371. }
  4372. if (bindData[3]) {
  4373. bindData[3] = slice(bindData[3]);
  4374. }
  4375. // set `thisBinding` is not previously bound
  4376. if (isBind && !(bindData[1] & 1)) {
  4377. bindData[4] = thisArg;
  4378. }
  4379. // set if previously bound but not currently (subsequent curried functions)
  4380. if (!isBind && bindData[1] & 1) {
  4381. bitmask |= 8;
  4382. }
  4383. // set curried arity if not yet set
  4384. if (isCurry && !(bindData[1] & 4)) {
  4385. bindData[5] = arity;
  4386. }
  4387. // append partial left arguments
  4388. if (isPartial) {
  4389. push.apply(bindData[2] || (bindData[2] = []), partialArgs);
  4390. }
  4391. // append partial right arguments
  4392. if (isPartialRight) {
  4393. unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
  4394. }
  4395. // merge flags
  4396. bindData[1] |= bitmask;
  4397. return createWrapper.apply(null, bindData);
  4398. }
  4399. // fast path for `_.bind`
  4400. var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
  4401. return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
  4402. }
  4403. /**
  4404. * Used by `escape` to convert characters to HTML entities.
  4405. *
  4406. * @private
  4407. * @param {string} match The matched character to escape.
  4408. * @returns {string} Returns the escaped character.
  4409. */
  4410. function escapeHtmlChar(match) {
  4411. return htmlEscapes[match];
  4412. }
  4413. /**
  4414. * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
  4415. * customized, this method returns the custom method, otherwise it returns
  4416. * the `baseIndexOf` function.
  4417. *
  4418. * @private
  4419. * @returns {Function} Returns the "indexOf" function.
  4420. */
  4421. function getIndexOf() {
  4422. var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result;
  4423. return result;
  4424. }
  4425. /**
  4426. * Checks if `value` is a native function.
  4427. *
  4428. * @private
  4429. * @param {*} value The value to check.
  4430. * @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
  4431. */
  4432. function isNative(value) {
  4433. return typeof value == 'function' && reNative.test(value);
  4434. }
  4435. /**
  4436. * Sets `this` binding data on a given function.
  4437. *
  4438. * @private
  4439. * @param {Function} func The function to set data on.
  4440. * @param {Array} value The data array to set.
  4441. */
  4442. var setBindData = !defineProperty ? noop : function(func, value) {
  4443. descriptor.value = value;
  4444. defineProperty(func, '__bindData__', descriptor);
  4445. };
  4446. /**
  4447. * A fallback implementation of `isPlainObject` which checks if a given value
  4448. * is an object created by the `Object` constructor, assuming objects created
  4449. * by the `Object` constructor have no inherited enumerable properties and that
  4450. * there are no `Object.prototype` extensions.
  4451. *
  4452. * @private
  4453. * @param {*} value The value to check.
  4454. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  4455. */
  4456. function shimIsPlainObject(value) {
  4457. var ctor,
  4458. result;
  4459. // avoid non Object objects, `arguments` objects, and DOM elements
  4460. if (!(value && toString.call(value) == objectClass) ||
  4461. (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) {
  4462. return false;
  4463. }
  4464. // In most environments an object's own properties are iterated before
  4465. // its inherited properties. If the last iterated property is an object's
  4466. // own property then there are no inherited enumerable properties.
  4467. forIn(value, function(value, key) {
  4468. result = key;
  4469. });
  4470. return typeof result == 'undefined' || hasOwnProperty.call(value, result);
  4471. }
  4472. /**
  4473. * Used by `unescape` to convert HTML entities to characters.
  4474. *
  4475. * @private
  4476. * @param {string} match The matched character to unescape.
  4477. * @returns {string} Returns the unescaped character.
  4478. */
  4479. function unescapeHtmlChar(match) {
  4480. return htmlUnescapes[match];
  4481. }
  4482. /*--------------------------------------------------------------------------*/
  4483. /**
  4484. * Checks if `value` is an `arguments` object.
  4485. *
  4486. * @static
  4487. * @memberOf _
  4488. * @category Objects
  4489. * @param {*} value The value to check.
  4490. * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
  4491. * @example
  4492. *
  4493. * (function() { return _.isArguments(arguments); })(1, 2, 3);
  4494. * // => true
  4495. *
  4496. * _.isArguments([1, 2, 3]);
  4497. * // => false
  4498. */
  4499. function isArguments(value) {
  4500. return value && typeof value == 'object' && typeof value.length == 'number' &&
  4501. toString.call(value) == argsClass || false;
  4502. }
  4503. /**
  4504. * Checks if `value` is an array.
  4505. *
  4506. * @static
  4507. * @memberOf _
  4508. * @type Function
  4509. * @category Objects
  4510. * @param {*} value The value to check.
  4511. * @returns {boolean} Returns `true` if the `value` is an array, else `false`.
  4512. * @example
  4513. *
  4514. * (function() { return _.isArray(arguments); })();
  4515. * // => false
  4516. *
  4517. * _.isArray([1, 2, 3]);
  4518. * // => true
  4519. */
  4520. var isArray = nativeIsArray || function(value) {
  4521. return value && typeof value == 'object' && typeof value.length == 'number' &&
  4522. toString.call(value) == arrayClass || false;
  4523. };
  4524. /**
  4525. * A fallback implementation of `Object.keys` which produces an array of the
  4526. * given object's own enumerable property names.
  4527. *
  4528. * @private
  4529. * @type Function
  4530. * @param {Object} object The object to inspect.
  4531. * @returns {Array} Returns an array of property names.
  4532. */
  4533. var shimKeys = function(object) {
  4534. var index, iterable = object, result = [];
  4535. if (!iterable) return result;
  4536. if (!(objectTypes[typeof object])) return result;
  4537. for (index in iterable) {
  4538. if (hasOwnProperty.call(iterable, index)) {
  4539. result.push(index);
  4540. }
  4541. }
  4542. return result
  4543. };
  4544. /**
  4545. * Creates an array composed of the own enumerable property names of an object.
  4546. *
  4547. * @static
  4548. * @memberOf _
  4549. * @category Objects
  4550. * @param {Object} object The object to inspect.
  4551. * @returns {Array} Returns an array of property names.
  4552. * @example
  4553. *
  4554. * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
  4555. * // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
  4556. */
  4557. var keys = !nativeKeys ? shimKeys : function(object) {
  4558. if (!isObject(object)) {
  4559. return [];
  4560. }
  4561. return nativeKeys(object);
  4562. };
  4563. /**
  4564. * Used to convert characters to HTML entities:
  4565. *
  4566. * Though the `>` character is escaped for symmetry, characters like `>` and `/`
  4567. * don't require escaping in HTML and have no special meaning unless they're part
  4568. * of a tag or an unquoted attribute value.
  4569. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
  4570. */
  4571. var htmlEscapes = {
  4572. '&': '&amp;',
  4573. '<': '&lt;',
  4574. '>': '&gt;',
  4575. '"': '&quot;',
  4576. "'": '&#39;'
  4577. };
  4578. /** Used to convert HTML entities to characters */
  4579. var htmlUnescapes = invert(htmlEscapes);
  4580. /** Used to match HTML entities and HTML characters */
  4581. var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'),
  4582. reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g');
  4583. /*--------------------------------------------------------------------------*/
  4584. /**
  4585. * Assigns own enumerable properties of source object(s) to the destination
  4586. * object. Subsequent sources will overwrite property assignments of previous
  4587. * sources. If a callback is provided it will be executed to produce the
  4588. * assigned values. The callback is bound to `thisArg` and invoked with two
  4589. * arguments; (objectValue, sourceValue).
  4590. *
  4591. * @static
  4592. * @memberOf _
  4593. * @type Function
  4594. * @alias extend
  4595. * @category Objects
  4596. * @param {Object} object The destination object.
  4597. * @param {...Object} [source] The source objects.
  4598. * @param {Function} [callback] The function to customize assigning values.
  4599. * @param {*} [thisArg] The `this` binding of `callback`.
  4600. * @returns {Object} Returns the destination object.
  4601. * @example
  4602. *
  4603. * _.assign({ 'name': 'fred' }, { 'employer': 'slate' });
  4604. * // => { 'name': 'fred', 'employer': 'slate' }
  4605. *
  4606. * var defaults = _.partialRight(_.assign, function(a, b) {
  4607. * return typeof a == 'undefined' ? b : a;
  4608. * });
  4609. *
  4610. * var object = { 'name': 'barney' };
  4611. * defaults(object, { 'name': 'fred', 'employer': 'slate' });
  4612. * // => { 'name': 'barney', 'employer': 'slate' }
  4613. */
  4614. var assign = function(object, source, guard) {
  4615. var index, iterable = object, result = iterable;
  4616. if (!iterable) return result;
  4617. var args = arguments,
  4618. argsIndex = 0,
  4619. argsLength = typeof guard == 'number' ? 2 : args.length;
  4620. if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {
  4621. var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);
  4622. } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {
  4623. callback = args[--argsLength];
  4624. }
  4625. while (++argsIndex < argsLength) {
  4626. iterable = args[argsIndex];
  4627. if (iterable && objectTypes[typeof iterable]) {
  4628. var ownIndex = -1,
  4629. ownProps = objectTypes[typeof iterable] && keys(iterable),
  4630. length = ownProps ? ownProps.length : 0;
  4631. while (++ownIndex < length) {
  4632. index = ownProps[ownIndex];
  4633. result[index] = callback ? callback(result[index], iterable[index]) : iterable[index];
  4634. }
  4635. }
  4636. }
  4637. return result
  4638. };
  4639. /**
  4640. * Creates a clone of `value`. If `isDeep` is `true` nested objects will also
  4641. * be cloned, otherwise they will be assigned by reference. If a callback
  4642. * is provided it will be executed to produce the cloned values. If the
  4643. * callback returns `undefined` cloning will be handled by the method instead.
  4644. * The callback is bound to `thisArg` and invoked with one argument; (value).
  4645. *
  4646. * @static
  4647. * @memberOf _
  4648. * @category Objects
  4649. * @param {*} value The value to clone.
  4650. * @param {boolean} [isDeep=false] Specify a deep clone.
  4651. * @param {Function} [callback] The function to customize cloning values.
  4652. * @param {*} [thisArg] The `this` binding of `callback`.
  4653. * @returns {*} Returns the cloned value.
  4654. * @example
  4655. *
  4656. * var characters = [
  4657. * { 'name': 'barney', 'age': 36 },
  4658. * { 'name': 'fred', 'age': 40 }
  4659. * ];
  4660. *
  4661. * var shallow = _.clone(characters);
  4662. * shallow[0] === characters[0];
  4663. * // => true
  4664. *
  4665. * var deep = _.clone(characters, true);
  4666. * deep[0] === characters[0];
  4667. * // => false
  4668. *
  4669. * _.mixin({
  4670. * 'clone': _.partialRight(_.clone, function(value) {
  4671. * return _.isElement(value) ? value.cloneNode(false) : undefined;
  4672. * })
  4673. * });
  4674. *
  4675. * var clone = _.clone(document.body);
  4676. * clone.childNodes.length;
  4677. * // => 0
  4678. */
  4679. function clone(value, isDeep, callback, thisArg) {
  4680. // allows working with "Collections" methods without using their `index`
  4681. // and `collection` arguments for `isDeep` and `callback`
  4682. if (typeof isDeep != 'boolean' && isDeep != null) {
  4683. thisArg = callback;
  4684. callback = isDeep;
  4685. isDeep = false;
  4686. }
  4687. return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
  4688. }
  4689. /**
  4690. * Creates a deep clone of `value`. If a callback is provided it will be
  4691. * executed to produce the cloned values. If the callback returns `undefined`
  4692. * cloning will be handled by the method instead. The callback is bound to
  4693. * `thisArg` and invoked with one argument; (value).
  4694. *
  4695. * Note: This method is loosely based on the structured clone algorithm. Functions
  4696. * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
  4697. * objects created by constructors other than `Object` are cloned to plain `Object` objects.
  4698. * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
  4699. *
  4700. * @static
  4701. * @memberOf _
  4702. * @category Objects
  4703. * @param {*} value The value to deep clone.
  4704. * @param {Function} [callback] The function to customize cloning values.
  4705. * @param {*} [thisArg] The `this` binding of `callback`.
  4706. * @returns {*} Returns the deep cloned value.
  4707. * @example
  4708. *
  4709. * var characters = [
  4710. * { 'name': 'barney', 'age': 36 },
  4711. * { 'name': 'fred', 'age': 40 }
  4712. * ];
  4713. *
  4714. * var deep = _.cloneDeep(characters);
  4715. * deep[0] === characters[0];
  4716. * // => false
  4717. *
  4718. * var view = {
  4719. * 'label': 'docs',
  4720. * 'node': element
  4721. * };
  4722. *
  4723. * var clone = _.cloneDeep(view, function(value) {
  4724. * return _.isElement(value) ? value.cloneNode(true) : undefined;
  4725. * });
  4726. *
  4727. * clone.node == view.node;
  4728. * // => false
  4729. */
  4730. function cloneDeep(value, callback, thisArg) {
  4731. return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
  4732. }
  4733. /**
  4734. * Creates an object that inherits from the given `prototype` object. If a
  4735. * `properties` object is provided its own enumerable properties are assigned
  4736. * to the created object.
  4737. *
  4738. * @static
  4739. * @memberOf _
  4740. * @category Objects
  4741. * @param {Object} prototype The object to inherit from.
  4742. * @param {Object} [properties] The properties to assign to the object.
  4743. * @returns {Object} Returns the new object.
  4744. * @example
  4745. *
  4746. * function Shape() {
  4747. * this.x = 0;
  4748. * this.y = 0;
  4749. * }
  4750. *
  4751. * function Circle() {
  4752. * Shape.call(this);
  4753. * }
  4754. *
  4755. * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle });
  4756. *
  4757. * var circle = new Circle;
  4758. * circle instanceof Circle;
  4759. * // => true
  4760. *
  4761. * circle instanceof Shape;
  4762. * // => true
  4763. */
  4764. function create(prototype, properties) {
  4765. var result = baseCreate(prototype);
  4766. return properties ? assign(result, properties) : result;
  4767. }
  4768. /**
  4769. * Assigns own enumerable properties of source object(s) to the destination
  4770. * object for all destination properties that resolve to `undefined`. Once a
  4771. * property is set, additional defaults of the same property will be ignored.
  4772. *
  4773. * @static
  4774. * @memberOf _
  4775. * @type Function
  4776. * @category Objects
  4777. * @param {Object} object The destination object.
  4778. * @param {...Object} [source] The source objects.
  4779. * @param- {Object} [guard] Allows working with `_.reduce` without using its
  4780. * `key` and `object` arguments as sources.
  4781. * @returns {Object} Returns the destination object.
  4782. * @example
  4783. *
  4784. * var object = { 'name': 'barney' };
  4785. * _.defaults(object, { 'name': 'fred', 'employer': 'slate' });
  4786. * // => { 'name': 'barney', 'employer': 'slate' }
  4787. */
  4788. var defaults = function(object, source, guard) {
  4789. var index, iterable = object, result = iterable;
  4790. if (!iterable) return result;
  4791. var args = arguments,
  4792. argsIndex = 0,
  4793. argsLength = typeof guard == 'number' ? 2 : args.length;
  4794. while (++argsIndex < argsLength) {
  4795. iterable = args[argsIndex];
  4796. if (iterable && objectTypes[typeof iterable]) {
  4797. var ownIndex = -1,
  4798. ownProps = objectTypes[typeof iterable] && keys(iterable),
  4799. length = ownProps ? ownProps.length : 0;
  4800. while (++ownIndex < length) {
  4801. index = ownProps[ownIndex];
  4802. if (typeof result[index] == 'undefined') result[index] = iterable[index];
  4803. }
  4804. }
  4805. }
  4806. return result
  4807. };
  4808. /**
  4809. * This method is like `_.findIndex` except that it returns the key of the
  4810. * first element that passes the callback check, instead of the element itself.
  4811. *
  4812. * If a property name is provided for `callback` the created "_.pluck" style
  4813. * callback will return the property value of the given element.
  4814. *
  4815. * If an object is provided for `callback` the created "_.where" style callback
  4816. * will return `true` for elements that have the properties of the given object,
  4817. * else `false`.
  4818. *
  4819. * @static
  4820. * @memberOf _
  4821. * @category Objects
  4822. * @param {Object} object The object to search.
  4823. * @param {Function|Object|string} [callback=identity] The function called per
  4824. * iteration. If a property name or object is provided it will be used to
  4825. * create a "_.pluck" or "_.where" style callback, respectively.
  4826. * @param {*} [thisArg] The `this` binding of `callback`.
  4827. * @returns {string|undefined} Returns the key of the found element, else `undefined`.
  4828. * @example
  4829. *
  4830. * var characters = {
  4831. * 'barney': { 'age': 36, 'blocked': false },
  4832. * 'fred': { 'age': 40, 'blocked': true },
  4833. * 'pebbles': { 'age': 1, 'blocked': false }
  4834. * };
  4835. *
  4836. * _.findKey(characters, function(chr) {
  4837. * return chr.age < 40;
  4838. * });
  4839. * // => 'barney' (property order is not guaranteed across environments)
  4840. *
  4841. * // using "_.where" callback shorthand
  4842. * _.findKey(characters, { 'age': 1 });
  4843. * // => 'pebbles'
  4844. *
  4845. * // using "_.pluck" callback shorthand
  4846. * _.findKey(characters, 'blocked');
  4847. * // => 'fred'
  4848. */
  4849. function findKey(object, callback, thisArg) {
  4850. var result;
  4851. callback = lodash.createCallback(callback, thisArg, 3);
  4852. forOwn(object, function(value, key, object) {
  4853. if (callback(value, key, object)) {
  4854. result = key;
  4855. return false;
  4856. }
  4857. });
  4858. return result;
  4859. }
  4860. /**
  4861. * This method is like `_.findKey` except that it iterates over elements
  4862. * of a `collection` in the opposite order.
  4863. *
  4864. * If a property name is provided for `callback` the created "_.pluck" style
  4865. * callback will return the property value of the given element.
  4866. *
  4867. * If an object is provided for `callback` the created "_.where" style callback
  4868. * will return `true` for elements that have the properties of the given object,
  4869. * else `false`.
  4870. *
  4871. * @static
  4872. * @memberOf _
  4873. * @category Objects
  4874. * @param {Object} object The object to search.
  4875. * @param {Function|Object|string} [callback=identity] The function called per
  4876. * iteration. If a property name or object is provided it will be used to
  4877. * create a "_.pluck" or "_.where" style callback, respectively.
  4878. * @param {*} [thisArg] The `this` binding of `callback`.
  4879. * @returns {string|undefined} Returns the key of the found element, else `undefined`.
  4880. * @example
  4881. *
  4882. * var characters = {
  4883. * 'barney': { 'age': 36, 'blocked': true },
  4884. * 'fred': { 'age': 40, 'blocked': false },
  4885. * 'pebbles': { 'age': 1, 'blocked': true }
  4886. * };
  4887. *
  4888. * _.findLastKey(characters, function(chr) {
  4889. * return chr.age < 40;
  4890. * });
  4891. * // => returns `pebbles`, assuming `_.findKey` returns `barney`
  4892. *
  4893. * // using "_.where" callback shorthand
  4894. * _.findLastKey(characters, { 'age': 40 });
  4895. * // => 'fred'
  4896. *
  4897. * // using "_.pluck" callback shorthand
  4898. * _.findLastKey(characters, 'blocked');
  4899. * // => 'pebbles'
  4900. */
  4901. function findLastKey(object, callback, thisArg) {
  4902. var result;
  4903. callback = lodash.createCallback(callback, thisArg, 3);
  4904. forOwnRight(object, function(value, key, object) {
  4905. if (callback(value, key, object)) {
  4906. result = key;
  4907. return false;
  4908. }
  4909. });
  4910. return result;
  4911. }
  4912. /**
  4913. * Iterates over own and inherited enumerable properties of an object,
  4914. * executing the callback for each property. The callback is bound to `thisArg`
  4915. * and invoked with three arguments; (value, key, object). Callbacks may exit
  4916. * iteration early by explicitly returning `false`.
  4917. *
  4918. * @static
  4919. * @memberOf _
  4920. * @type Function
  4921. * @category Objects
  4922. * @param {Object} object The object to iterate over.
  4923. * @param {Function} [callback=identity] The function called per iteration.
  4924. * @param {*} [thisArg] The `this` binding of `callback`.
  4925. * @returns {Object} Returns `object`.
  4926. * @example
  4927. *
  4928. * function Shape() {
  4929. * this.x = 0;
  4930. * this.y = 0;
  4931. * }
  4932. *
  4933. * Shape.prototype.move = function(x, y) {
  4934. * this.x += x;
  4935. * this.y += y;
  4936. * };
  4937. *
  4938. * _.forIn(new Shape, function(value, key) {
  4939. * console.log(key);
  4940. * });
  4941. * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
  4942. */
  4943. var forIn = function(collection, callback, thisArg) {
  4944. var index, iterable = collection, result = iterable;
  4945. if (!iterable) return result;
  4946. if (!objectTypes[typeof iterable]) return result;
  4947. callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
  4948. for (index in iterable) {
  4949. if (callback(iterable[index], index, collection) === false) return result;
  4950. }
  4951. return result
  4952. };
  4953. /**
  4954. * This method is like `_.forIn` except that it iterates over elements
  4955. * of a `collection` in the opposite order.
  4956. *
  4957. * @static
  4958. * @memberOf _
  4959. * @category Objects
  4960. * @param {Object} object The object to iterate over.
  4961. * @param {Function} [callback=identity] The function called per iteration.
  4962. * @param {*} [thisArg] The `this` binding of `callback`.
  4963. * @returns {Object} Returns `object`.
  4964. * @example
  4965. *
  4966. * function Shape() {
  4967. * this.x = 0;
  4968. * this.y = 0;
  4969. * }
  4970. *
  4971. * Shape.prototype.move = function(x, y) {
  4972. * this.x += x;
  4973. * this.y += y;
  4974. * };
  4975. *
  4976. * _.forInRight(new Shape, function(value, key) {
  4977. * console.log(key);
  4978. * });
  4979. * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move'
  4980. */
  4981. function forInRight(object, callback, thisArg) {
  4982. var pairs = [];
  4983. forIn(object, function(value, key) {
  4984. pairs.push(key, value);
  4985. });
  4986. var length = pairs.length;
  4987. callback = baseCreateCallback(callback, thisArg, 3);
  4988. while (length--) {
  4989. if (callback(pairs[length--], pairs[length], object) === false) {
  4990. break;
  4991. }
  4992. }
  4993. return object;
  4994. }
  4995. /**
  4996. * Iterates over own enumerable properties of an object, executing the callback
  4997. * for each property. The callback is bound to `thisArg` and invoked with three
  4998. * arguments; (value, key, object). Callbacks may exit iteration early by
  4999. * explicitly returning `false`.
  5000. *
  5001. * @static
  5002. * @memberOf _
  5003. * @type Function
  5004. * @category Objects
  5005. * @param {Object} object The object to iterate over.
  5006. * @param {Function} [callback=identity] The function called per iteration.
  5007. * @param {*} [thisArg] The `this` binding of `callback`.
  5008. * @returns {Object} Returns `object`.
  5009. * @example
  5010. *
  5011. * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
  5012. * console.log(key);
  5013. * });
  5014. * // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
  5015. */
  5016. var forOwn = function(collection, callback, thisArg) {
  5017. var index, iterable = collection, result = iterable;
  5018. if (!iterable) return result;
  5019. if (!objectTypes[typeof iterable]) return result;
  5020. callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
  5021. var ownIndex = -1,
  5022. ownProps = objectTypes[typeof iterable] && keys(iterable),
  5023. length = ownProps ? ownProps.length : 0;
  5024. while (++ownIndex < length) {
  5025. index = ownProps[ownIndex];
  5026. if (callback(iterable[index], index, collection) === false) return result;
  5027. }
  5028. return result
  5029. };
  5030. /**
  5031. * This method is like `_.forOwn` except that it iterates over elements
  5032. * of a `collection` in the opposite order.
  5033. *
  5034. * @static
  5035. * @memberOf _
  5036. * @category Objects
  5037. * @param {Object} object The object to iterate over.
  5038. * @param {Function} [callback=identity] The function called per iteration.
  5039. * @param {*} [thisArg] The `this` binding of `callback`.
  5040. * @returns {Object} Returns `object`.
  5041. * @example
  5042. *
  5043. * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
  5044. * console.log(key);
  5045. * });
  5046. * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
  5047. */
  5048. function forOwnRight(object, callback, thisArg) {
  5049. var props = keys(object),
  5050. length = props.length;
  5051. callback = baseCreateCallback(callback, thisArg, 3);
  5052. while (length--) {
  5053. var key = props[length];
  5054. if (callback(object[key], key, object) === false) {
  5055. break;
  5056. }
  5057. }
  5058. return object;
  5059. }
  5060. /**
  5061. * Creates a sorted array of property names of all enumerable properties,
  5062. * own and inherited, of `object` that have function values.
  5063. *
  5064. * @static
  5065. * @memberOf _
  5066. * @alias methods
  5067. * @category Objects
  5068. * @param {Object} object The object to inspect.
  5069. * @returns {Array} Returns an array of property names that have function values.
  5070. * @example
  5071. *
  5072. * _.functions(_);
  5073. * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
  5074. */
  5075. function functions(object) {
  5076. var result = [];
  5077. forIn(object, function(value, key) {
  5078. if (isFunction(value)) {
  5079. result.push(key);
  5080. }
  5081. });
  5082. return result.sort();
  5083. }
  5084. /**
  5085. * Checks if the specified property name exists as a direct property of `object`,
  5086. * instead of an inherited property.
  5087. *
  5088. * @static
  5089. * @memberOf _
  5090. * @category Objects
  5091. * @param {Object} object The object to inspect.
  5092. * @param {string} key The name of the property to check.
  5093. * @returns {boolean} Returns `true` if key is a direct property, else `false`.
  5094. * @example
  5095. *
  5096. * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
  5097. * // => true
  5098. */
  5099. function has(object, key) {
  5100. return object ? hasOwnProperty.call(object, key) : false;
  5101. }
  5102. /**
  5103. * Creates an object composed of the inverted keys and values of the given object.
  5104. *
  5105. * @static
  5106. * @memberOf _
  5107. * @category Objects
  5108. * @param {Object} object The object to invert.
  5109. * @returns {Object} Returns the created inverted object.
  5110. * @example
  5111. *
  5112. * _.invert({ 'first': 'fred', 'second': 'barney' });
  5113. * // => { 'fred': 'first', 'barney': 'second' }
  5114. */
  5115. function invert(object) {
  5116. var index = -1,
  5117. props = keys(object),
  5118. length = props.length,
  5119. result = {};
  5120. while (++index < length) {
  5121. var key = props[index];
  5122. result[object[key]] = key;
  5123. }
  5124. return result;
  5125. }
  5126. /**
  5127. * Checks if `value` is a boolean value.
  5128. *
  5129. * @static
  5130. * @memberOf _
  5131. * @category Objects
  5132. * @param {*} value The value to check.
  5133. * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
  5134. * @example
  5135. *
  5136. * _.isBoolean(null);
  5137. * // => false
  5138. */
  5139. function isBoolean(value) {
  5140. return value === true || value === false ||
  5141. value && typeof value == 'object' && toString.call(value) == boolClass || false;
  5142. }
  5143. /**
  5144. * Checks if `value` is a date.
  5145. *
  5146. * @static
  5147. * @memberOf _
  5148. * @category Objects
  5149. * @param {*} value The value to check.
  5150. * @returns {boolean} Returns `true` if the `value` is a date, else `false`.
  5151. * @example
  5152. *
  5153. * _.isDate(new Date);
  5154. * // => true
  5155. */
  5156. function isDate(value) {
  5157. return value && typeof value == 'object' && toString.call(value) == dateClass || false;
  5158. }
  5159. /**
  5160. * Checks if `value` is a DOM element.
  5161. *
  5162. * @static
  5163. * @memberOf _
  5164. * @category Objects
  5165. * @param {*} value The value to check.
  5166. * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`.
  5167. * @example
  5168. *
  5169. * _.isElement(document.body);
  5170. * // => true
  5171. */
  5172. function isElement(value) {
  5173. return value && value.nodeType === 1 || false;
  5174. }
  5175. /**
  5176. * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
  5177. * length of `0` and objects with no own enumerable properties are considered
  5178. * "empty".
  5179. *
  5180. * @static
  5181. * @memberOf _
  5182. * @category Objects
  5183. * @param {Array|Object|string} value The value to inspect.
  5184. * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
  5185. * @example
  5186. *
  5187. * _.isEmpty([1, 2, 3]);
  5188. * // => false
  5189. *
  5190. * _.isEmpty({});
  5191. * // => true
  5192. *
  5193. * _.isEmpty('');
  5194. * // => true
  5195. */
  5196. function isEmpty(value) {
  5197. var result = true;
  5198. if (!value) {
  5199. return result;
  5200. }
  5201. var className = toString.call(value),
  5202. length = value.length;
  5203. if ((className == arrayClass || className == stringClass || className == argsClass ) ||
  5204. (className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
  5205. return !length;
  5206. }
  5207. forOwn(value, function() {
  5208. return (result = false);
  5209. });
  5210. return result;
  5211. }
  5212. /**
  5213. * Performs a deep comparison between two values to determine if they are
  5214. * equivalent to each other. If a callback is provided it will be executed
  5215. * to compare values. If the callback returns `undefined` comparisons will
  5216. * be handled by the method instead. The callback is bound to `thisArg` and
  5217. * invoked with two arguments; (a, b).
  5218. *
  5219. * @static
  5220. * @memberOf _
  5221. * @category Objects
  5222. * @param {*} a The value to compare.
  5223. * @param {*} b The other value to compare.
  5224. * @param {Function} [callback] The function to customize comparing values.
  5225. * @param {*} [thisArg] The `this` binding of `callback`.
  5226. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  5227. * @example
  5228. *
  5229. * var object = { 'name': 'fred' };
  5230. * var copy = { 'name': 'fred' };
  5231. *
  5232. * object == copy;
  5233. * // => false
  5234. *
  5235. * _.isEqual(object, copy);
  5236. * // => true
  5237. *
  5238. * var words = ['hello', 'goodbye'];
  5239. * var otherWords = ['hi', 'goodbye'];
  5240. *
  5241. * _.isEqual(words, otherWords, function(a, b) {
  5242. * var reGreet = /^(?:hello|hi)$/i,
  5243. * aGreet = _.isString(a) && reGreet.test(a),
  5244. * bGreet = _.isString(b) && reGreet.test(b);
  5245. *
  5246. * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
  5247. * });
  5248. * // => true
  5249. */
  5250. function isEqual(a, b, callback, thisArg) {
  5251. return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2));
  5252. }
  5253. /**
  5254. * Checks if `value` is, or can be coerced to, a finite number.
  5255. *
  5256. * Note: This is not the same as native `isFinite` which will return true for
  5257. * booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
  5258. *
  5259. * @static
  5260. * @memberOf _
  5261. * @category Objects
  5262. * @param {*} value The value to check.
  5263. * @returns {boolean} Returns `true` if the `value` is finite, else `false`.
  5264. * @example
  5265. *
  5266. * _.isFinite(-101);
  5267. * // => true
  5268. *
  5269. * _.isFinite('10');
  5270. * // => true
  5271. *
  5272. * _.isFinite(true);
  5273. * // => false
  5274. *
  5275. * _.isFinite('');
  5276. * // => false
  5277. *
  5278. * _.isFinite(Infinity);
  5279. * // => false
  5280. */
  5281. function isFinite(value) {
  5282. return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
  5283. }
  5284. /**
  5285. * Checks if `value` is a function.
  5286. *
  5287. * @static
  5288. * @memberOf _
  5289. * @category Objects
  5290. * @param {*} value The value to check.
  5291. * @returns {boolean} Returns `true` if the `value` is a function, else `false`.
  5292. * @example
  5293. *
  5294. * _.isFunction(_);
  5295. * // => true
  5296. */
  5297. function isFunction(value) {
  5298. return typeof value == 'function';
  5299. }
  5300. /**
  5301. * Checks if `value` is the language type of Object.
  5302. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  5303. *
  5304. * @static
  5305. * @memberOf _
  5306. * @category Objects
  5307. * @param {*} value The value to check.
  5308. * @returns {boolean} Returns `true` if the `value` is an object, else `false`.
  5309. * @example
  5310. *
  5311. * _.isObject({});
  5312. * // => true
  5313. *
  5314. * _.isObject([1, 2, 3]);
  5315. * // => true
  5316. *
  5317. * _.isObject(1);
  5318. * // => false
  5319. */
  5320. function isObject(value) {
  5321. // check if the value is the ECMAScript language type of Object
  5322. // http://es5.github.io/#x8
  5323. // and avoid a V8 bug
  5324. // http://code.google.com/p/v8/issues/detail?id=2291
  5325. return !!(value && objectTypes[typeof value]);
  5326. }
  5327. /**
  5328. * Checks if `value` is `NaN`.
  5329. *
  5330. * Note: This is not the same as native `isNaN` which will return `true` for
  5331. * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
  5332. *
  5333. * @static
  5334. * @memberOf _
  5335. * @category Objects
  5336. * @param {*} value The value to check.
  5337. * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
  5338. * @example
  5339. *
  5340. * _.isNaN(NaN);
  5341. * // => true
  5342. *
  5343. * _.isNaN(new Number(NaN));
  5344. * // => true
  5345. *
  5346. * isNaN(undefined);
  5347. * // => true
  5348. *
  5349. * _.isNaN(undefined);
  5350. * // => false
  5351. */
  5352. function isNaN(value) {
  5353. // `NaN` as a primitive is the only value that is not equal to itself
  5354. // (perform the [[Class]] check first to avoid errors with some host objects in IE)
  5355. return isNumber(value) && value != +value;
  5356. }
  5357. /**
  5358. * Checks if `value` is `null`.
  5359. *
  5360. * @static
  5361. * @memberOf _
  5362. * @category Objects
  5363. * @param {*} value The value to check.
  5364. * @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
  5365. * @example
  5366. *
  5367. * _.isNull(null);
  5368. * // => true
  5369. *
  5370. * _.isNull(undefined);
  5371. * // => false
  5372. */
  5373. function isNull(value) {
  5374. return value === null;
  5375. }
  5376. /**
  5377. * Checks if `value` is a number.
  5378. *
  5379. * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
  5380. *
  5381. * @static
  5382. * @memberOf _
  5383. * @category Objects
  5384. * @param {*} value The value to check.
  5385. * @returns {boolean} Returns `true` if the `value` is a number, else `false`.
  5386. * @example
  5387. *
  5388. * _.isNumber(8.4 * 5);
  5389. * // => true
  5390. */
  5391. function isNumber(value) {
  5392. return typeof value == 'number' ||
  5393. value && typeof value == 'object' && toString.call(value) == numberClass || false;
  5394. }
  5395. /**
  5396. * Checks if `value` is an object created by the `Object` constructor.
  5397. *
  5398. * @static
  5399. * @memberOf _
  5400. * @category Objects
  5401. * @param {*} value The value to check.
  5402. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  5403. * @example
  5404. *
  5405. * function Shape() {
  5406. * this.x = 0;
  5407. * this.y = 0;
  5408. * }
  5409. *
  5410. * _.isPlainObject(new Shape);
  5411. * // => false
  5412. *
  5413. * _.isPlainObject([1, 2, 3]);
  5414. * // => false
  5415. *
  5416. * _.isPlainObject({ 'x': 0, 'y': 0 });
  5417. * // => true
  5418. */
  5419. var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
  5420. if (!(value && toString.call(value) == objectClass)) {
  5421. return false;
  5422. }
  5423. var valueOf = value.valueOf,
  5424. objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
  5425. return objProto
  5426. ? (value == objProto || getPrototypeOf(value) == objProto)
  5427. : shimIsPlainObject(value);
  5428. };
  5429. /**
  5430. * Checks if `value` is a regular expression.
  5431. *
  5432. * @static
  5433. * @memberOf _
  5434. * @category Objects
  5435. * @param {*} value The value to check.
  5436. * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`.
  5437. * @example
  5438. *
  5439. * _.isRegExp(/fred/);
  5440. * // => true
  5441. */
  5442. function isRegExp(value) {
  5443. return value && typeof value == 'object' && toString.call(value) == regexpClass || false;
  5444. }
  5445. /**
  5446. * Checks if `value` is a string.
  5447. *
  5448. * @static
  5449. * @memberOf _
  5450. * @category Objects
  5451. * @param {*} value The value to check.
  5452. * @returns {boolean} Returns `true` if the `value` is a string, else `false`.
  5453. * @example
  5454. *
  5455. * _.isString('fred');
  5456. * // => true
  5457. */
  5458. function isString(value) {
  5459. return typeof value == 'string' ||
  5460. value && typeof value == 'object' && toString.call(value) == stringClass || false;
  5461. }
  5462. /**
  5463. * Checks if `value` is `undefined`.
  5464. *
  5465. * @static
  5466. * @memberOf _
  5467. * @category Objects
  5468. * @param {*} value The value to check.
  5469. * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
  5470. * @example
  5471. *
  5472. * _.isUndefined(void 0);
  5473. * // => true
  5474. */
  5475. function isUndefined(value) {
  5476. return typeof value == 'undefined';
  5477. }
  5478. /**
  5479. * Creates an object with the same keys as `object` and values generated by
  5480. * running each own enumerable property of `object` through the callback.
  5481. * The callback is bound to `thisArg` and invoked with three arguments;
  5482. * (value, key, object).
  5483. *
  5484. * If a property name is provided for `callback` the created "_.pluck" style
  5485. * callback will return the property value of the given element.
  5486. *
  5487. * If an object is provided for `callback` the created "_.where" style callback
  5488. * will return `true` for elements that have the properties of the given object,
  5489. * else `false`.
  5490. *
  5491. * @static
  5492. * @memberOf _
  5493. * @category Objects
  5494. * @param {Object} object The object to iterate over.
  5495. * @param {Function|Object|string} [callback=identity] The function called
  5496. * per iteration. If a property name or object is provided it will be used
  5497. * to create a "_.pluck" or "_.where" style callback, respectively.
  5498. * @param {*} [thisArg] The `this` binding of `callback`.
  5499. * @returns {Array} Returns a new object with values of the results of each `callback` execution.
  5500. * @example
  5501. *
  5502. * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
  5503. * // => { 'a': 3, 'b': 6, 'c': 9 }
  5504. *
  5505. * var characters = {
  5506. * 'fred': { 'name': 'fred', 'age': 40 },
  5507. * 'pebbles': { 'name': 'pebbles', 'age': 1 }
  5508. * };
  5509. *
  5510. * // using "_.pluck" callback shorthand
  5511. * _.mapValues(characters, 'age');
  5512. * // => { 'fred': 40, 'pebbles': 1 }
  5513. */
  5514. function mapValues(object, callback, thisArg) {
  5515. var result = {};
  5516. callback = lodash.createCallback(callback, thisArg, 3);
  5517. forOwn(object, function(value, key, object) {
  5518. result[key] = callback(value, key, object);
  5519. });
  5520. return result;
  5521. }
  5522. /**
  5523. * Recursively merges own enumerable properties of the source object(s), that
  5524. * don't resolve to `undefined` into the destination object. Subsequent sources
  5525. * will overwrite property assignments of previous sources. If a callback is
  5526. * provided it will be executed to produce the merged values of the destination
  5527. * and source properties. If the callback returns `undefined` merging will
  5528. * be handled by the method instead. The callback is bound to `thisArg` and
  5529. * invoked with two arguments; (objectValue, sourceValue).
  5530. *
  5531. * @static
  5532. * @memberOf _
  5533. * @category Objects
  5534. * @param {Object} object The destination object.
  5535. * @param {...Object} [source] The source objects.
  5536. * @param {Function} [callback] The function to customize merging properties.
  5537. * @param {*} [thisArg] The `this` binding of `callback`.
  5538. * @returns {Object} Returns the destination object.
  5539. * @example
  5540. *
  5541. * var names = {
  5542. * 'characters': [
  5543. * { 'name': 'barney' },
  5544. * { 'name': 'fred' }
  5545. * ]
  5546. * };
  5547. *
  5548. * var ages = {
  5549. * 'characters': [
  5550. * { 'age': 36 },
  5551. * { 'age': 40 }
  5552. * ]
  5553. * };
  5554. *
  5555. * _.merge(names, ages);
  5556. * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
  5557. *
  5558. * var food = {
  5559. * 'fruits': ['apple'],
  5560. * 'vegetables': ['beet']
  5561. * };
  5562. *
  5563. * var otherFood = {
  5564. * 'fruits': ['banana'],
  5565. * 'vegetables': ['carrot']
  5566. * };
  5567. *
  5568. * _.merge(food, otherFood, function(a, b) {
  5569. * return _.isArray(a) ? a.concat(b) : undefined;
  5570. * });
  5571. * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
  5572. */
  5573. function merge(object) {
  5574. var args = arguments,
  5575. length = 2;
  5576. if (!isObject(object)) {
  5577. return object;
  5578. }
  5579. // allows working with `_.reduce` and `_.reduceRight` without using
  5580. // their `index` and `collection` arguments
  5581. if (typeof args[2] != 'number') {
  5582. length = args.length;
  5583. }
  5584. if (length > 3 && typeof args[length - 2] == 'function') {
  5585. var callback = baseCreateCallback(args[--length - 1], args[length--], 2);
  5586. } else if (length > 2 && typeof args[length - 1] == 'function') {
  5587. callback = args[--length];
  5588. }
  5589. var sources = slice(arguments, 1, length),
  5590. index = -1,
  5591. stackA = getArray(),
  5592. stackB = getArray();
  5593. while (++index < length) {
  5594. baseMerge(object, sources[index], callback, stackA, stackB);
  5595. }
  5596. releaseArray(stackA);
  5597. releaseArray(stackB);
  5598. return object;
  5599. }
  5600. /**
  5601. * Creates a shallow clone of `object` excluding the specified properties.
  5602. * Property names may be specified as individual arguments or as arrays of
  5603. * property names. If a callback is provided it will be executed for each
  5604. * property of `object` omitting the properties the callback returns truey
  5605. * for. The callback is bound to `thisArg` and invoked with three arguments;
  5606. * (value, key, object).
  5607. *
  5608. * @static
  5609. * @memberOf _
  5610. * @category Objects
  5611. * @param {Object} object The source object.
  5612. * @param {Function|...string|string[]} [callback] The properties to omit or the
  5613. * function called per iteration.
  5614. * @param {*} [thisArg] The `this` binding of `callback`.
  5615. * @returns {Object} Returns an object without the omitted properties.
  5616. * @example
  5617. *
  5618. * _.omit({ 'name': 'fred', 'age': 40 }, 'age');
  5619. * // => { 'name': 'fred' }
  5620. *
  5621. * _.omit({ 'name': 'fred', 'age': 40 }, function(value) {
  5622. * return typeof value == 'number';
  5623. * });
  5624. * // => { 'name': 'fred' }
  5625. */
  5626. function omit(object, callback, thisArg) {
  5627. var result = {};
  5628. if (typeof callback != 'function') {
  5629. var props = [];
  5630. forIn(object, function(value, key) {
  5631. props.push(key);
  5632. });
  5633. props = baseDifference(props, baseFlatten(arguments, true, false, 1));
  5634. var index = -1,
  5635. length = props.length;
  5636. while (++index < length) {
  5637. var key = props[index];
  5638. result[key] = object[key];
  5639. }
  5640. } else {
  5641. callback = lodash.createCallback(callback, thisArg, 3);
  5642. forIn(object, function(value, key, object) {
  5643. if (!callback(value, key, object)) {
  5644. result[key] = value;
  5645. }
  5646. });
  5647. }
  5648. return result;
  5649. }
  5650. /**
  5651. * Creates a two dimensional array of an object's key-value pairs,
  5652. * i.e. `[[key1, value1], [key2, value2]]`.
  5653. *
  5654. * @static
  5655. * @memberOf _
  5656. * @category Objects
  5657. * @param {Object} object The object to inspect.
  5658. * @returns {Array} Returns new array of key-value pairs.
  5659. * @example
  5660. *
  5661. * _.pairs({ 'barney': 36, 'fred': 40 });
  5662. * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
  5663. */
  5664. function pairs(object) {
  5665. var index = -1,
  5666. props = keys(object),
  5667. length = props.length,
  5668. result = Array(length);
  5669. while (++index < length) {
  5670. var key = props[index];
  5671. result[index] = [key, object[key]];
  5672. }
  5673. return result;
  5674. }
  5675. /**
  5676. * Creates a shallow clone of `object` composed of the specified properties.
  5677. * Property names may be specified as individual arguments or as arrays of
  5678. * property names. If a callback is provided it will be executed for each
  5679. * property of `object` picking the properties the callback returns truey
  5680. * for. The callback is bound to `thisArg` and invoked with three arguments;
  5681. * (value, key, object).
  5682. *
  5683. * @static
  5684. * @memberOf _
  5685. * @category Objects
  5686. * @param {Object} object The source object.
  5687. * @param {Function|...string|string[]} [callback] The function called per
  5688. * iteration or property names to pick, specified as individual property
  5689. * names or arrays of property names.
  5690. * @param {*} [thisArg] The `this` binding of `callback`.
  5691. * @returns {Object} Returns an object composed of the picked properties.
  5692. * @example
  5693. *
  5694. * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name');
  5695. * // => { 'name': 'fred' }
  5696. *
  5697. * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) {
  5698. * return key.charAt(0) != '_';
  5699. * });
  5700. * // => { 'name': 'fred' }
  5701. */
  5702. function pick(object, callback, thisArg) {
  5703. var result = {};
  5704. if (typeof callback != 'function') {
  5705. var index = -1,
  5706. props = baseFlatten(arguments, true, false, 1),
  5707. length = isObject(object) ? props.length : 0;
  5708. while (++index < length) {
  5709. var key = props[index];
  5710. if (key in object) {
  5711. result[key] = object[key];
  5712. }
  5713. }
  5714. } else {
  5715. callback = lodash.createCallback(callback, thisArg, 3);
  5716. forIn(object, function(value, key, object) {
  5717. if (callback(value, key, object)) {
  5718. result[key] = value;
  5719. }
  5720. });
  5721. }
  5722. return result;
  5723. }
  5724. /**
  5725. * An alternative to `_.reduce` this method transforms `object` to a new
  5726. * `accumulator` object which is the result of running each of its own
  5727. * enumerable properties through a callback, with each callback execution
  5728. * potentially mutating the `accumulator` object. The callback is bound to
  5729. * `thisArg` and invoked with four arguments; (accumulator, value, key, object).
  5730. * Callbacks may exit iteration early by explicitly returning `false`.
  5731. *
  5732. * @static
  5733. * @memberOf _
  5734. * @category Objects
  5735. * @param {Array|Object} object The object to iterate over.
  5736. * @param {Function} [callback=identity] The function called per iteration.
  5737. * @param {*} [accumulator] The custom accumulator value.
  5738. * @param {*} [thisArg] The `this` binding of `callback`.
  5739. * @returns {*} Returns the accumulated value.
  5740. * @example
  5741. *
  5742. * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
  5743. * num *= num;
  5744. * if (num % 2) {
  5745. * return result.push(num) < 3;
  5746. * }
  5747. * });
  5748. * // => [1, 9, 25]
  5749. *
  5750. * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
  5751. * result[key] = num * 3;
  5752. * });
  5753. * // => { 'a': 3, 'b': 6, 'c': 9 }
  5754. */
  5755. function transform(object, callback, accumulator, thisArg) {
  5756. var isArr = isArray(object);
  5757. if (accumulator == null) {
  5758. if (isArr) {
  5759. accumulator = [];
  5760. } else {
  5761. var ctor = object && object.constructor,
  5762. proto = ctor && ctor.prototype;
  5763. accumulator = baseCreate(proto);
  5764. }
  5765. }
  5766. if (callback) {
  5767. callback = lodash.createCallback(callback, thisArg, 4);
  5768. (isArr ? forEach : forOwn)(object, function(value, index, object) {
  5769. return callback(accumulator, value, index, object);
  5770. });
  5771. }
  5772. return accumulator;
  5773. }
  5774. /**
  5775. * Creates an array composed of the own enumerable property values of `object`.
  5776. *
  5777. * @static
  5778. * @memberOf _
  5779. * @category Objects
  5780. * @param {Object} object The object to inspect.
  5781. * @returns {Array} Returns an array of property values.
  5782. * @example
  5783. *
  5784. * _.values({ 'one': 1, 'two': 2, 'three': 3 });
  5785. * // => [1, 2, 3] (property order is not guaranteed across environments)
  5786. */
  5787. function values(object) {
  5788. var index = -1,
  5789. props = keys(object),
  5790. length = props.length,
  5791. result = Array(length);
  5792. while (++index < length) {
  5793. result[index] = object[props[index]];
  5794. }
  5795. return result;
  5796. }
  5797. /*--------------------------------------------------------------------------*/
  5798. /**
  5799. * Creates an array of elements from the specified indexes, or keys, of the
  5800. * `collection`. Indexes may be specified as individual arguments or as arrays
  5801. * of indexes.
  5802. *
  5803. * @static
  5804. * @memberOf _
  5805. * @category Collections
  5806. * @param {Array|Object|string} collection The collection to iterate over.
  5807. * @param {...(number|number[]|string|string[])} [index] The indexes of `collection`
  5808. * to retrieve, specified as individual indexes or arrays of indexes.
  5809. * @returns {Array} Returns a new array of elements corresponding to the
  5810. * provided indexes.
  5811. * @example
  5812. *
  5813. * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
  5814. * // => ['a', 'c', 'e']
  5815. *
  5816. * _.at(['fred', 'barney', 'pebbles'], 0, 2);
  5817. * // => ['fred', 'pebbles']
  5818. */
  5819. function at(collection) {
  5820. var args = arguments,
  5821. index = -1,
  5822. props = baseFlatten(args, true, false, 1),
  5823. length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length,
  5824. result = Array(length);
  5825. while(++index < length) {
  5826. result[index] = collection[props[index]];
  5827. }
  5828. return result;
  5829. }
  5830. /**
  5831. * Checks if a given value is present in a collection using strict equality
  5832. * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the
  5833. * offset from the end of the collection.
  5834. *
  5835. * @static
  5836. * @memberOf _
  5837. * @alias include
  5838. * @category Collections
  5839. * @param {Array|Object|string} collection The collection to iterate over.
  5840. * @param {*} target The value to check for.
  5841. * @param {number} [fromIndex=0] The index to search from.
  5842. * @returns {boolean} Returns `true` if the `target` element is found, else `false`.
  5843. * @example
  5844. *
  5845. * _.contains([1, 2, 3], 1);
  5846. * // => true
  5847. *
  5848. * _.contains([1, 2, 3], 1, 2);
  5849. * // => false
  5850. *
  5851. * _.contains({ 'name': 'fred', 'age': 40 }, 'fred');
  5852. * // => true
  5853. *
  5854. * _.contains('pebbles', 'eb');
  5855. * // => true
  5856. */
  5857. function contains(collection, target, fromIndex) {
  5858. var index = -1,
  5859. indexOf = getIndexOf(),
  5860. length = collection ? collection.length : 0,
  5861. result = false;
  5862. fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
  5863. if (isArray(collection)) {
  5864. result = indexOf(collection, target, fromIndex) > -1;
  5865. } else if (typeof length == 'number') {
  5866. result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1;
  5867. } else {
  5868. forOwn(collection, function(value) {
  5869. if (++index >= fromIndex) {
  5870. return !(result = value === target);
  5871. }
  5872. });
  5873. }
  5874. return result;
  5875. }
  5876. /**
  5877. * Creates an object composed of keys generated from the results of running
  5878. * each element of `collection` through the callback. The corresponding value
  5879. * of each key is the number of times the key was returned by the callback.
  5880. * The callback is bound to `thisArg` and invoked with three arguments;
  5881. * (value, index|key, collection).
  5882. *
  5883. * If a property name is provided for `callback` the created "_.pluck" style
  5884. * callback will return the property value of the given element.
  5885. *
  5886. * If an object is provided for `callback` the created "_.where" style callback
  5887. * will return `true` for elements that have the properties of the given object,
  5888. * else `false`.
  5889. *
  5890. * @static
  5891. * @memberOf _
  5892. * @category Collections
  5893. * @param {Array|Object|string} collection The collection to iterate over.
  5894. * @param {Function|Object|string} [callback=identity] The function called
  5895. * per iteration. If a property name or object is provided it will be used
  5896. * to create a "_.pluck" or "_.where" style callback, respectively.
  5897. * @param {*} [thisArg] The `this` binding of `callback`.
  5898. * @returns {Object} Returns the composed aggregate object.
  5899. * @example
  5900. *
  5901. * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
  5902. * // => { '4': 1, '6': 2 }
  5903. *
  5904. * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  5905. * // => { '4': 1, '6': 2 }
  5906. *
  5907. * _.countBy(['one', 'two', 'three'], 'length');
  5908. * // => { '3': 2, '5': 1 }
  5909. */
  5910. var countBy = createAggregator(function(result, value, key) {
  5911. (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
  5912. });
  5913. /**
  5914. * Checks if the given callback returns truey value for **all** elements of
  5915. * a collection. The callback is bound to `thisArg` and invoked with three
  5916. * arguments; (value, index|key, collection).
  5917. *
  5918. * If a property name is provided for `callback` the created "_.pluck" style
  5919. * callback will return the property value of the given element.
  5920. *
  5921. * If an object is provided for `callback` the created "_.where" style callback
  5922. * will return `true` for elements that have the properties of the given object,
  5923. * else `false`.
  5924. *
  5925. * @static
  5926. * @memberOf _
  5927. * @alias all
  5928. * @category Collections
  5929. * @param {Array|Object|string} collection The collection to iterate over.
  5930. * @param {Function|Object|string} [callback=identity] The function called
  5931. * per iteration. If a property name or object is provided it will be used
  5932. * to create a "_.pluck" or "_.where" style callback, respectively.
  5933. * @param {*} [thisArg] The `this` binding of `callback`.
  5934. * @returns {boolean} Returns `true` if all elements passed the callback check,
  5935. * else `false`.
  5936. * @example
  5937. *
  5938. * _.every([true, 1, null, 'yes']);
  5939. * // => false
  5940. *
  5941. * var characters = [
  5942. * { 'name': 'barney', 'age': 36 },
  5943. * { 'name': 'fred', 'age': 40 }
  5944. * ];
  5945. *
  5946. * // using "_.pluck" callback shorthand
  5947. * _.every(characters, 'age');
  5948. * // => true
  5949. *
  5950. * // using "_.where" callback shorthand
  5951. * _.every(characters, { 'age': 36 });
  5952. * // => false
  5953. */
  5954. function every(collection, callback, thisArg) {
  5955. var result = true;
  5956. callback = lodash.createCallback(callback, thisArg, 3);
  5957. var index = -1,
  5958. length = collection ? collection.length : 0;
  5959. if (typeof length == 'number') {
  5960. while (++index < length) {
  5961. if (!(result = !!callback(collection[index], index, collection))) {
  5962. break;
  5963. }
  5964. }
  5965. } else {
  5966. forOwn(collection, function(value, index, collection) {
  5967. return (result = !!callback(value, index, collection));
  5968. });
  5969. }
  5970. return result;
  5971. }
  5972. /**
  5973. * Iterates over elements of a collection, returning an array of all elements
  5974. * the callback returns truey for. The callback is bound to `thisArg` and
  5975. * invoked with three arguments; (value, index|key, collection).
  5976. *
  5977. * If a property name is provided for `callback` the created "_.pluck" style
  5978. * callback will return the property value of the given element.
  5979. *
  5980. * If an object is provided for `callback` the created "_.where" style callback
  5981. * will return `true` for elements that have the properties of the given object,
  5982. * else `false`.
  5983. *
  5984. * @static
  5985. * @memberOf _
  5986. * @alias select
  5987. * @category Collections
  5988. * @param {Array|Object|string} collection The collection to iterate over.
  5989. * @param {Function|Object|string} [callback=identity] The function called
  5990. * per iteration. If a property name or object is provided it will be used
  5991. * to create a "_.pluck" or "_.where" style callback, respectively.
  5992. * @param {*} [thisArg] The `this` binding of `callback`.
  5993. * @returns {Array} Returns a new array of elements that passed the callback check.
  5994. * @example
  5995. *
  5996. * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  5997. * // => [2, 4, 6]
  5998. *
  5999. * var characters = [
  6000. * { 'name': 'barney', 'age': 36, 'blocked': false },
  6001. * { 'name': 'fred', 'age': 40, 'blocked': true }
  6002. * ];
  6003. *
  6004. * // using "_.pluck" callback shorthand
  6005. * _.filter(characters, 'blocked');
  6006. * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
  6007. *
  6008. * // using "_.where" callback shorthand
  6009. * _.filter(characters, { 'age': 36 });
  6010. * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
  6011. */
  6012. function filter(collection, callback, thisArg) {
  6013. var result = [];
  6014. callback = lodash.createCallback(callback, thisArg, 3);
  6015. var index = -1,
  6016. length = collection ? collection.length : 0;
  6017. if (typeof length == 'number') {
  6018. while (++index < length) {
  6019. var value = collection[index];
  6020. if (callback(value, index, collection)) {
  6021. result.push(value);
  6022. }
  6023. }
  6024. } else {
  6025. forOwn(collection, function(value, index, collection) {
  6026. if (callback(value, index, collection)) {
  6027. result.push(value);
  6028. }
  6029. });
  6030. }
  6031. return result;
  6032. }
  6033. /**
  6034. * Iterates over elements of a collection, returning the first element that
  6035. * the callback returns truey for. The callback is bound to `thisArg` and
  6036. * invoked with three arguments; (value, index|key, collection).
  6037. *
  6038. * If a property name is provided for `callback` the created "_.pluck" style
  6039. * callback will return the property value of the given element.
  6040. *
  6041. * If an object is provided for `callback` the created "_.where" style callback
  6042. * will return `true` for elements that have the properties of the given object,
  6043. * else `false`.
  6044. *
  6045. * @static
  6046. * @memberOf _
  6047. * @alias detect, findWhere
  6048. * @category Collections
  6049. * @param {Array|Object|string} collection The collection to iterate over.
  6050. * @param {Function|Object|string} [callback=identity] The function called
  6051. * per iteration. If a property name or object is provided it will be used
  6052. * to create a "_.pluck" or "_.where" style callback, respectively.
  6053. * @param {*} [thisArg] The `this` binding of `callback`.
  6054. * @returns {*} Returns the found element, else `undefined`.
  6055. * @example
  6056. *
  6057. * var characters = [
  6058. * { 'name': 'barney', 'age': 36, 'blocked': false },
  6059. * { 'name': 'fred', 'age': 40, 'blocked': true },
  6060. * { 'name': 'pebbles', 'age': 1, 'blocked': false }
  6061. * ];
  6062. *
  6063. * _.find(characters, function(chr) {
  6064. * return chr.age < 40;
  6065. * });
  6066. * // => { 'name': 'barney', 'age': 36, 'blocked': false }
  6067. *
  6068. * // using "_.where" callback shorthand
  6069. * _.find(characters, { 'age': 1 });
  6070. * // => { 'name': 'pebbles', 'age': 1, 'blocked': false }
  6071. *
  6072. * // using "_.pluck" callback shorthand
  6073. * _.find(characters, 'blocked');
  6074. * // => { 'name': 'fred', 'age': 40, 'blocked': true }
  6075. */
  6076. function find(collection, callback, thisArg) {
  6077. callback = lodash.createCallback(callback, thisArg, 3);
  6078. var index = -1,
  6079. length = collection ? collection.length : 0;
  6080. if (typeof length == 'number') {
  6081. while (++index < length) {
  6082. var value = collection[index];
  6083. if (callback(value, index, collection)) {
  6084. return value;
  6085. }
  6086. }
  6087. } else {
  6088. var result;
  6089. forOwn(collection, function(value, index, collection) {
  6090. if (callback(value, index, collection)) {
  6091. result = value;
  6092. return false;
  6093. }
  6094. });
  6095. return result;
  6096. }
  6097. }
  6098. /**
  6099. * This method is like `_.find` except that it iterates over elements
  6100. * of a `collection` from right to left.
  6101. *
  6102. * @static
  6103. * @memberOf _
  6104. * @category Collections
  6105. * @param {Array|Object|string} collection The collection to iterate over.
  6106. * @param {Function|Object|string} [callback=identity] The function called
  6107. * per iteration. If a property name or object is provided it will be used
  6108. * to create a "_.pluck" or "_.where" style callback, respectively.
  6109. * @param {*} [thisArg] The `this` binding of `callback`.
  6110. * @returns {*} Returns the found element, else `undefined`.
  6111. * @example
  6112. *
  6113. * _.findLast([1, 2, 3, 4], function(num) {
  6114. * return num % 2 == 1;
  6115. * });
  6116. * // => 3
  6117. */
  6118. function findLast(collection, callback, thisArg) {
  6119. var result;
  6120. callback = lodash.createCallback(callback, thisArg, 3);
  6121. forEachRight(collection, function(value, index, collection) {
  6122. if (callback(value, index, collection)) {
  6123. result = value;
  6124. return false;
  6125. }
  6126. });
  6127. return result;
  6128. }
  6129. /**
  6130. * Iterates over elements of a collection, executing the callback for each
  6131. * element. The callback is bound to `thisArg` and invoked with three arguments;
  6132. * (value, index|key, collection). Callbacks may exit iteration early by
  6133. * explicitly returning `false`.
  6134. *
  6135. * Note: As with other "Collections" methods, objects with a `length` property
  6136. * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
  6137. * may be used for object iteration.
  6138. *
  6139. * @static
  6140. * @memberOf _
  6141. * @alias each
  6142. * @category Collections
  6143. * @param {Array|Object|string} collection The collection to iterate over.
  6144. * @param {Function} [callback=identity] The function called per iteration.
  6145. * @param {*} [thisArg] The `this` binding of `callback`.
  6146. * @returns {Array|Object|string} Returns `collection`.
  6147. * @example
  6148. *
  6149. * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
  6150. * // => logs each number and returns '1,2,3'
  6151. *
  6152. * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
  6153. * // => logs each number and returns the object (property order is not guaranteed across environments)
  6154. */
  6155. function forEach(collection, callback, thisArg) {
  6156. var index = -1,
  6157. length = collection ? collection.length : 0;
  6158. callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
  6159. if (typeof length == 'number') {
  6160. while (++index < length) {
  6161. if (callback(collection[index], index, collection) === false) {
  6162. break;
  6163. }
  6164. }
  6165. } else {
  6166. forOwn(collection, callback);
  6167. }
  6168. return collection;
  6169. }
  6170. /**
  6171. * This method is like `_.forEach` except that it iterates over elements
  6172. * of a `collection` from right to left.
  6173. *
  6174. * @static
  6175. * @memberOf _
  6176. * @alias eachRight
  6177. * @category Collections
  6178. * @param {Array|Object|string} collection The collection to iterate over.
  6179. * @param {Function} [callback=identity] The function called per iteration.
  6180. * @param {*} [thisArg] The `this` binding of `callback`.
  6181. * @returns {Array|Object|string} Returns `collection`.
  6182. * @example
  6183. *
  6184. * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
  6185. * // => logs each number from right to left and returns '3,2,1'
  6186. */
  6187. function forEachRight(collection, callback, thisArg) {
  6188. var length = collection ? collection.length : 0;
  6189. callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
  6190. if (typeof length == 'number') {
  6191. while (length--) {
  6192. if (callback(collection[length], length, collection) === false) {
  6193. break;
  6194. }
  6195. }
  6196. } else {
  6197. var props = keys(collection);
  6198. length = props.length;
  6199. forOwn(collection, function(value, key, collection) {
  6200. key = props ? props[--length] : --length;
  6201. return callback(collection[key], key, collection);
  6202. });
  6203. }
  6204. return collection;
  6205. }
  6206. /**
  6207. * Creates an object composed of keys generated from the results of running
  6208. * each element of a collection through the callback. The corresponding value
  6209. * of each key is an array of the elements responsible for generating the key.
  6210. * The callback is bound to `thisArg` and invoked with three arguments;
  6211. * (value, index|key, collection).
  6212. *
  6213. * If a property name is provided for `callback` the created "_.pluck" style
  6214. * callback will return the property value of the given element.
  6215. *
  6216. * If an object is provided for `callback` the created "_.where" style callback
  6217. * will return `true` for elements that have the properties of the given object,
  6218. * else `false`
  6219. *
  6220. * @static
  6221. * @memberOf _
  6222. * @category Collections
  6223. * @param {Array|Object|string} collection The collection to iterate over.
  6224. * @param {Function|Object|string} [callback=identity] The function called
  6225. * per iteration. If a property name or object is provided it will be used
  6226. * to create a "_.pluck" or "_.where" style callback, respectively.
  6227. * @param {*} [thisArg] The `this` binding of `callback`.
  6228. * @returns {Object} Returns the composed aggregate object.
  6229. * @example
  6230. *
  6231. * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
  6232. * // => { '4': [4.2], '6': [6.1, 6.4] }
  6233. *
  6234. * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  6235. * // => { '4': [4.2], '6': [6.1, 6.4] }
  6236. *
  6237. * // using "_.pluck" callback shorthand
  6238. * _.groupBy(['one', 'two', 'three'], 'length');
  6239. * // => { '3': ['one', 'two'], '5': ['three'] }
  6240. */
  6241. var groupBy = createAggregator(function(result, value, key) {
  6242. (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
  6243. });
  6244. /**
  6245. * Creates an object composed of keys generated from the results of running
  6246. * each element of the collection through the given callback. The corresponding
  6247. * value of each key is the last element responsible for generating the key.
  6248. * The callback is bound to `thisArg` and invoked with three arguments;
  6249. * (value, index|key, collection).
  6250. *
  6251. * If a property name is provided for `callback` the created "_.pluck" style
  6252. * callback will return the property value of the given element.
  6253. *
  6254. * If an object is provided for `callback` the created "_.where" style callback
  6255. * will return `true` for elements that have the properties of the given object,
  6256. * else `false`.
  6257. *
  6258. * @static
  6259. * @memberOf _
  6260. * @category Collections
  6261. * @param {Array|Object|string} collection The collection to iterate over.
  6262. * @param {Function|Object|string} [callback=identity] The function called
  6263. * per iteration. If a property name or object is provided it will be used
  6264. * to create a "_.pluck" or "_.where" style callback, respectively.
  6265. * @param {*} [thisArg] The `this` binding of `callback`.
  6266. * @returns {Object} Returns the composed aggregate object.
  6267. * @example
  6268. *
  6269. * var keys = [
  6270. * { 'dir': 'left', 'code': 97 },
  6271. * { 'dir': 'right', 'code': 100 }
  6272. * ];
  6273. *
  6274. * _.indexBy(keys, 'dir');
  6275. * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
  6276. *
  6277. * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
  6278. * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
  6279. *
  6280. * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String);
  6281. * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
  6282. */
  6283. var indexBy = createAggregator(function(result, value, key) {
  6284. result[key] = value;
  6285. });
  6286. /**
  6287. * Invokes the method named by `methodName` on each element in the `collection`
  6288. * returning an array of the results of each invoked method. Additional arguments
  6289. * will be provided to each invoked method. If `methodName` is a function it
  6290. * will be invoked for, and `this` bound to, each element in the `collection`.
  6291. *
  6292. * @static
  6293. * @memberOf _
  6294. * @category Collections
  6295. * @param {Array|Object|string} collection The collection to iterate over.
  6296. * @param {Function|string} methodName The name of the method to invoke or
  6297. * the function invoked per iteration.
  6298. * @param {...*} [arg] Arguments to invoke the method with.
  6299. * @returns {Array} Returns a new array of the results of each invoked method.
  6300. * @example
  6301. *
  6302. * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  6303. * // => [[1, 5, 7], [1, 2, 3]]
  6304. *
  6305. * _.invoke([123, 456], String.prototype.split, '');
  6306. * // => [['1', '2', '3'], ['4', '5', '6']]
  6307. */
  6308. function invoke(collection, methodName) {
  6309. var args = slice(arguments, 2),
  6310. index = -1,
  6311. isFunc = typeof methodName == 'function',
  6312. length = collection ? collection.length : 0,
  6313. result = Array(typeof length == 'number' ? length : 0);
  6314. forEach(collection, function(value) {
  6315. result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
  6316. });
  6317. return result;
  6318. }
  6319. /**
  6320. * Creates an array of values by running each element in the collection
  6321. * through the callback. The callback is bound to `thisArg` and invoked with
  6322. * three arguments; (value, index|key, collection).
  6323. *
  6324. * If a property name is provided for `callback` the created "_.pluck" style
  6325. * callback will return the property value of the given element.
  6326. *
  6327. * If an object is provided for `callback` the created "_.where" style callback
  6328. * will return `true` for elements that have the properties of the given object,
  6329. * else `false`.
  6330. *
  6331. * @static
  6332. * @memberOf _
  6333. * @alias collect
  6334. * @category Collections
  6335. * @param {Array|Object|string} collection The collection to iterate over.
  6336. * @param {Function|Object|string} [callback=identity] The function called
  6337. * per iteration. If a property name or object is provided it will be used
  6338. * to create a "_.pluck" or "_.where" style callback, respectively.
  6339. * @param {*} [thisArg] The `this` binding of `callback`.
  6340. * @returns {Array} Returns a new array of the results of each `callback` execution.
  6341. * @example
  6342. *
  6343. * _.map([1, 2, 3], function(num) { return num * 3; });
  6344. * // => [3, 6, 9]
  6345. *
  6346. * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
  6347. * // => [3, 6, 9] (property order is not guaranteed across environments)
  6348. *
  6349. * var characters = [
  6350. * { 'name': 'barney', 'age': 36 },
  6351. * { 'name': 'fred', 'age': 40 }
  6352. * ];
  6353. *
  6354. * // using "_.pluck" callback shorthand
  6355. * _.map(characters, 'name');
  6356. * // => ['barney', 'fred']
  6357. */
  6358. function map(collection, callback, thisArg) {
  6359. var index = -1,
  6360. length = collection ? collection.length : 0;
  6361. callback = lodash.createCallback(callback, thisArg, 3);
  6362. if (typeof length == 'number') {
  6363. var result = Array(length);
  6364. while (++index < length) {
  6365. result[index] = callback(collection[index], index, collection);
  6366. }
  6367. } else {
  6368. result = [];
  6369. forOwn(collection, function(value, key, collection) {
  6370. result[++index] = callback(value, key, collection);
  6371. });
  6372. }
  6373. return result;
  6374. }
  6375. /**
  6376. * Retrieves the maximum value of a collection. If the collection is empty or
  6377. * falsey `-Infinity` is returned. If a callback is provided it will be executed
  6378. * for each value in the collection to generate the criterion by which the value
  6379. * is ranked. The callback is bound to `thisArg` and invoked with three
  6380. * arguments; (value, index, collection).
  6381. *
  6382. * If a property name is provided for `callback` the created "_.pluck" style
  6383. * callback will return the property value of the given element.
  6384. *
  6385. * If an object is provided for `callback` the created "_.where" style callback
  6386. * will return `true` for elements that have the properties of the given object,
  6387. * else `false`.
  6388. *
  6389. * @static
  6390. * @memberOf _
  6391. * @category Collections
  6392. * @param {Array|Object|string} collection The collection to iterate over.
  6393. * @param {Function|Object|string} [callback=identity] The function called
  6394. * per iteration. If a property name or object is provided it will be used
  6395. * to create a "_.pluck" or "_.where" style callback, respectively.
  6396. * @param {*} [thisArg] The `this` binding of `callback`.
  6397. * @returns {*} Returns the maximum value.
  6398. * @example
  6399. *
  6400. * _.max([4, 2, 8, 6]);
  6401. * // => 8
  6402. *
  6403. * var characters = [
  6404. * { 'name': 'barney', 'age': 36 },
  6405. * { 'name': 'fred', 'age': 40 }
  6406. * ];
  6407. *
  6408. * _.max(characters, function(chr) { return chr.age; });
  6409. * // => { 'name': 'fred', 'age': 40 };
  6410. *
  6411. * // using "_.pluck" callback shorthand
  6412. * _.max(characters, 'age');
  6413. * // => { 'name': 'fred', 'age': 40 };
  6414. */
  6415. function max(collection, callback, thisArg) {
  6416. var computed = -Infinity,
  6417. result = computed;
  6418. // allows working with functions like `_.map` without using
  6419. // their `index` argument as a callback
  6420. if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
  6421. callback = null;
  6422. }
  6423. if (callback == null && isArray(collection)) {
  6424. var index = -1,
  6425. length = collection.length;
  6426. while (++index < length) {
  6427. var value = collection[index];
  6428. if (value > result) {
  6429. result = value;
  6430. }
  6431. }
  6432. } else {
  6433. callback = (callback == null && isString(collection))
  6434. ? charAtCallback
  6435. : lodash.createCallback(callback, thisArg, 3);
  6436. forEach(collection, function(value, index, collection) {
  6437. var current = callback(value, index, collection);
  6438. if (current > computed) {
  6439. computed = current;
  6440. result = value;
  6441. }
  6442. });
  6443. }
  6444. return result;
  6445. }
  6446. /**
  6447. * Retrieves the minimum value of a collection. If the collection is empty or
  6448. * falsey `Infinity` is returned. If a callback is provided it will be executed
  6449. * for each value in the collection to generate the criterion by which the value
  6450. * is ranked. The callback is bound to `thisArg` and invoked with three
  6451. * arguments; (value, index, collection).
  6452. *
  6453. * If a property name is provided for `callback` the created "_.pluck" style
  6454. * callback will return the property value of the given element.
  6455. *
  6456. * If an object is provided for `callback` the created "_.where" style callback
  6457. * will return `true` for elements that have the properties of the given object,
  6458. * else `false`.
  6459. *
  6460. * @static
  6461. * @memberOf _
  6462. * @category Collections
  6463. * @param {Array|Object|string} collection The collection to iterate over.
  6464. * @param {Function|Object|string} [callback=identity] The function called
  6465. * per iteration. If a property name or object is provided it will be used
  6466. * to create a "_.pluck" or "_.where" style callback, respectively.
  6467. * @param {*} [thisArg] The `this` binding of `callback`.
  6468. * @returns {*} Returns the minimum value.
  6469. * @example
  6470. *
  6471. * _.min([4, 2, 8, 6]);
  6472. * // => 2
  6473. *
  6474. * var characters = [
  6475. * { 'name': 'barney', 'age': 36 },
  6476. * { 'name': 'fred', 'age': 40 }
  6477. * ];
  6478. *
  6479. * _.min(characters, function(chr) { return chr.age; });
  6480. * // => { 'name': 'barney', 'age': 36 };
  6481. *
  6482. * // using "_.pluck" callback shorthand
  6483. * _.min(characters, 'age');
  6484. * // => { 'name': 'barney', 'age': 36 };
  6485. */
  6486. function min(collection, callback, thisArg) {
  6487. var computed = Infinity,
  6488. result = computed;
  6489. // allows working with functions like `_.map` without using
  6490. // their `index` argument as a callback
  6491. if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
  6492. callback = null;
  6493. }
  6494. if (callback == null && isArray(collection)) {
  6495. var index = -1,
  6496. length = collection.length;
  6497. while (++index < length) {
  6498. var value = collection[index];
  6499. if (value < result) {
  6500. result = value;
  6501. }
  6502. }
  6503. } else {
  6504. callback = (callback == null && isString(collection))
  6505. ? charAtCallback
  6506. : lodash.createCallback(callback, thisArg, 3);
  6507. forEach(collection, function(value, index, collection) {
  6508. var current = callback(value, index, collection);
  6509. if (current < computed) {
  6510. computed = current;
  6511. result = value;
  6512. }
  6513. });
  6514. }
  6515. return result;
  6516. }
  6517. /**
  6518. * Retrieves the value of a specified property from all elements in the collection.
  6519. *
  6520. * @static
  6521. * @memberOf _
  6522. * @type Function
  6523. * @category Collections
  6524. * @param {Array|Object|string} collection The collection to iterate over.
  6525. * @param {string} property The name of the property to pluck.
  6526. * @returns {Array} Returns a new array of property values.
  6527. * @example
  6528. *
  6529. * var characters = [
  6530. * { 'name': 'barney', 'age': 36 },
  6531. * { 'name': 'fred', 'age': 40 }
  6532. * ];
  6533. *
  6534. * _.pluck(characters, 'name');
  6535. * // => ['barney', 'fred']
  6536. */
  6537. var pluck = map;
  6538. /**
  6539. * Reduces a collection to a value which is the accumulated result of running
  6540. * each element in the collection through the callback, where each successive
  6541. * callback execution consumes the return value of the previous execution. If
  6542. * `accumulator` is not provided the first element of the collection will be
  6543. * used as the initial `accumulator` value. The callback is bound to `thisArg`
  6544. * and invoked with four arguments; (accumulator, value, index|key, collection).
  6545. *
  6546. * @static
  6547. * @memberOf _
  6548. * @alias foldl, inject
  6549. * @category Collections
  6550. * @param {Array|Object|string} collection The collection to iterate over.
  6551. * @param {Function} [callback=identity] The function called per iteration.
  6552. * @param {*} [accumulator] Initial value of the accumulator.
  6553. * @param {*} [thisArg] The `this` binding of `callback`.
  6554. * @returns {*} Returns the accumulated value.
  6555. * @example
  6556. *
  6557. * var sum = _.reduce([1, 2, 3], function(sum, num) {
  6558. * return sum + num;
  6559. * });
  6560. * // => 6
  6561. *
  6562. * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
  6563. * result[key] = num * 3;
  6564. * return result;
  6565. * }, {});
  6566. * // => { 'a': 3, 'b': 6, 'c': 9 }
  6567. */
  6568. function reduce(collection, callback, accumulator, thisArg) {
  6569. if (!collection) return accumulator;
  6570. var noaccum = arguments.length < 3;
  6571. callback = lodash.createCallback(callback, thisArg, 4);
  6572. var index = -1,
  6573. length = collection.length;
  6574. if (typeof length == 'number') {
  6575. if (noaccum) {
  6576. accumulator = collection[++index];
  6577. }
  6578. while (++index < length) {
  6579. accumulator = callback(accumulator, collection[index], index, collection);
  6580. }
  6581. } else {
  6582. forOwn(collection, function(value, index, collection) {
  6583. accumulator = noaccum
  6584. ? (noaccum = false, value)
  6585. : callback(accumulator, value, index, collection)
  6586. });
  6587. }
  6588. return accumulator;
  6589. }
  6590. /**
  6591. * This method is like `_.reduce` except that it iterates over elements
  6592. * of a `collection` from right to left.
  6593. *
  6594. * @static
  6595. * @memberOf _
  6596. * @alias foldr
  6597. * @category Collections
  6598. * @param {Array|Object|string} collection The collection to iterate over.
  6599. * @param {Function} [callback=identity] The function called per iteration.
  6600. * @param {*} [accumulator] Initial value of the accumulator.
  6601. * @param {*} [thisArg] The `this` binding of `callback`.
  6602. * @returns {*} Returns the accumulated value.
  6603. * @example
  6604. *
  6605. * var list = [[0, 1], [2, 3], [4, 5]];
  6606. * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  6607. * // => [4, 5, 2, 3, 0, 1]
  6608. */
  6609. function reduceRight(collection, callback, accumulator, thisArg) {
  6610. var noaccum = arguments.length < 3;
  6611. callback = lodash.createCallback(callback, thisArg, 4);
  6612. forEachRight(collection, function(value, index, collection) {
  6613. accumulator = noaccum
  6614. ? (noaccum = false, value)
  6615. : callback(accumulator, value, index, collection);
  6616. });
  6617. return accumulator;
  6618. }
  6619. /**
  6620. * The opposite of `_.filter` this method returns the elements of a
  6621. * collection that the callback does **not** return truey for.
  6622. *
  6623. * If a property name is provided for `callback` the created "_.pluck" style
  6624. * callback will return the property value of the given element.
  6625. *
  6626. * If an object is provided for `callback` the created "_.where" style callback
  6627. * will return `true` for elements that have the properties of the given object,
  6628. * else `false`.
  6629. *
  6630. * @static
  6631. * @memberOf _
  6632. * @category Collections
  6633. * @param {Array|Object|string} collection The collection to iterate over.
  6634. * @param {Function|Object|string} [callback=identity] The function called
  6635. * per iteration. If a property name or object is provided it will be used
  6636. * to create a "_.pluck" or "_.where" style callback, respectively.
  6637. * @param {*} [thisArg] The `this` binding of `callback`.
  6638. * @returns {Array} Returns a new array of elements that failed the callback check.
  6639. * @example
  6640. *
  6641. * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  6642. * // => [1, 3, 5]
  6643. *
  6644. * var characters = [
  6645. * { 'name': 'barney', 'age': 36, 'blocked': false },
  6646. * { 'name': 'fred', 'age': 40, 'blocked': true }
  6647. * ];
  6648. *
  6649. * // using "_.pluck" callback shorthand
  6650. * _.reject(characters, 'blocked');
  6651. * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
  6652. *
  6653. * // using "_.where" callback shorthand
  6654. * _.reject(characters, { 'age': 36 });
  6655. * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
  6656. */
  6657. function reject(collection, callback, thisArg) {
  6658. callback = lodash.createCallback(callback, thisArg, 3);
  6659. return filter(collection, function(value, index, collection) {
  6660. return !callback(value, index, collection);
  6661. });
  6662. }
  6663. /**
  6664. * Retrieves a random element or `n` random elements from a collection.
  6665. *
  6666. * @static
  6667. * @memberOf _
  6668. * @category Collections
  6669. * @param {Array|Object|string} collection The collection to sample.
  6670. * @param {number} [n] The number of elements to sample.
  6671. * @param- {Object} [guard] Allows working with functions like `_.map`
  6672. * without using their `index` arguments as `n`.
  6673. * @returns {Array} Returns the random sample(s) of `collection`.
  6674. * @example
  6675. *
  6676. * _.sample([1, 2, 3, 4]);
  6677. * // => 2
  6678. *
  6679. * _.sample([1, 2, 3, 4], 2);
  6680. * // => [3, 1]
  6681. */
  6682. function sample(collection, n, guard) {
  6683. if (collection && typeof collection.length != 'number') {
  6684. collection = values(collection);
  6685. }
  6686. if (n == null || guard) {
  6687. return collection ? collection[baseRandom(0, collection.length - 1)] : undefined;
  6688. }
  6689. var result = shuffle(collection);
  6690. result.length = nativeMin(nativeMax(0, n), result.length);
  6691. return result;
  6692. }
  6693. /**
  6694. * Creates an array of shuffled values, using a version of the Fisher-Yates
  6695. * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
  6696. *
  6697. * @static
  6698. * @memberOf _
  6699. * @category Collections
  6700. * @param {Array|Object|string} collection The collection to shuffle.
  6701. * @returns {Array} Returns a new shuffled collection.
  6702. * @example
  6703. *
  6704. * _.shuffle([1, 2, 3, 4, 5, 6]);
  6705. * // => [4, 1, 6, 3, 5, 2]
  6706. */
  6707. function shuffle(collection) {
  6708. var index = -1,
  6709. length = collection ? collection.length : 0,
  6710. result = Array(typeof length == 'number' ? length : 0);
  6711. forEach(collection, function(value) {
  6712. var rand = baseRandom(0, ++index);
  6713. result[index] = result[rand];
  6714. result[rand] = value;
  6715. });
  6716. return result;
  6717. }
  6718. /**
  6719. * Gets the size of the `collection` by returning `collection.length` for arrays
  6720. * and array-like objects or the number of own enumerable properties for objects.
  6721. *
  6722. * @static
  6723. * @memberOf _
  6724. * @category Collections
  6725. * @param {Array|Object|string} collection The collection to inspect.
  6726. * @returns {number} Returns `collection.length` or number of own enumerable properties.
  6727. * @example
  6728. *
  6729. * _.size([1, 2]);
  6730. * // => 2
  6731. *
  6732. * _.size({ 'one': 1, 'two': 2, 'three': 3 });
  6733. * // => 3
  6734. *
  6735. * _.size('pebbles');
  6736. * // => 7
  6737. */
  6738. function size(collection) {
  6739. var length = collection ? collection.length : 0;
  6740. return typeof length == 'number' ? length : keys(collection).length;
  6741. }
  6742. /**
  6743. * Checks if the callback returns a truey value for **any** element of a
  6744. * collection. The function returns as soon as it finds a passing value and
  6745. * does not iterate over the entire collection. The callback is bound to
  6746. * `thisArg` and invoked with three arguments; (value, index|key, collection).
  6747. *
  6748. * If a property name is provided for `callback` the created "_.pluck" style
  6749. * callback will return the property value of the given element.
  6750. *
  6751. * If an object is provided for `callback` the created "_.where" style callback
  6752. * will return `true` for elements that have the properties of the given object,
  6753. * else `false`.
  6754. *
  6755. * @static
  6756. * @memberOf _
  6757. * @alias any
  6758. * @category Collections
  6759. * @param {Array|Object|string} collection The collection to iterate over.
  6760. * @param {Function|Object|string} [callback=identity] The function called
  6761. * per iteration. If a property name or object is provided it will be used
  6762. * to create a "_.pluck" or "_.where" style callback, respectively.
  6763. * @param {*} [thisArg] The `this` binding of `callback`.
  6764. * @returns {boolean} Returns `true` if any element passed the callback check,
  6765. * else `false`.
  6766. * @example
  6767. *
  6768. * _.some([null, 0, 'yes', false], Boolean);
  6769. * // => true
  6770. *
  6771. * var characters = [
  6772. * { 'name': 'barney', 'age': 36, 'blocked': false },
  6773. * { 'name': 'fred', 'age': 40, 'blocked': true }
  6774. * ];
  6775. *
  6776. * // using "_.pluck" callback shorthand
  6777. * _.some(characters, 'blocked');
  6778. * // => true
  6779. *
  6780. * // using "_.where" callback shorthand
  6781. * _.some(characters, { 'age': 1 });
  6782. * // => false
  6783. */
  6784. function some(collection, callback, thisArg) {
  6785. var result;
  6786. callback = lodash.createCallback(callback, thisArg, 3);
  6787. var index = -1,
  6788. length = collection ? collection.length : 0;
  6789. if (typeof length == 'number') {
  6790. while (++index < length) {
  6791. if ((result = callback(collection[index], index, collection))) {
  6792. break;
  6793. }
  6794. }
  6795. } else {
  6796. forOwn(collection, function(value, index, collection) {
  6797. return !(result = callback(value, index, collection));
  6798. });
  6799. }
  6800. return !!result;
  6801. }
  6802. /**
  6803. * Creates an array of elements, sorted in ascending order by the results of
  6804. * running each element in a collection through the callback. This method
  6805. * performs a stable sort, that is, it will preserve the original sort order
  6806. * of equal elements. The callback is bound to `thisArg` and invoked with
  6807. * three arguments; (value, index|key, collection).
  6808. *
  6809. * If a property name is provided for `callback` the created "_.pluck" style
  6810. * callback will return the property value of the given element.
  6811. *
  6812. * If an array of property names is provided for `callback` the collection
  6813. * will be sorted by each property value.
  6814. *
  6815. * If an object is provided for `callback` the created "_.where" style callback
  6816. * will return `true` for elements that have the properties of the given object,
  6817. * else `false`.
  6818. *
  6819. * @static
  6820. * @memberOf _
  6821. * @category Collections
  6822. * @param {Array|Object|string} collection The collection to iterate over.
  6823. * @param {Array|Function|Object|string} [callback=identity] The function called
  6824. * per iteration. If a property name or object is provided it will be used
  6825. * to create a "_.pluck" or "_.where" style callback, respectively.
  6826. * @param {*} [thisArg] The `this` binding of `callback`.
  6827. * @returns {Array} Returns a new array of sorted elements.
  6828. * @example
  6829. *
  6830. * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
  6831. * // => [3, 1, 2]
  6832. *
  6833. * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
  6834. * // => [3, 1, 2]
  6835. *
  6836. * var characters = [
  6837. * { 'name': 'barney', 'age': 36 },
  6838. * { 'name': 'fred', 'age': 40 },
  6839. * { 'name': 'barney', 'age': 26 },
  6840. * { 'name': 'fred', 'age': 30 }
  6841. * ];
  6842. *
  6843. * // using "_.pluck" callback shorthand
  6844. * _.map(_.sortBy(characters, 'age'), _.values);
  6845. * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]]
  6846. *
  6847. * // sorting by multiple properties
  6848. * _.map(_.sortBy(characters, ['name', 'age']), _.values);
  6849. * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
  6850. */
  6851. function sortBy(collection, callback, thisArg) {
  6852. var index = -1,
  6853. isArr = isArray(callback),
  6854. length = collection ? collection.length : 0,
  6855. result = Array(typeof length == 'number' ? length : 0);
  6856. if (!isArr) {
  6857. callback = lodash.createCallback(callback, thisArg, 3);
  6858. }
  6859. forEach(collection, function(value, key, collection) {
  6860. var object = result[++index] = getObject();
  6861. if (isArr) {
  6862. object.criteria = map(callback, function(key) { return value[key]; });
  6863. } else {
  6864. (object.criteria = getArray())[0] = callback(value, key, collection);
  6865. }
  6866. object.index = index;
  6867. object.value = value;
  6868. });
  6869. length = result.length;
  6870. result.sort(compareAscending);
  6871. while (length--) {
  6872. var object = result[length];
  6873. result[length] = object.value;
  6874. if (!isArr) {
  6875. releaseArray(object.criteria);
  6876. }
  6877. releaseObject(object);
  6878. }
  6879. return result;
  6880. }
  6881. /**
  6882. * Converts the `collection` to an array.
  6883. *
  6884. * @static
  6885. * @memberOf _
  6886. * @category Collections
  6887. * @param {Array|Object|string} collection The collection to convert.
  6888. * @returns {Array} Returns the new converted array.
  6889. * @example
  6890. *
  6891. * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
  6892. * // => [2, 3, 4]
  6893. */
  6894. function toArray(collection) {
  6895. if (collection && typeof collection.length == 'number') {
  6896. return slice(collection);
  6897. }
  6898. return values(collection);
  6899. }
  6900. /**
  6901. * Performs a deep comparison of each element in a `collection` to the given
  6902. * `properties` object, returning an array of all elements that have equivalent
  6903. * property values.
  6904. *
  6905. * @static
  6906. * @memberOf _
  6907. * @type Function
  6908. * @category Collections
  6909. * @param {Array|Object|string} collection The collection to iterate over.
  6910. * @param {Object} props The object of property values to filter by.
  6911. * @returns {Array} Returns a new array of elements that have the given properties.
  6912. * @example
  6913. *
  6914. * var characters = [
  6915. * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
  6916. * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
  6917. * ];
  6918. *
  6919. * _.where(characters, { 'age': 36 });
  6920. * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }]
  6921. *
  6922. * _.where(characters, { 'pets': ['dino'] });
  6923. * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]
  6924. */
  6925. var where = filter;
  6926. /*--------------------------------------------------------------------------*/
  6927. /**
  6928. * Creates an array with all falsey values removed. The values `false`, `null`,
  6929. * `0`, `""`, `undefined`, and `NaN` are all falsey.
  6930. *
  6931. * @static
  6932. * @memberOf _
  6933. * @category Arrays
  6934. * @param {Array} array The array to compact.
  6935. * @returns {Array} Returns a new array of filtered values.
  6936. * @example
  6937. *
  6938. * _.compact([0, 1, false, 2, '', 3]);
  6939. * // => [1, 2, 3]
  6940. */
  6941. function compact(array) {
  6942. var index = -1,
  6943. length = array ? array.length : 0,
  6944. result = [];
  6945. while (++index < length) {
  6946. var value = array[index];
  6947. if (value) {
  6948. result.push(value);
  6949. }
  6950. }
  6951. return result;
  6952. }
  6953. /**
  6954. * Creates an array excluding all values of the provided arrays using strict
  6955. * equality for comparisons, i.e. `===`.
  6956. *
  6957. * @static
  6958. * @memberOf _
  6959. * @category Arrays
  6960. * @param {Array} array The array to process.
  6961. * @param {...Array} [values] The arrays of values to exclude.
  6962. * @returns {Array} Returns a new array of filtered values.
  6963. * @example
  6964. *
  6965. * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
  6966. * // => [1, 3, 4]
  6967. */
  6968. function difference(array) {
  6969. return baseDifference(array, baseFlatten(arguments, true, true, 1));
  6970. }
  6971. /**
  6972. * This method is like `_.find` except that it returns the index of the first
  6973. * element that passes the callback check, instead of the element itself.
  6974. *
  6975. * If a property name is provided for `callback` the created "_.pluck" style
  6976. * callback will return the property value of the given element.
  6977. *
  6978. * If an object is provided for `callback` the created "_.where" style callback
  6979. * will return `true` for elements that have the properties of the given object,
  6980. * else `false`.
  6981. *
  6982. * @static
  6983. * @memberOf _
  6984. * @category Arrays
  6985. * @param {Array} array The array to search.
  6986. * @param {Function|Object|string} [callback=identity] The function called
  6987. * per iteration. If a property name or object is provided it will be used
  6988. * to create a "_.pluck" or "_.where" style callback, respectively.
  6989. * @param {*} [thisArg] The `this` binding of `callback`.
  6990. * @returns {number} Returns the index of the found element, else `-1`.
  6991. * @example
  6992. *
  6993. * var characters = [
  6994. * { 'name': 'barney', 'age': 36, 'blocked': false },
  6995. * { 'name': 'fred', 'age': 40, 'blocked': true },
  6996. * { 'name': 'pebbles', 'age': 1, 'blocked': false }
  6997. * ];
  6998. *
  6999. * _.findIndex(characters, function(chr) {
  7000. * return chr.age < 20;
  7001. * });
  7002. * // => 2
  7003. *
  7004. * // using "_.where" callback shorthand
  7005. * _.findIndex(characters, { 'age': 36 });
  7006. * // => 0
  7007. *
  7008. * // using "_.pluck" callback shorthand
  7009. * _.findIndex(characters, 'blocked');
  7010. * // => 1
  7011. */
  7012. function findIndex(array, callback, thisArg) {
  7013. var index = -1,
  7014. length = array ? array.length : 0;
  7015. callback = lodash.createCallback(callback, thisArg, 3);
  7016. while (++index < length) {
  7017. if (callback(array[index], index, array)) {
  7018. return index;
  7019. }
  7020. }
  7021. return -1;
  7022. }
  7023. /**
  7024. * This method is like `_.findIndex` except that it iterates over elements
  7025. * of a `collection` from right to left.
  7026. *
  7027. * If a property name is provided for `callback` the created "_.pluck" style
  7028. * callback will return the property value of the given element.
  7029. *
  7030. * If an object is provided for `callback` the created "_.where" style callback
  7031. * will return `true` for elements that have the properties of the given object,
  7032. * else `false`.
  7033. *
  7034. * @static
  7035. * @memberOf _
  7036. * @category Arrays
  7037. * @param {Array} array The array to search.
  7038. * @param {Function|Object|string} [callback=identity] The function called
  7039. * per iteration. If a property name or object is provided it will be used
  7040. * to create a "_.pluck" or "_.where" style callback, respectively.
  7041. * @param {*} [thisArg] The `this` binding of `callback`.
  7042. * @returns {number} Returns the index of the found element, else `-1`.
  7043. * @example
  7044. *
  7045. * var characters = [
  7046. * { 'name': 'barney', 'age': 36, 'blocked': true },
  7047. * { 'name': 'fred', 'age': 40, 'blocked': false },
  7048. * { 'name': 'pebbles', 'age': 1, 'blocked': true }
  7049. * ];
  7050. *
  7051. * _.findLastIndex(characters, function(chr) {
  7052. * return chr.age > 30;
  7053. * });
  7054. * // => 1
  7055. *
  7056. * // using "_.where" callback shorthand
  7057. * _.findLastIndex(characters, { 'age': 36 });
  7058. * // => 0
  7059. *
  7060. * // using "_.pluck" callback shorthand
  7061. * _.findLastIndex(characters, 'blocked');
  7062. * // => 2
  7063. */
  7064. function findLastIndex(array, callback, thisArg) {
  7065. var length = array ? array.length : 0;
  7066. callback = lodash.createCallback(callback, thisArg, 3);
  7067. while (length--) {
  7068. if (callback(array[length], length, array)) {
  7069. return length;
  7070. }
  7071. }
  7072. return -1;
  7073. }
  7074. /**
  7075. * Gets the first element or first `n` elements of an array. If a callback
  7076. * is provided elements at the beginning of the array are returned as long
  7077. * as the callback returns truey. The callback is bound to `thisArg` and
  7078. * invoked with three arguments; (value, index, array).
  7079. *
  7080. * If a property name is provided for `callback` the created "_.pluck" style
  7081. * callback will return the property value of the given element.
  7082. *
  7083. * If an object is provided for `callback` the created "_.where" style callback
  7084. * will return `true` for elements that have the properties of the given object,
  7085. * else `false`.
  7086. *
  7087. * @static
  7088. * @memberOf _
  7089. * @alias head, take
  7090. * @category Arrays
  7091. * @param {Array} array The array to query.
  7092. * @param {Function|Object|number|string} [callback] The function called
  7093. * per element or the number of elements to return. If a property name or
  7094. * object is provided it will be used to create a "_.pluck" or "_.where"
  7095. * style callback, respectively.
  7096. * @param {*} [thisArg] The `this` binding of `callback`.
  7097. * @returns {*} Returns the first element(s) of `array`.
  7098. * @example
  7099. *
  7100. * _.first([1, 2, 3]);
  7101. * // => 1
  7102. *
  7103. * _.first([1, 2, 3], 2);
  7104. * // => [1, 2]
  7105. *
  7106. * _.first([1, 2, 3], function(num) {
  7107. * return num < 3;
  7108. * });
  7109. * // => [1, 2]
  7110. *
  7111. * var characters = [
  7112. * { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
  7113. * { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
  7114. * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
  7115. * ];
  7116. *
  7117. * // using "_.pluck" callback shorthand
  7118. * _.first(characters, 'blocked');
  7119. * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }]
  7120. *
  7121. * // using "_.where" callback shorthand
  7122. * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name');
  7123. * // => ['barney', 'fred']
  7124. */
  7125. function first(array, callback, thisArg) {
  7126. var n = 0,
  7127. length = array ? array.length : 0;
  7128. if (typeof callback != 'number' && callback != null) {
  7129. var index = -1;
  7130. callback = lodash.createCallback(callback, thisArg, 3);
  7131. while (++index < length && callback(array[index], index, array)) {
  7132. n++;
  7133. }
  7134. } else {
  7135. n = callback;
  7136. if (n == null || thisArg) {
  7137. return array ? array[0] : undefined;
  7138. }
  7139. }
  7140. return slice(array, 0, nativeMin(nativeMax(0, n), length));
  7141. }
  7142. /**
  7143. * Flattens a nested array (the nesting can be to any depth). If `isShallow`
  7144. * is truey, the array will only be flattened a single level. If a callback
  7145. * is provided each element of the array is passed through the callback before
  7146. * flattening. The callback is bound to `thisArg` and invoked with three
  7147. * arguments; (value, index, array).
  7148. *
  7149. * If a property name is provided for `callback` the created "_.pluck" style
  7150. * callback will return the property value of the given element.
  7151. *
  7152. * If an object is provided for `callback` the created "_.where" style callback
  7153. * will return `true` for elements that have the properties of the given object,
  7154. * else `false`.
  7155. *
  7156. * @static
  7157. * @memberOf _
  7158. * @category Arrays
  7159. * @param {Array} array The array to flatten.
  7160. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
  7161. * @param {Function|Object|string} [callback=identity] The function called
  7162. * per iteration. If a property name or object is provided it will be used
  7163. * to create a "_.pluck" or "_.where" style callback, respectively.
  7164. * @param {*} [thisArg] The `this` binding of `callback`.
  7165. * @returns {Array} Returns a new flattened array.
  7166. * @example
  7167. *
  7168. * _.flatten([1, [2], [3, [[4]]]]);
  7169. * // => [1, 2, 3, 4];
  7170. *
  7171. * _.flatten([1, [2], [3, [[4]]]], true);
  7172. * // => [1, 2, 3, [[4]]];
  7173. *
  7174. * var characters = [
  7175. * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] },
  7176. * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
  7177. * ];
  7178. *
  7179. * // using "_.pluck" callback shorthand
  7180. * _.flatten(characters, 'pets');
  7181. * // => ['hoppy', 'baby puss', 'dino']
  7182. */
  7183. function flatten(array, isShallow, callback, thisArg) {
  7184. // juggle arguments
  7185. if (typeof isShallow != 'boolean' && isShallow != null) {
  7186. thisArg = callback;
  7187. callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow;
  7188. isShallow = false;
  7189. }
  7190. if (callback != null) {
  7191. array = map(array, callback, thisArg);
  7192. }
  7193. return baseFlatten(array, isShallow);
  7194. }
  7195. /**
  7196. * Gets the index at which the first occurrence of `value` is found using
  7197. * strict equality for comparisons, i.e. `===`. If the array is already sorted
  7198. * providing `true` for `fromIndex` will run a faster binary search.
  7199. *
  7200. * @static
  7201. * @memberOf _
  7202. * @category Arrays
  7203. * @param {Array} array The array to search.
  7204. * @param {*} value The value to search for.
  7205. * @param {boolean|number} [fromIndex=0] The index to search from or `true`
  7206. * to perform a binary search on a sorted array.
  7207. * @returns {number} Returns the index of the matched value or `-1`.
  7208. * @example
  7209. *
  7210. * _.indexOf([1, 2, 3, 1, 2, 3], 2);
  7211. * // => 1
  7212. *
  7213. * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
  7214. * // => 4
  7215. *
  7216. * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
  7217. * // => 2
  7218. */
  7219. function indexOf(array, value, fromIndex) {
  7220. if (typeof fromIndex == 'number') {
  7221. var length = array ? array.length : 0;
  7222. fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
  7223. } else if (fromIndex) {
  7224. var index = sortedIndex(array, value);
  7225. return array[index] === value ? index : -1;
  7226. }
  7227. return baseIndexOf(array, value, fromIndex);
  7228. }
  7229. /**
  7230. * Gets all but the last element or last `n` elements of an array. If a
  7231. * callback is provided elements at the end of the array are excluded from
  7232. * the result as long as the callback returns truey. The callback is bound
  7233. * to `thisArg` and invoked with three arguments; (value, index, array).
  7234. *
  7235. * If a property name is provided for `callback` the created "_.pluck" style
  7236. * callback will return the property value of the given element.
  7237. *
  7238. * If an object is provided for `callback` the created "_.where" style callback
  7239. * will return `true` for elements that have the properties of the given object,
  7240. * else `false`.
  7241. *
  7242. * @static
  7243. * @memberOf _
  7244. * @category Arrays
  7245. * @param {Array} array The array to query.
  7246. * @param {Function|Object|number|string} [callback=1] The function called
  7247. * per element or the number of elements to exclude. If a property name or
  7248. * object is provided it will be used to create a "_.pluck" or "_.where"
  7249. * style callback, respectively.
  7250. * @param {*} [thisArg] The `this` binding of `callback`.
  7251. * @returns {Array} Returns a slice of `array`.
  7252. * @example
  7253. *
  7254. * _.initial([1, 2, 3]);
  7255. * // => [1, 2]
  7256. *
  7257. * _.initial([1, 2, 3], 2);
  7258. * // => [1]
  7259. *
  7260. * _.initial([1, 2, 3], function(num) {
  7261. * return num > 1;
  7262. * });
  7263. * // => [1]
  7264. *
  7265. * var characters = [
  7266. * { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
  7267. * { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
  7268. * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
  7269. * ];
  7270. *
  7271. * // using "_.pluck" callback shorthand
  7272. * _.initial(characters, 'blocked');
  7273. * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }]
  7274. *
  7275. * // using "_.where" callback shorthand
  7276. * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name');
  7277. * // => ['barney', 'fred']
  7278. */
  7279. function initial(array, callback, thisArg) {
  7280. var n = 0,
  7281. length = array ? array.length : 0;
  7282. if (typeof callback != 'number' && callback != null) {
  7283. var index = length;
  7284. callback = lodash.createCallback(callback, thisArg, 3);
  7285. while (index-- && callback(array[index], index, array)) {
  7286. n++;
  7287. }
  7288. } else {
  7289. n = (callback == null || thisArg) ? 1 : callback || n;
  7290. }
  7291. return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
  7292. }
  7293. /**
  7294. * Creates an array of unique values present in all provided arrays using
  7295. * strict equality for comparisons, i.e. `===`.
  7296. *
  7297. * @static
  7298. * @memberOf _
  7299. * @category Arrays
  7300. * @param {...Array} [array] The arrays to inspect.
  7301. * @returns {Array} Returns an array of shared values.
  7302. * @example
  7303. *
  7304. * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
  7305. * // => [1, 2]
  7306. */
  7307. function intersection() {
  7308. var args = [],
  7309. argsIndex = -1,
  7310. argsLength = arguments.length,
  7311. caches = getArray(),
  7312. indexOf = getIndexOf(),
  7313. trustIndexOf = indexOf === baseIndexOf,
  7314. seen = getArray();
  7315. while (++argsIndex < argsLength) {
  7316. var value = arguments[argsIndex];
  7317. if (isArray(value) || isArguments(value)) {
  7318. args.push(value);
  7319. caches.push(trustIndexOf && value.length >= largeArraySize &&
  7320. createCache(argsIndex ? args[argsIndex] : seen));
  7321. }
  7322. }
  7323. var array = args[0],
  7324. index = -1,
  7325. length = array ? array.length : 0,
  7326. result = [];
  7327. outer:
  7328. while (++index < length) {
  7329. var cache = caches[0];
  7330. value = array[index];
  7331. if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
  7332. argsIndex = argsLength;
  7333. (cache || seen).push(value);
  7334. while (--argsIndex) {
  7335. cache = caches[argsIndex];
  7336. if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
  7337. continue outer;
  7338. }
  7339. }
  7340. result.push(value);
  7341. }
  7342. }
  7343. while (argsLength--) {
  7344. cache = caches[argsLength];
  7345. if (cache) {
  7346. releaseObject(cache);
  7347. }
  7348. }
  7349. releaseArray(caches);
  7350. releaseArray(seen);
  7351. return result;
  7352. }
  7353. /**
  7354. * Gets the last element or last `n` elements of an array. If a callback is
  7355. * provided elements at the end of the array are returned as long as the
  7356. * callback returns truey. The callback is bound to `thisArg` and invoked
  7357. * with three arguments; (value, index, array).
  7358. *
  7359. * If a property name is provided for `callback` the created "_.pluck" style
  7360. * callback will return the property value of the given element.
  7361. *
  7362. * If an object is provided for `callback` the created "_.where" style callback
  7363. * will return `true` for elements that have the properties of the given object,
  7364. * else `false`.
  7365. *
  7366. * @static
  7367. * @memberOf _
  7368. * @category Arrays
  7369. * @param {Array} array The array to query.
  7370. * @param {Function|Object|number|string} [callback] The function called
  7371. * per element or the number of elements to return. If a property name or
  7372. * object is provided it will be used to create a "_.pluck" or "_.where"
  7373. * style callback, respectively.
  7374. * @param {*} [thisArg] The `this` binding of `callback`.
  7375. * @returns {*} Returns the last element(s) of `array`.
  7376. * @example
  7377. *
  7378. * _.last([1, 2, 3]);
  7379. * // => 3
  7380. *
  7381. * _.last([1, 2, 3], 2);
  7382. * // => [2, 3]
  7383. *
  7384. * _.last([1, 2, 3], function(num) {
  7385. * return num > 1;
  7386. * });
  7387. * // => [2, 3]
  7388. *
  7389. * var characters = [
  7390. * { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
  7391. * { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
  7392. * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
  7393. * ];
  7394. *
  7395. * // using "_.pluck" callback shorthand
  7396. * _.pluck(_.last(characters, 'blocked'), 'name');
  7397. * // => ['fred', 'pebbles']
  7398. *
  7399. * // using "_.where" callback shorthand
  7400. * _.last(characters, { 'employer': 'na' });
  7401. * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
  7402. */
  7403. function last(array, callback, thisArg) {
  7404. var n = 0,
  7405. length = array ? array.length : 0;
  7406. if (typeof callback != 'number' && callback != null) {
  7407. var index = length;
  7408. callback = lodash.createCallback(callback, thisArg, 3);
  7409. while (index-- && callback(array[index], index, array)) {
  7410. n++;
  7411. }
  7412. } else {
  7413. n = callback;
  7414. if (n == null || thisArg) {
  7415. return array ? array[length - 1] : undefined;
  7416. }
  7417. }
  7418. return slice(array, nativeMax(0, length - n));
  7419. }
  7420. /**
  7421. * Gets the index at which the last occurrence of `value` is found using strict
  7422. * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
  7423. * as the offset from the end of the collection.
  7424. *
  7425. * If a property name is provided for `callback` the created "_.pluck" style
  7426. * callback will return the property value of the given element.
  7427. *
  7428. * If an object is provided for `callback` the created "_.where" style callback
  7429. * will return `true` for elements that have the properties of the given object,
  7430. * else `false`.
  7431. *
  7432. * @static
  7433. * @memberOf _
  7434. * @category Arrays
  7435. * @param {Array} array The array to search.
  7436. * @param {*} value The value to search for.
  7437. * @param {number} [fromIndex=array.length-1] The index to search from.
  7438. * @returns {number} Returns the index of the matched value or `-1`.
  7439. * @example
  7440. *
  7441. * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
  7442. * // => 4
  7443. *
  7444. * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
  7445. * // => 1
  7446. */
  7447. function lastIndexOf(array, value, fromIndex) {
  7448. var index = array ? array.length : 0;
  7449. if (typeof fromIndex == 'number') {
  7450. index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
  7451. }
  7452. while (index--) {
  7453. if (array[index] === value) {
  7454. return index;
  7455. }
  7456. }
  7457. return -1;
  7458. }
  7459. /**
  7460. * Removes all provided values from the given array using strict equality for
  7461. * comparisons, i.e. `===`.
  7462. *
  7463. * @static
  7464. * @memberOf _
  7465. * @category Arrays
  7466. * @param {Array} array The array to modify.
  7467. * @param {...*} [value] The values to remove.
  7468. * @returns {Array} Returns `array`.
  7469. * @example
  7470. *
  7471. * var array = [1, 2, 3, 1, 2, 3];
  7472. * _.pull(array, 2, 3);
  7473. * console.log(array);
  7474. * // => [1, 1]
  7475. */
  7476. function pull(array) {
  7477. var args = arguments,
  7478. argsIndex = 0,
  7479. argsLength = args.length,
  7480. length = array ? array.length : 0;
  7481. while (++argsIndex < argsLength) {
  7482. var index = -1,
  7483. value = args[argsIndex];
  7484. while (++index < length) {
  7485. if (array[index] === value) {
  7486. splice.call(array, index--, 1);
  7487. length--;
  7488. }
  7489. }
  7490. }
  7491. return array;
  7492. }
  7493. /**
  7494. * Creates an array of numbers (positive and/or negative) progressing from
  7495. * `start` up to but not including `end`. If `start` is less than `stop` a
  7496. * zero-length range is created unless a negative `step` is specified.
  7497. *
  7498. * @static
  7499. * @memberOf _
  7500. * @category Arrays
  7501. * @param {number} [start=0] The start of the range.
  7502. * @param {number} end The end of the range.
  7503. * @param {number} [step=1] The value to increment or decrement by.
  7504. * @returns {Array} Returns a new range array.
  7505. * @example
  7506. *
  7507. * _.range(4);
  7508. * // => [0, 1, 2, 3]
  7509. *
  7510. * _.range(1, 5);
  7511. * // => [1, 2, 3, 4]
  7512. *
  7513. * _.range(0, 20, 5);
  7514. * // => [0, 5, 10, 15]
  7515. *
  7516. * _.range(0, -4, -1);
  7517. * // => [0, -1, -2, -3]
  7518. *
  7519. * _.range(1, 4, 0);
  7520. * // => [1, 1, 1]
  7521. *
  7522. * _.range(0);
  7523. * // => []
  7524. */
  7525. function range(start, end, step) {
  7526. start = +start || 0;
  7527. step = typeof step == 'number' ? step : (+step || 1);
  7528. if (end == null) {
  7529. end = start;
  7530. start = 0;
  7531. }
  7532. // use `Array(length)` so engines like Chakra and V8 avoid slower modes
  7533. // http://youtu.be/XAqIpGU8ZZk#t=17m25s
  7534. var index = -1,
  7535. length = nativeMax(0, ceil((end - start) / (step || 1))),
  7536. result = Array(length);
  7537. while (++index < length) {
  7538. result[index] = start;
  7539. start += step;
  7540. }
  7541. return result;
  7542. }
  7543. /**
  7544. * Removes all elements from an array that the callback returns truey for
  7545. * and returns an array of removed elements. The callback is bound to `thisArg`
  7546. * and invoked with three arguments; (value, index, array).
  7547. *
  7548. * If a property name is provided for `callback` the created "_.pluck" style
  7549. * callback will return the property value of the given element.
  7550. *
  7551. * If an object is provided for `callback` the created "_.where" style callback
  7552. * will return `true` for elements that have the properties of the given object,
  7553. * else `false`.
  7554. *
  7555. * @static
  7556. * @memberOf _
  7557. * @category Arrays
  7558. * @param {Array} array The array to modify.
  7559. * @param {Function|Object|string} [callback=identity] The function called
  7560. * per iteration. If a property name or object is provided it will be used
  7561. * to create a "_.pluck" or "_.where" style callback, respectively.
  7562. * @param {*} [thisArg] The `this` binding of `callback`.
  7563. * @returns {Array} Returns a new array of removed elements.
  7564. * @example
  7565. *
  7566. * var array = [1, 2, 3, 4, 5, 6];
  7567. * var evens = _.remove(array, function(num) { return num % 2 == 0; });
  7568. *
  7569. * console.log(array);
  7570. * // => [1, 3, 5]
  7571. *
  7572. * console.log(evens);
  7573. * // => [2, 4, 6]
  7574. */
  7575. function remove(array, callback, thisArg) {
  7576. var index = -1,
  7577. length = array ? array.length : 0,
  7578. result = [];
  7579. callback = lodash.createCallback(callback, thisArg, 3);
  7580. while (++index < length) {
  7581. var value = array[index];
  7582. if (callback(value, index, array)) {
  7583. result.push(value);
  7584. splice.call(array, index--, 1);
  7585. length--;
  7586. }
  7587. }
  7588. return result;
  7589. }
  7590. /**
  7591. * The opposite of `_.initial` this method gets all but the first element or
  7592. * first `n` elements of an array. If a callback function is provided elements
  7593. * at the beginning of the array are excluded from the result as long as the
  7594. * callback returns truey. The callback is bound to `thisArg` and invoked
  7595. * with three arguments; (value, index, array).
  7596. *
  7597. * If a property name is provided for `callback` the created "_.pluck" style
  7598. * callback will return the property value of the given element.
  7599. *
  7600. * If an object is provided for `callback` the created "_.where" style callback
  7601. * will return `true` for elements that have the properties of the given object,
  7602. * else `false`.
  7603. *
  7604. * @static
  7605. * @memberOf _
  7606. * @alias drop, tail
  7607. * @category Arrays
  7608. * @param {Array} array The array to query.
  7609. * @param {Function|Object|number|string} [callback=1] The function called
  7610. * per element or the number of elements to exclude. If a property name or
  7611. * object is provided it will be used to create a "_.pluck" or "_.where"
  7612. * style callback, respectively.
  7613. * @param {*} [thisArg] The `this` binding of `callback`.
  7614. * @returns {Array} Returns a slice of `array`.
  7615. * @example
  7616. *
  7617. * _.rest([1, 2, 3]);
  7618. * // => [2, 3]
  7619. *
  7620. * _.rest([1, 2, 3], 2);
  7621. * // => [3]
  7622. *
  7623. * _.rest([1, 2, 3], function(num) {
  7624. * return num < 3;
  7625. * });
  7626. * // => [3]
  7627. *
  7628. * var characters = [
  7629. * { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
  7630. * { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
  7631. * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
  7632. * ];
  7633. *
  7634. * // using "_.pluck" callback shorthand
  7635. * _.pluck(_.rest(characters, 'blocked'), 'name');
  7636. * // => ['fred', 'pebbles']
  7637. *
  7638. * // using "_.where" callback shorthand
  7639. * _.rest(characters, { 'employer': 'slate' });
  7640. * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
  7641. */
  7642. function rest(array, callback, thisArg) {
  7643. if (typeof callback != 'number' && callback != null) {
  7644. var n = 0,
  7645. index = -1,
  7646. length = array ? array.length : 0;
  7647. callback = lodash.createCallback(callback, thisArg, 3);
  7648. while (++index < length && callback(array[index], index, array)) {
  7649. n++;
  7650. }
  7651. } else {
  7652. n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
  7653. }
  7654. return slice(array, n);
  7655. }
  7656. /**
  7657. * Uses a binary search to determine the smallest index at which a value
  7658. * should be inserted into a given sorted array in order to maintain the sort
  7659. * order of the array. If a callback is provided it will be executed for
  7660. * `value` and each element of `array` to compute their sort ranking. The
  7661. * callback is bound to `thisArg` and invoked with one argument; (value).
  7662. *
  7663. * If a property name is provided for `callback` the created "_.pluck" style
  7664. * callback will return the property value of the given element.
  7665. *
  7666. * If an object is provided for `callback` the created "_.where" style callback
  7667. * will return `true` for elements that have the properties of the given object,
  7668. * else `false`.
  7669. *
  7670. * @static
  7671. * @memberOf _
  7672. * @category Arrays
  7673. * @param {Array} array The array to inspect.
  7674. * @param {*} value The value to evaluate.
  7675. * @param {Function|Object|string} [callback=identity] The function called
  7676. * per iteration. If a property name or object is provided it will be used
  7677. * to create a "_.pluck" or "_.where" style callback, respectively.
  7678. * @param {*} [thisArg] The `this` binding of `callback`.
  7679. * @returns {number} Returns the index at which `value` should be inserted
  7680. * into `array`.
  7681. * @example
  7682. *
  7683. * _.sortedIndex([20, 30, 50], 40);
  7684. * // => 2
  7685. *
  7686. * // using "_.pluck" callback shorthand
  7687. * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
  7688. * // => 2
  7689. *
  7690. * var dict = {
  7691. * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
  7692. * };
  7693. *
  7694. * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
  7695. * return dict.wordToNumber[word];
  7696. * });
  7697. * // => 2
  7698. *
  7699. * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
  7700. * return this.wordToNumber[word];
  7701. * }, dict);
  7702. * // => 2
  7703. */
  7704. function sortedIndex(array, value, callback, thisArg) {
  7705. var low = 0,
  7706. high = array ? array.length : low;
  7707. // explicitly reference `identity` for better inlining in Firefox
  7708. callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
  7709. value = callback(value);
  7710. while (low < high) {
  7711. var mid = (low + high) >>> 1;
  7712. (callback(array[mid]) < value)
  7713. ? low = mid + 1
  7714. : high = mid;
  7715. }
  7716. return low;
  7717. }
  7718. /**
  7719. * Creates an array of unique values, in order, of the provided arrays using
  7720. * strict equality for comparisons, i.e. `===`.
  7721. *
  7722. * @static
  7723. * @memberOf _
  7724. * @category Arrays
  7725. * @param {...Array} [array] The arrays to inspect.
  7726. * @returns {Array} Returns an array of combined values.
  7727. * @example
  7728. *
  7729. * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);
  7730. * // => [1, 2, 3, 5, 4]
  7731. */
  7732. function union() {
  7733. return baseUniq(baseFlatten(arguments, true, true));
  7734. }
  7735. /**
  7736. * Creates a duplicate-value-free version of an array using strict equality
  7737. * for comparisons, i.e. `===`. If the array is sorted, providing
  7738. * `true` for `isSorted` will use a faster algorithm. If a callback is provided
  7739. * each element of `array` is passed through the callback before uniqueness
  7740. * is computed. The callback is bound to `thisArg` and invoked with three
  7741. * arguments; (value, index, array).
  7742. *
  7743. * If a property name is provided for `callback` the created "_.pluck" style
  7744. * callback will return the property value of the given element.
  7745. *
  7746. * If an object is provided for `callback` the created "_.where" style callback
  7747. * will return `true` for elements that have the properties of the given object,
  7748. * else `false`.
  7749. *
  7750. * @static
  7751. * @memberOf _
  7752. * @alias unique
  7753. * @category Arrays
  7754. * @param {Array} array The array to process.
  7755. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
  7756. * @param {Function|Object|string} [callback=identity] The function called
  7757. * per iteration. If a property name or object is provided it will be used
  7758. * to create a "_.pluck" or "_.where" style callback, respectively.
  7759. * @param {*} [thisArg] The `this` binding of `callback`.
  7760. * @returns {Array} Returns a duplicate-value-free array.
  7761. * @example
  7762. *
  7763. * _.uniq([1, 2, 1, 3, 1]);
  7764. * // => [1, 2, 3]
  7765. *
  7766. * _.uniq([1, 1, 2, 2, 3], true);
  7767. * // => [1, 2, 3]
  7768. *
  7769. * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
  7770. * // => ['A', 'b', 'C']
  7771. *
  7772. * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
  7773. * // => [1, 2.5, 3]
  7774. *
  7775. * // using "_.pluck" callback shorthand
  7776. * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
  7777. * // => [{ 'x': 1 }, { 'x': 2 }]
  7778. */
  7779. function uniq(array, isSorted, callback, thisArg) {
  7780. // juggle arguments
  7781. if (typeof isSorted != 'boolean' && isSorted != null) {
  7782. thisArg = callback;
  7783. callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted;
  7784. isSorted = false;
  7785. }
  7786. if (callback != null) {
  7787. callback = lodash.createCallback(callback, thisArg, 3);
  7788. }
  7789. return baseUniq(array, isSorted, callback);
  7790. }
  7791. /**
  7792. * Creates an array excluding all provided values using strict equality for
  7793. * comparisons, i.e. `===`.
  7794. *
  7795. * @static
  7796. * @memberOf _
  7797. * @category Arrays
  7798. * @param {Array} array The array to filter.
  7799. * @param {...*} [value] The values to exclude.
  7800. * @returns {Array} Returns a new array of filtered values.
  7801. * @example
  7802. *
  7803. * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
  7804. * // => [2, 3, 4]
  7805. */
  7806. function without(array) {
  7807. return baseDifference(array, slice(arguments, 1));
  7808. }
  7809. /**
  7810. * Creates an array that is the symmetric difference of the provided arrays.
  7811. * See http://en.wikipedia.org/wiki/Symmetric_difference.
  7812. *
  7813. * @static
  7814. * @memberOf _
  7815. * @category Arrays
  7816. * @param {...Array} [array] The arrays to inspect.
  7817. * @returns {Array} Returns an array of values.
  7818. * @example
  7819. *
  7820. * _.xor([1, 2, 3], [5, 2, 1, 4]);
  7821. * // => [3, 5, 4]
  7822. *
  7823. * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
  7824. * // => [1, 4, 5]
  7825. */
  7826. function xor() {
  7827. var index = -1,
  7828. length = arguments.length;
  7829. while (++index < length) {
  7830. var array = arguments[index];
  7831. if (isArray(array) || isArguments(array)) {
  7832. var result = result
  7833. ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result)))
  7834. : array;
  7835. }
  7836. }
  7837. return result || [];
  7838. }
  7839. /**
  7840. * Creates an array of grouped elements, the first of which contains the first
  7841. * elements of the given arrays, the second of which contains the second
  7842. * elements of the given arrays, and so on.
  7843. *
  7844. * @static
  7845. * @memberOf _
  7846. * @alias unzip
  7847. * @category Arrays
  7848. * @param {...Array} [array] Arrays to process.
  7849. * @returns {Array} Returns a new array of grouped elements.
  7850. * @example
  7851. *
  7852. * _.zip(['fred', 'barney'], [30, 40], [true, false]);
  7853. * // => [['fred', 30, true], ['barney', 40, false]]
  7854. */
  7855. function zip() {
  7856. var array = arguments.length > 1 ? arguments : arguments[0],
  7857. index = -1,
  7858. length = array ? max(pluck(array, 'length')) : 0,
  7859. result = Array(length < 0 ? 0 : length);
  7860. while (++index < length) {
  7861. result[index] = pluck(array, index);
  7862. }
  7863. return result;
  7864. }
  7865. /**
  7866. * Creates an object composed from arrays of `keys` and `values`. Provide
  7867. * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`
  7868. * or two arrays, one of `keys` and one of corresponding `values`.
  7869. *
  7870. * @static
  7871. * @memberOf _
  7872. * @alias object
  7873. * @category Arrays
  7874. * @param {Array} keys The array of keys.
  7875. * @param {Array} [values=[]] The array of values.
  7876. * @returns {Object} Returns an object composed of the given keys and
  7877. * corresponding values.
  7878. * @example
  7879. *
  7880. * _.zipObject(['fred', 'barney'], [30, 40]);
  7881. * // => { 'fred': 30, 'barney': 40 }
  7882. */
  7883. function zipObject(keys, values) {
  7884. var index = -1,
  7885. length = keys ? keys.length : 0,
  7886. result = {};
  7887. if (!values && length && !isArray(keys[0])) {
  7888. values = [];
  7889. }
  7890. while (++index < length) {
  7891. var key = keys[index];
  7892. if (values) {
  7893. result[key] = values[index];
  7894. } else if (key) {
  7895. result[key[0]] = key[1];
  7896. }
  7897. }
  7898. return result;
  7899. }
  7900. /*--------------------------------------------------------------------------*/
  7901. /**
  7902. * Creates a function that executes `func`, with the `this` binding and
  7903. * arguments of the created function, only after being called `n` times.
  7904. *
  7905. * @static
  7906. * @memberOf _
  7907. * @category Functions
  7908. * @param {number} n The number of times the function must be called before
  7909. * `func` is executed.
  7910. * @param {Function} func The function to restrict.
  7911. * @returns {Function} Returns the new restricted function.
  7912. * @example
  7913. *
  7914. * var saves = ['profile', 'settings'];
  7915. *
  7916. * var done = _.after(saves.length, function() {
  7917. * console.log('Done saving!');
  7918. * });
  7919. *
  7920. * _.forEach(saves, function(type) {
  7921. * asyncSave({ 'type': type, 'complete': done });
  7922. * });
  7923. * // => logs 'Done saving!', after all saves have completed
  7924. */
  7925. function after(n, func) {
  7926. if (!isFunction(func)) {
  7927. throw new TypeError;
  7928. }
  7929. return function() {
  7930. if (--n < 1) {
  7931. return func.apply(this, arguments);
  7932. }
  7933. };
  7934. }
  7935. /**
  7936. * Creates a function that, when called, invokes `func` with the `this`
  7937. * binding of `thisArg` and prepends any additional `bind` arguments to those
  7938. * provided to the bound function.
  7939. *
  7940. * @static
  7941. * @memberOf _
  7942. * @category Functions
  7943. * @param {Function} func The function to bind.
  7944. * @param {*} [thisArg] The `this` binding of `func`.
  7945. * @param {...*} [arg] Arguments to be partially applied.
  7946. * @returns {Function} Returns the new bound function.
  7947. * @example
  7948. *
  7949. * var func = function(greeting) {
  7950. * return greeting + ' ' + this.name;
  7951. * };
  7952. *
  7953. * func = _.bind(func, { 'name': 'fred' }, 'hi');
  7954. * func();
  7955. * // => 'hi fred'
  7956. */
  7957. function bind(func, thisArg) {
  7958. return arguments.length > 2
  7959. ? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
  7960. : createWrapper(func, 1, null, null, thisArg);
  7961. }
  7962. /**
  7963. * Binds methods of an object to the object itself, overwriting the existing
  7964. * method. Method names may be specified as individual arguments or as arrays
  7965. * of method names. If no method names are provided all the function properties
  7966. * of `object` will be bound.
  7967. *
  7968. * @static
  7969. * @memberOf _
  7970. * @category Functions
  7971. * @param {Object} object The object to bind and assign the bound methods to.
  7972. * @param {...string} [methodName] The object method names to
  7973. * bind, specified as individual method names or arrays of method names.
  7974. * @returns {Object} Returns `object`.
  7975. * @example
  7976. *
  7977. * var view = {
  7978. * 'label': 'docs',
  7979. * 'onClick': function() { console.log('clicked ' + this.label); }
  7980. * };
  7981. *
  7982. * _.bindAll(view);
  7983. * jQuery('#docs').on('click', view.onClick);
  7984. * // => logs 'clicked docs', when the button is clicked
  7985. */
  7986. function bindAll(object) {
  7987. var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
  7988. index = -1,
  7989. length = funcs.length;
  7990. while (++index < length) {
  7991. var key = funcs[index];
  7992. object[key] = createWrapper(object[key], 1, null, null, object);
  7993. }
  7994. return object;
  7995. }
  7996. /**
  7997. * Creates a function that, when called, invokes the method at `object[key]`
  7998. * and prepends any additional `bindKey` arguments to those provided to the bound
  7999. * function. This method differs from `_.bind` by allowing bound functions to
  8000. * reference methods that will be redefined or don't yet exist.
  8001. * See http://michaux.ca/articles/lazy-function-definition-pattern.
  8002. *
  8003. * @static
  8004. * @memberOf _
  8005. * @category Functions
  8006. * @param {Object} object The object the method belongs to.
  8007. * @param {string} key The key of the method.
  8008. * @param {...*} [arg] Arguments to be partially applied.
  8009. * @returns {Function} Returns the new bound function.
  8010. * @example
  8011. *
  8012. * var object = {
  8013. * 'name': 'fred',
  8014. * 'greet': function(greeting) {
  8015. * return greeting + ' ' + this.name;
  8016. * }
  8017. * };
  8018. *
  8019. * var func = _.bindKey(object, 'greet', 'hi');
  8020. * func();
  8021. * // => 'hi fred'
  8022. *
  8023. * object.greet = function(greeting) {
  8024. * return greeting + 'ya ' + this.name + '!';
  8025. * };
  8026. *
  8027. * func();
  8028. * // => 'hiya fred!'
  8029. */
  8030. function bindKey(object, key) {
  8031. return arguments.length > 2
  8032. ? createWrapper(key, 19, slice(arguments, 2), null, object)
  8033. : createWrapper(key, 3, null, null, object);
  8034. }
  8035. /**
  8036. * Creates a function that is the composition of the provided functions,
  8037. * where each function consumes the return value of the function that follows.
  8038. * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
  8039. * Each function is executed with the `this` binding of the composed function.
  8040. *
  8041. * @static
  8042. * @memberOf _
  8043. * @category Functions
  8044. * @param {...Function} [func] Functions to compose.
  8045. * @returns {Function} Returns the new composed function.
  8046. * @example
  8047. *
  8048. * var realNameMap = {
  8049. * 'pebbles': 'penelope'
  8050. * };
  8051. *
  8052. * var format = function(name) {
  8053. * name = realNameMap[name.toLowerCase()] || name;
  8054. * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
  8055. * };
  8056. *
  8057. * var greet = function(formatted) {
  8058. * return 'Hiya ' + formatted + '!';
  8059. * };
  8060. *
  8061. * var welcome = _.compose(greet, format);
  8062. * welcome('pebbles');
  8063. * // => 'Hiya Penelope!'
  8064. */
  8065. function compose() {
  8066. var funcs = arguments,
  8067. length = funcs.length;
  8068. while (length--) {
  8069. if (!isFunction(funcs[length])) {
  8070. throw new TypeError;
  8071. }
  8072. }
  8073. return function() {
  8074. var args = arguments,
  8075. length = funcs.length;
  8076. while (length--) {
  8077. args = [funcs[length].apply(this, args)];
  8078. }
  8079. return args[0];
  8080. };
  8081. }
  8082. /**
  8083. * Creates a function which accepts one or more arguments of `func` that when
  8084. * invoked either executes `func` returning its result, if all `func` arguments
  8085. * have been provided, or returns a function that accepts one or more of the
  8086. * remaining `func` arguments, and so on. The arity of `func` can be specified
  8087. * if `func.length` is not sufficient.
  8088. *
  8089. * @static
  8090. * @memberOf _
  8091. * @category Functions
  8092. * @param {Function} func The function to curry.
  8093. * @param {number} [arity=func.length] The arity of `func`.
  8094. * @returns {Function} Returns the new curried function.
  8095. * @example
  8096. *
  8097. * var curried = _.curry(function(a, b, c) {
  8098. * console.log(a + b + c);
  8099. * });
  8100. *
  8101. * curried(1)(2)(3);
  8102. * // => 6
  8103. *
  8104. * curried(1, 2)(3);
  8105. * // => 6
  8106. *
  8107. * curried(1, 2, 3);
  8108. * // => 6
  8109. */
  8110. function curry(func, arity) {
  8111. arity = typeof arity == 'number' ? arity : (+arity || func.length);
  8112. return createWrapper(func, 4, null, null, null, arity);
  8113. }
  8114. /**
  8115. * Creates a function that will delay the execution of `func` until after
  8116. * `wait` milliseconds have elapsed since the last time it was invoked.
  8117. * Provide an options object to indicate that `func` should be invoked on
  8118. * the leading and/or trailing edge of the `wait` timeout. Subsequent calls
  8119. * to the debounced function will return the result of the last `func` call.
  8120. *
  8121. * Note: If `leading` and `trailing` options are `true` `func` will be called
  8122. * on the trailing edge of the timeout only if the the debounced function is
  8123. * invoked more than once during the `wait` timeout.
  8124. *
  8125. * @static
  8126. * @memberOf _
  8127. * @category Functions
  8128. * @param {Function} func The function to debounce.
  8129. * @param {number} wait The number of milliseconds to delay.
  8130. * @param {Object} [options] The options object.
  8131. * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout.
  8132. * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called.
  8133. * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
  8134. * @returns {Function} Returns the new debounced function.
  8135. * @example
  8136. *
  8137. * // avoid costly calculations while the window size is in flux
  8138. * var lazyLayout = _.debounce(calculateLayout, 150);
  8139. * jQuery(window).on('resize', lazyLayout);
  8140. *
  8141. * // execute `sendMail` when the click event is fired, debouncing subsequent calls
  8142. * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
  8143. * 'leading': true,
  8144. * 'trailing': false
  8145. * });
  8146. *
  8147. * // ensure `batchLog` is executed once after 1 second of debounced calls
  8148. * var source = new EventSource('/stream');
  8149. * source.addEventListener('message', _.debounce(batchLog, 250, {
  8150. * 'maxWait': 1000
  8151. * }, false);
  8152. */
  8153. function debounce(func, wait, options) {
  8154. var args,
  8155. maxTimeoutId,
  8156. result,
  8157. stamp,
  8158. thisArg,
  8159. timeoutId,
  8160. trailingCall,
  8161. lastCalled = 0,
  8162. maxWait = false,
  8163. trailing = true;
  8164. if (!isFunction(func)) {
  8165. throw new TypeError;
  8166. }
  8167. wait = nativeMax(0, wait) || 0;
  8168. if (options === true) {
  8169. var leading = true;
  8170. trailing = false;
  8171. } else if (isObject(options)) {
  8172. leading = options.leading;
  8173. maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);
  8174. trailing = 'trailing' in options ? options.trailing : trailing;
  8175. }
  8176. var delayed = function() {
  8177. var remaining = wait - (now() - stamp);
  8178. if (remaining <= 0) {
  8179. if (maxTimeoutId) {
  8180. clearTimeout(maxTimeoutId);
  8181. }
  8182. var isCalled = trailingCall;
  8183. maxTimeoutId = timeoutId = trailingCall = undefined;
  8184. if (isCalled) {
  8185. lastCalled = now();
  8186. result = func.apply(thisArg, args);
  8187. if (!timeoutId && !maxTimeoutId) {
  8188. args = thisArg = null;
  8189. }
  8190. }
  8191. } else {
  8192. timeoutId = setTimeout(delayed, remaining);
  8193. }
  8194. };
  8195. var maxDelayed = function() {
  8196. if (timeoutId) {
  8197. clearTimeout(timeoutId);
  8198. }
  8199. maxTimeoutId = timeoutId = trailingCall = undefined;
  8200. if (trailing || (maxWait !== wait)) {
  8201. lastCalled = now();
  8202. result = func.apply(thisArg, args);
  8203. if (!timeoutId && !maxTimeoutId) {
  8204. args = thisArg = null;
  8205. }
  8206. }
  8207. };
  8208. return function() {
  8209. args = arguments;
  8210. stamp = now();
  8211. thisArg = this;
  8212. trailingCall = trailing && (timeoutId || !leading);
  8213. if (maxWait === false) {
  8214. var leadingCall = leading && !timeoutId;
  8215. } else {
  8216. if (!maxTimeoutId && !leading) {
  8217. lastCalled = stamp;
  8218. }
  8219. var remaining = maxWait - (stamp - lastCalled),
  8220. isCalled = remaining <= 0;
  8221. if (isCalled) {
  8222. if (maxTimeoutId) {
  8223. maxTimeoutId = clearTimeout(maxTimeoutId);
  8224. }
  8225. lastCalled = stamp;
  8226. result = func.apply(thisArg, args);
  8227. }
  8228. else if (!maxTimeoutId) {
  8229. maxTimeoutId = setTimeout(maxDelayed, remaining);
  8230. }
  8231. }
  8232. if (isCalled && timeoutId) {
  8233. timeoutId = clearTimeout(timeoutId);
  8234. }
  8235. else if (!timeoutId && wait !== maxWait) {
  8236. timeoutId = setTimeout(delayed, wait);
  8237. }
  8238. if (leadingCall) {
  8239. isCalled = true;
  8240. result = func.apply(thisArg, args);
  8241. }
  8242. if (isCalled && !timeoutId && !maxTimeoutId) {
  8243. args = thisArg = null;
  8244. }
  8245. return result;
  8246. };
  8247. }
  8248. /**
  8249. * Defers executing the `func` function until the current call stack has cleared.
  8250. * Additional arguments will be provided to `func` when it is invoked.
  8251. *
  8252. * @static
  8253. * @memberOf _
  8254. * @category Functions
  8255. * @param {Function} func The function to defer.
  8256. * @param {...*} [arg] Arguments to invoke the function with.
  8257. * @returns {number} Returns the timer id.
  8258. * @example
  8259. *
  8260. * _.defer(function(text) { console.log(text); }, 'deferred');
  8261. * // logs 'deferred' after one or more milliseconds
  8262. */
  8263. function defer(func) {
  8264. if (!isFunction(func)) {
  8265. throw new TypeError;
  8266. }
  8267. var args = slice(arguments, 1);
  8268. return setTimeout(function() { func.apply(undefined, args); }, 1);
  8269. }
  8270. /**
  8271. * Executes the `func` function after `wait` milliseconds. Additional arguments
  8272. * will be provided to `func` when it is invoked.
  8273. *
  8274. * @static
  8275. * @memberOf _
  8276. * @category Functions
  8277. * @param {Function} func The function to delay.
  8278. * @param {number} wait The number of milliseconds to delay execution.
  8279. * @param {...*} [arg] Arguments to invoke the function with.
  8280. * @returns {number} Returns the timer id.
  8281. * @example
  8282. *
  8283. * _.delay(function(text) { console.log(text); }, 1000, 'later');
  8284. * // => logs 'later' after one second
  8285. */
  8286. function delay(func, wait) {
  8287. if (!isFunction(func)) {
  8288. throw new TypeError;
  8289. }
  8290. var args = slice(arguments, 2);
  8291. return setTimeout(function() { func.apply(undefined, args); }, wait);
  8292. }
  8293. /**
  8294. * Creates a function that memoizes the result of `func`. If `resolver` is
  8295. * provided it will be used to determine the cache key for storing the result
  8296. * based on the arguments provided to the memoized function. By default, the
  8297. * first argument provided to the memoized function is used as the cache key.
  8298. * The `func` is executed with the `this` binding of the memoized function.
  8299. * The result cache is exposed as the `cache` property on the memoized function.
  8300. *
  8301. * @static
  8302. * @memberOf _
  8303. * @category Functions
  8304. * @param {Function} func The function to have its output memoized.
  8305. * @param {Function} [resolver] A function used to resolve the cache key.
  8306. * @returns {Function} Returns the new memoizing function.
  8307. * @example
  8308. *
  8309. * var fibonacci = _.memoize(function(n) {
  8310. * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
  8311. * });
  8312. *
  8313. * fibonacci(9)
  8314. * // => 34
  8315. *
  8316. * var data = {
  8317. * 'fred': { 'name': 'fred', 'age': 40 },
  8318. * 'pebbles': { 'name': 'pebbles', 'age': 1 }
  8319. * };
  8320. *
  8321. * // modifying the result cache
  8322. * var get = _.memoize(function(name) { return data[name]; }, _.identity);
  8323. * get('pebbles');
  8324. * // => { 'name': 'pebbles', 'age': 1 }
  8325. *
  8326. * get.cache.pebbles.name = 'penelope';
  8327. * get('pebbles');
  8328. * // => { 'name': 'penelope', 'age': 1 }
  8329. */
  8330. function memoize(func, resolver) {
  8331. if (!isFunction(func)) {
  8332. throw new TypeError;
  8333. }
  8334. var memoized = function() {
  8335. var cache = memoized.cache,
  8336. key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
  8337. return hasOwnProperty.call(cache, key)
  8338. ? cache[key]
  8339. : (cache[key] = func.apply(this, arguments));
  8340. }
  8341. memoized.cache = {};
  8342. return memoized;
  8343. }
  8344. /**
  8345. * Creates a function that is restricted to execute `func` once. Repeat calls to
  8346. * the function will return the value of the first call. The `func` is executed
  8347. * with the `this` binding of the created function.
  8348. *
  8349. * @static
  8350. * @memberOf _
  8351. * @category Functions
  8352. * @param {Function} func The function to restrict.
  8353. * @returns {Function} Returns the new restricted function.
  8354. * @example
  8355. *
  8356. * var initialize = _.once(createApplication);
  8357. * initialize();
  8358. * initialize();
  8359. * // `initialize` executes `createApplication` once
  8360. */
  8361. function once(func) {
  8362. var ran,
  8363. result;
  8364. if (!isFunction(func)) {
  8365. throw new TypeError;
  8366. }
  8367. return function() {
  8368. if (ran) {
  8369. return result;
  8370. }
  8371. ran = true;
  8372. result = func.apply(this, arguments);
  8373. // clear the `func` variable so the function may be garbage collected
  8374. func = null;
  8375. return result;
  8376. };
  8377. }
  8378. /**
  8379. * Creates a function that, when called, invokes `func` with any additional
  8380. * `partial` arguments prepended to those provided to the new function. This
  8381. * method is similar to `_.bind` except it does **not** alter the `this` binding.
  8382. *
  8383. * @static
  8384. * @memberOf _
  8385. * @category Functions
  8386. * @param {Function} func The function to partially apply arguments to.
  8387. * @param {...*} [arg] Arguments to be partially applied.
  8388. * @returns {Function} Returns the new partially applied function.
  8389. * @example
  8390. *
  8391. * var greet = function(greeting, name) { return greeting + ' ' + name; };
  8392. * var hi = _.partial(greet, 'hi');
  8393. * hi('fred');
  8394. * // => 'hi fred'
  8395. */
  8396. function partial(func) {
  8397. return createWrapper(func, 16, slice(arguments, 1));
  8398. }
  8399. /**
  8400. * This method is like `_.partial` except that `partial` arguments are
  8401. * appended to those provided to the new function.
  8402. *
  8403. * @static
  8404. * @memberOf _
  8405. * @category Functions
  8406. * @param {Function} func The function to partially apply arguments to.
  8407. * @param {...*} [arg] Arguments to be partially applied.
  8408. * @returns {Function} Returns the new partially applied function.
  8409. * @example
  8410. *
  8411. * var defaultsDeep = _.partialRight(_.merge, _.defaults);
  8412. *
  8413. * var options = {
  8414. * 'variable': 'data',
  8415. * 'imports': { 'jq': $ }
  8416. * };
  8417. *
  8418. * defaultsDeep(options, _.templateSettings);
  8419. *
  8420. * options.variable
  8421. * // => 'data'
  8422. *
  8423. * options.imports
  8424. * // => { '_': _, 'jq': $ }
  8425. */
  8426. function partialRight(func) {
  8427. return createWrapper(func, 32, null, slice(arguments, 1));
  8428. }
  8429. /**
  8430. * Creates a function that, when executed, will only call the `func` function
  8431. * at most once per every `wait` milliseconds. Provide an options object to
  8432. * indicate that `func` should be invoked on the leading and/or trailing edge
  8433. * of the `wait` timeout. Subsequent calls to the throttled function will
  8434. * return the result of the last `func` call.
  8435. *
  8436. * Note: If `leading` and `trailing` options are `true` `func` will be called
  8437. * on the trailing edge of the timeout only if the the throttled function is
  8438. * invoked more than once during the `wait` timeout.
  8439. *
  8440. * @static
  8441. * @memberOf _
  8442. * @category Functions
  8443. * @param {Function} func The function to throttle.
  8444. * @param {number} wait The number of milliseconds to throttle executions to.
  8445. * @param {Object} [options] The options object.
  8446. * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout.
  8447. * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
  8448. * @returns {Function} Returns the new throttled function.
  8449. * @example
  8450. *
  8451. * // avoid excessively updating the position while scrolling
  8452. * var throttled = _.throttle(updatePosition, 100);
  8453. * jQuery(window).on('scroll', throttled);
  8454. *
  8455. * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes
  8456. * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
  8457. * 'trailing': false
  8458. * }));
  8459. */
  8460. function throttle(func, wait, options) {
  8461. var leading = true,
  8462. trailing = true;
  8463. if (!isFunction(func)) {
  8464. throw new TypeError;
  8465. }
  8466. if (options === false) {
  8467. leading = false;
  8468. } else if (isObject(options)) {
  8469. leading = 'leading' in options ? options.leading : leading;
  8470. trailing = 'trailing' in options ? options.trailing : trailing;
  8471. }
  8472. debounceOptions.leading = leading;
  8473. debounceOptions.maxWait = wait;
  8474. debounceOptions.trailing = trailing;
  8475. return debounce(func, wait, debounceOptions);
  8476. }
  8477. /**
  8478. * Creates a function that provides `value` to the wrapper function as its
  8479. * first argument. Additional arguments provided to the function are appended
  8480. * to those provided to the wrapper function. The wrapper is executed with
  8481. * the `this` binding of the created function.
  8482. *
  8483. * @static
  8484. * @memberOf _
  8485. * @category Functions
  8486. * @param {*} value The value to wrap.
  8487. * @param {Function} wrapper The wrapper function.
  8488. * @returns {Function} Returns the new function.
  8489. * @example
  8490. *
  8491. * var p = _.wrap(_.escape, function(func, text) {
  8492. * return '<p>' + func(text) + '</p>';
  8493. * });
  8494. *
  8495. * p('Fred, Wilma, & Pebbles');
  8496. * // => '<p>Fred, Wilma, &amp; Pebbles</p>'
  8497. */
  8498. function wrap(value, wrapper) {
  8499. return createWrapper(wrapper, 16, [value]);
  8500. }
  8501. /*--------------------------------------------------------------------------*/
  8502. /**
  8503. * Creates a function that returns `value`.
  8504. *
  8505. * @static
  8506. * @memberOf _
  8507. * @category Utilities
  8508. * @param {*} value The value to return from the new function.
  8509. * @returns {Function} Returns the new function.
  8510. * @example
  8511. *
  8512. * var object = { 'name': 'fred' };
  8513. * var getter = _.constant(object);
  8514. * getter() === object;
  8515. * // => true
  8516. */
  8517. function constant(value) {
  8518. return function() {
  8519. return value;
  8520. };
  8521. }
  8522. /**
  8523. * Produces a callback bound to an optional `thisArg`. If `func` is a property
  8524. * name the created callback will return the property value for a given element.
  8525. * If `func` is an object the created callback will return `true` for elements
  8526. * that contain the equivalent object properties, otherwise it will return `false`.
  8527. *
  8528. * @static
  8529. * @memberOf _
  8530. * @category Utilities
  8531. * @param {*} [func=identity] The value to convert to a callback.
  8532. * @param {*} [thisArg] The `this` binding of the created callback.
  8533. * @param {number} [argCount] The number of arguments the callback accepts.
  8534. * @returns {Function} Returns a callback function.
  8535. * @example
  8536. *
  8537. * var characters = [
  8538. * { 'name': 'barney', 'age': 36 },
  8539. * { 'name': 'fred', 'age': 40 }
  8540. * ];
  8541. *
  8542. * // wrap to create custom callback shorthands
  8543. * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
  8544. * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
  8545. * return !match ? func(callback, thisArg) : function(object) {
  8546. * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
  8547. * };
  8548. * });
  8549. *
  8550. * _.filter(characters, 'age__gt38');
  8551. * // => [{ 'name': 'fred', 'age': 40 }]
  8552. */
  8553. function createCallback(func, thisArg, argCount) {
  8554. var type = typeof func;
  8555. if (func == null || type == 'function') {
  8556. return baseCreateCallback(func, thisArg, argCount);
  8557. }
  8558. // handle "_.pluck" style callback shorthands
  8559. if (type != 'object') {
  8560. return property(func);
  8561. }
  8562. var props = keys(func),
  8563. key = props[0],
  8564. a = func[key];
  8565. // handle "_.where" style callback shorthands
  8566. if (props.length == 1 && a === a && !isObject(a)) {
  8567. // fast path the common case of providing an object with a single
  8568. // property containing a primitive value
  8569. return function(object) {
  8570. var b = object[key];
  8571. return a === b && (a !== 0 || (1 / a == 1 / b));
  8572. };
  8573. }
  8574. return function(object) {
  8575. var length = props.length,
  8576. result = false;
  8577. while (length--) {
  8578. if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
  8579. break;
  8580. }
  8581. }
  8582. return result;
  8583. };
  8584. }
  8585. /**
  8586. * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
  8587. * corresponding HTML entities.
  8588. *
  8589. * @static
  8590. * @memberOf _
  8591. * @category Utilities
  8592. * @param {string} string The string to escape.
  8593. * @returns {string} Returns the escaped string.
  8594. * @example
  8595. *
  8596. * _.escape('Fred, Wilma, & Pebbles');
  8597. * // => 'Fred, Wilma, &amp; Pebbles'
  8598. */
  8599. function escape(string) {
  8600. return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
  8601. }
  8602. /**
  8603. * This method returns the first argument provided to it.
  8604. *
  8605. * @static
  8606. * @memberOf _
  8607. * @category Utilities
  8608. * @param {*} value Any value.
  8609. * @returns {*} Returns `value`.
  8610. * @example
  8611. *
  8612. * var object = { 'name': 'fred' };
  8613. * _.identity(object) === object;
  8614. * // => true
  8615. */
  8616. function identity(value) {
  8617. return value;
  8618. }
  8619. /**
  8620. * Adds function properties of a source object to the destination object.
  8621. * If `object` is a function methods will be added to its prototype as well.
  8622. *
  8623. * @static
  8624. * @memberOf _
  8625. * @category Utilities
  8626. * @param {Function|Object} [object=lodash] object The destination object.
  8627. * @param {Object} source The object of functions to add.
  8628. * @param {Object} [options] The options object.
  8629. * @param {boolean} [options.chain=true] Specify whether the functions added are chainable.
  8630. * @example
  8631. *
  8632. * function capitalize(string) {
  8633. * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
  8634. * }
  8635. *
  8636. * _.mixin({ 'capitalize': capitalize });
  8637. * _.capitalize('fred');
  8638. * // => 'Fred'
  8639. *
  8640. * _('fred').capitalize().value();
  8641. * // => 'Fred'
  8642. *
  8643. * _.mixin({ 'capitalize': capitalize }, { 'chain': false });
  8644. * _('fred').capitalize();
  8645. * // => 'Fred'
  8646. */
  8647. function mixin(object, source, options) {
  8648. var chain = true,
  8649. methodNames = source && functions(source);
  8650. if (!source || (!options && !methodNames.length)) {
  8651. if (options == null) {
  8652. options = source;
  8653. }
  8654. ctor = lodashWrapper;
  8655. source = object;
  8656. object = lodash;
  8657. methodNames = functions(source);
  8658. }
  8659. if (options === false) {
  8660. chain = false;
  8661. } else if (isObject(options) && 'chain' in options) {
  8662. chain = options.chain;
  8663. }
  8664. var ctor = object,
  8665. isFunc = isFunction(ctor);
  8666. forEach(methodNames, function(methodName) {
  8667. var func = object[methodName] = source[methodName];
  8668. if (isFunc) {
  8669. ctor.prototype[methodName] = function() {
  8670. var chainAll = this.__chain__,
  8671. value = this.__wrapped__,
  8672. args = [value];
  8673. push.apply(args, arguments);
  8674. var result = func.apply(object, args);
  8675. if (chain || chainAll) {
  8676. if (value === result && isObject(result)) {
  8677. return this;
  8678. }
  8679. result = new ctor(result);
  8680. result.__chain__ = chainAll;
  8681. }
  8682. return result;
  8683. };
  8684. }
  8685. });
  8686. }
  8687. /**
  8688. * Reverts the '_' variable to its previous value and returns a reference to
  8689. * the `lodash` function.
  8690. *
  8691. * @static
  8692. * @memberOf _
  8693. * @category Utilities
  8694. * @returns {Function} Returns the `lodash` function.
  8695. * @example
  8696. *
  8697. * var lodash = _.noConflict();
  8698. */
  8699. function noConflict() {
  8700. context._ = oldDash;
  8701. return this;
  8702. }
  8703. /**
  8704. * A no-operation function.
  8705. *
  8706. * @static
  8707. * @memberOf _
  8708. * @category Utilities
  8709. * @example
  8710. *
  8711. * var object = { 'name': 'fred' };
  8712. * _.noop(object) === undefined;
  8713. * // => true
  8714. */
  8715. function noop() {
  8716. // no operation performed
  8717. }
  8718. /**
  8719. * Gets the number of milliseconds that have elapsed since the Unix epoch
  8720. * (1 January 1970 00:00:00 UTC).
  8721. *
  8722. * @static
  8723. * @memberOf _
  8724. * @category Utilities
  8725. * @example
  8726. *
  8727. * var stamp = _.now();
  8728. * _.defer(function() { console.log(_.now() - stamp); });
  8729. * // => logs the number of milliseconds it took for the deferred function to be called
  8730. */
  8731. var now = isNative(now = Date.now) && now || function() {
  8732. return new Date().getTime();
  8733. };
  8734. /**
  8735. * Converts the given value into an integer of the specified radix.
  8736. * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the
  8737. * `value` is a hexadecimal, in which case a `radix` of `16` is used.
  8738. *
  8739. * Note: This method avoids differences in native ES3 and ES5 `parseInt`
  8740. * implementations. See http://es5.github.io/#E.
  8741. *
  8742. * @static
  8743. * @memberOf _
  8744. * @category Utilities
  8745. * @param {string} value The value to parse.
  8746. * @param {number} [radix] The radix used to interpret the value to parse.
  8747. * @returns {number} Returns the new integer value.
  8748. * @example
  8749. *
  8750. * _.parseInt('08');
  8751. * // => 8
  8752. */
  8753. var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
  8754. // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt`
  8755. return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
  8756. };
  8757. /**
  8758. * Creates a "_.pluck" style function, which returns the `key` value of a
  8759. * given object.
  8760. *
  8761. * @static
  8762. * @memberOf _
  8763. * @category Utilities
  8764. * @param {string} key The name of the property to retrieve.
  8765. * @returns {Function} Returns the new function.
  8766. * @example
  8767. *
  8768. * var characters = [
  8769. * { 'name': 'fred', 'age': 40 },
  8770. * { 'name': 'barney', 'age': 36 }
  8771. * ];
  8772. *
  8773. * var getName = _.property('name');
  8774. *
  8775. * _.map(characters, getName);
  8776. * // => ['barney', 'fred']
  8777. *
  8778. * _.sortBy(characters, getName);
  8779. * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]
  8780. */
  8781. function property(key) {
  8782. return function(object) {
  8783. return object[key];
  8784. };
  8785. }
  8786. /**
  8787. * Produces a random number between `min` and `max` (inclusive). If only one
  8788. * argument is provided a number between `0` and the given number will be
  8789. * returned. If `floating` is truey or either `min` or `max` are floats a
  8790. * floating-point number will be returned instead of an integer.
  8791. *
  8792. * @static
  8793. * @memberOf _
  8794. * @category Utilities
  8795. * @param {number} [min=0] The minimum possible value.
  8796. * @param {number} [max=1] The maximum possible value.
  8797. * @param {boolean} [floating=false] Specify returning a floating-point number.
  8798. * @returns {number} Returns a random number.
  8799. * @example
  8800. *
  8801. * _.random(0, 5);
  8802. * // => an integer between 0 and 5
  8803. *
  8804. * _.random(5);
  8805. * // => also an integer between 0 and 5
  8806. *
  8807. * _.random(5, true);
  8808. * // => a floating-point number between 0 and 5
  8809. *
  8810. * _.random(1.2, 5.2);
  8811. * // => a floating-point number between 1.2 and 5.2
  8812. */
  8813. function random(min, max, floating) {
  8814. var noMin = min == null,
  8815. noMax = max == null;
  8816. if (floating == null) {
  8817. if (typeof min == 'boolean' && noMax) {
  8818. floating = min;
  8819. min = 1;
  8820. }
  8821. else if (!noMax && typeof max == 'boolean') {
  8822. floating = max;
  8823. noMax = true;
  8824. }
  8825. }
  8826. if (noMin && noMax) {
  8827. max = 1;
  8828. }
  8829. min = +min || 0;
  8830. if (noMax) {
  8831. max = min;
  8832. min = 0;
  8833. } else {
  8834. max = +max || 0;
  8835. }
  8836. if (floating || min % 1 || max % 1) {
  8837. var rand = nativeRandom();
  8838. return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max);
  8839. }
  8840. return baseRandom(min, max);
  8841. }
  8842. /**
  8843. * Resolves the value of property `key` on `object`. If `key` is a function
  8844. * it will be invoked with the `this` binding of `object` and its result returned,
  8845. * else the property value is returned. If `object` is falsey then `undefined`
  8846. * is returned.
  8847. *
  8848. * @static
  8849. * @memberOf _
  8850. * @category Utilities
  8851. * @param {Object} object The object to inspect.
  8852. * @param {string} key The name of the property to resolve.
  8853. * @returns {*} Returns the resolved value.
  8854. * @example
  8855. *
  8856. * var object = {
  8857. * 'cheese': 'crumpets',
  8858. * 'stuff': function() {
  8859. * return 'nonsense';
  8860. * }
  8861. * };
  8862. *
  8863. * _.result(object, 'cheese');
  8864. * // => 'crumpets'
  8865. *
  8866. * _.result(object, 'stuff');
  8867. * // => 'nonsense'
  8868. */
  8869. function result(object, key) {
  8870. if (object) {
  8871. var value = object[key];
  8872. return isFunction(value) ? object[key]() : value;
  8873. }
  8874. }
  8875. /**
  8876. * A micro-templating method that handles arbitrary delimiters, preserves
  8877. * whitespace, and correctly escapes quotes within interpolated code.
  8878. *
  8879. * Note: In the development build, `_.template` utilizes sourceURLs for easier
  8880. * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
  8881. *
  8882. * For more information on precompiling templates see:
  8883. * http://lodash.com/custom-builds
  8884. *
  8885. * For more information on Chrome extension sandboxes see:
  8886. * http://developer.chrome.com/stable/extensions/sandboxingEval.html
  8887. *
  8888. * @static
  8889. * @memberOf _
  8890. * @category Utilities
  8891. * @param {string} text The template text.
  8892. * @param {Object} data The data object used to populate the text.
  8893. * @param {Object} [options] The options object.
  8894. * @param {RegExp} [options.escape] The "escape" delimiter.
  8895. * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
  8896. * @param {Object} [options.imports] An object to import into the template as local variables.
  8897. * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
  8898. * @param {string} [sourceURL] The sourceURL of the template's compiled source.
  8899. * @param {string} [variable] The data object variable name.
  8900. * @returns {Function|string} Returns a compiled function when no `data` object
  8901. * is given, else it returns the interpolated text.
  8902. * @example
  8903. *
  8904. * // using the "interpolate" delimiter to create a compiled template
  8905. * var compiled = _.template('hello <%= name %>');
  8906. * compiled({ 'name': 'fred' });
  8907. * // => 'hello fred'
  8908. *
  8909. * // using the "escape" delimiter to escape HTML in data property values
  8910. * _.template('<b><%- value %></b>', { 'value': '<script>' });
  8911. * // => '<b>&lt;script&gt;</b>'
  8912. *
  8913. * // using the "evaluate" delimiter to generate HTML
  8914. * var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
  8915. * _.template(list, { 'people': ['fred', 'barney'] });
  8916. * // => '<li>fred</li><li>barney</li>'
  8917. *
  8918. * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
  8919. * _.template('hello ${ name }', { 'name': 'pebbles' });
  8920. * // => 'hello pebbles'
  8921. *
  8922. * // using the internal `print` function in "evaluate" delimiters
  8923. * _.template('<% print("hello " + name); %>!', { 'name': 'barney' });
  8924. * // => 'hello barney!'
  8925. *
  8926. * // using a custom template delimiters
  8927. * _.templateSettings = {
  8928. * 'interpolate': /{{([\s\S]+?)}}/g
  8929. * };
  8930. *
  8931. * _.template('hello {{ name }}!', { 'name': 'mustache' });
  8932. * // => 'hello mustache!'
  8933. *
  8934. * // using the `imports` option to import jQuery
  8935. * var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>';
  8936. * _.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } });
  8937. * // => '<li>fred</li><li>barney</li>'
  8938. *
  8939. * // using the `sourceURL` option to specify a custom sourceURL for the template
  8940. * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
  8941. * compiled(data);
  8942. * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
  8943. *
  8944. * // using the `variable` option to ensure a with-statement isn't used in the compiled template
  8945. * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
  8946. * compiled.source;
  8947. * // => function(data) {
  8948. * var __t, __p = '', __e = _.escape;
  8949. * __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
  8950. * return __p;
  8951. * }
  8952. *
  8953. * // using the `source` property to inline compiled templates for meaningful
  8954. * // line numbers in error messages and a stack trace
  8955. * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
  8956. * var JST = {\
  8957. * "main": ' + _.template(mainText).source + '\
  8958. * };\
  8959. * ');
  8960. */
  8961. function template(text, data, options) {
  8962. // based on John Resig's `tmpl` implementation
  8963. // http://ejohn.org/blog/javascript-micro-templating/
  8964. // and Laura Doktorova's doT.js
  8965. // https://github.com/olado/doT
  8966. var settings = lodash.templateSettings;
  8967. text = String(text || '');
  8968. // avoid missing dependencies when `iteratorTemplate` is not defined
  8969. options = defaults({}, options, settings);
  8970. var imports = defaults({}, options.imports, settings.imports),
  8971. importsKeys = keys(imports),
  8972. importsValues = values(imports);
  8973. var isEvaluating,
  8974. index = 0,
  8975. interpolate = options.interpolate || reNoMatch,
  8976. source = "__p += '";
  8977. // compile the regexp to match each delimiter
  8978. var reDelimiters = RegExp(
  8979. (options.escape || reNoMatch).source + '|' +
  8980. interpolate.source + '|' +
  8981. (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
  8982. (options.evaluate || reNoMatch).source + '|$'
  8983. , 'g');
  8984. text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
  8985. interpolateValue || (interpolateValue = esTemplateValue);
  8986. // escape characters that cannot be included in string literals
  8987. source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);
  8988. // replace delimiters with snippets
  8989. if (escapeValue) {
  8990. source += "' +\n__e(" + escapeValue + ") +\n'";
  8991. }
  8992. if (evaluateValue) {
  8993. isEvaluating = true;
  8994. source += "';\n" + evaluateValue + ";\n__p += '";
  8995. }
  8996. if (interpolateValue) {
  8997. source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
  8998. }
  8999. index = offset + match.length;
  9000. // the JS engine embedded in Adobe products requires returning the `match`
  9001. // string in order to produce the correct `offset` value
  9002. return match;
  9003. });
  9004. source += "';\n";
  9005. // if `variable` is not specified, wrap a with-statement around the generated
  9006. // code to add the data object to the top of the scope chain
  9007. var variable = options.variable,
  9008. hasVariable = variable;
  9009. if (!hasVariable) {
  9010. variable = 'obj';
  9011. source = 'with (' + variable + ') {\n' + source + '\n}\n';
  9012. }
  9013. // cleanup code by stripping empty strings
  9014. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
  9015. .replace(reEmptyStringMiddle, '$1')
  9016. .replace(reEmptyStringTrailing, '$1;');
  9017. // frame code as the function body
  9018. source = 'function(' + variable + ') {\n' +
  9019. (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
  9020. "var __t, __p = '', __e = _.escape" +
  9021. (isEvaluating
  9022. ? ', __j = Array.prototype.join;\n' +
  9023. "function print() { __p += __j.call(arguments, '') }\n"
  9024. : ';\n'
  9025. ) +
  9026. source +
  9027. 'return __p\n}';
  9028. // Use a sourceURL for easier debugging.
  9029. // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
  9030. var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
  9031. try {
  9032. var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
  9033. } catch(e) {
  9034. e.source = source;
  9035. throw e;
  9036. }
  9037. if (data) {
  9038. return result(data);
  9039. }
  9040. // provide the compiled function's source by its `toString` method, in
  9041. // supported environments, or the `source` property as a convenience for
  9042. // inlining compiled templates during the build process
  9043. result.source = source;
  9044. return result;
  9045. }
  9046. /**
  9047. * Executes the callback `n` times, returning an array of the results
  9048. * of each callback execution. The callback is bound to `thisArg` and invoked
  9049. * with one argument; (index).
  9050. *
  9051. * @static
  9052. * @memberOf _
  9053. * @category Utilities
  9054. * @param {number} n The number of times to execute the callback.
  9055. * @param {Function} callback The function called per iteration.
  9056. * @param {*} [thisArg] The `this` binding of `callback`.
  9057. * @returns {Array} Returns an array of the results of each `callback` execution.
  9058. * @example
  9059. *
  9060. * var diceRolls = _.times(3, _.partial(_.random, 1, 6));
  9061. * // => [3, 6, 4]
  9062. *
  9063. * _.times(3, function(n) { mage.castSpell(n); });
  9064. * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
  9065. *
  9066. * _.times(3, function(n) { this.cast(n); }, mage);
  9067. * // => also calls `mage.castSpell(n)` three times
  9068. */
  9069. function times(n, callback, thisArg) {
  9070. n = (n = +n) > -1 ? n : 0;
  9071. var index = -1,
  9072. result = Array(n);
  9073. callback = baseCreateCallback(callback, thisArg, 1);
  9074. while (++index < n) {
  9075. result[index] = callback(index);
  9076. }
  9077. return result;
  9078. }
  9079. /**
  9080. * The inverse of `_.escape` this method converts the HTML entities
  9081. * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their
  9082. * corresponding characters.
  9083. *
  9084. * @static
  9085. * @memberOf _
  9086. * @category Utilities
  9087. * @param {string} string The string to unescape.
  9088. * @returns {string} Returns the unescaped string.
  9089. * @example
  9090. *
  9091. * _.unescape('Fred, Barney &amp; Pebbles');
  9092. * // => 'Fred, Barney & Pebbles'
  9093. */
  9094. function unescape(string) {
  9095. return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
  9096. }
  9097. /**
  9098. * Generates a unique ID. If `prefix` is provided the ID will be appended to it.
  9099. *
  9100. * @static
  9101. * @memberOf _
  9102. * @category Utilities
  9103. * @param {string} [prefix] The value to prefix the ID with.
  9104. * @returns {string} Returns the unique ID.
  9105. * @example
  9106. *
  9107. * _.uniqueId('contact_');
  9108. * // => 'contact_104'
  9109. *
  9110. * _.uniqueId();
  9111. * // => '105'
  9112. */
  9113. function uniqueId(prefix) {
  9114. var id = ++idCounter;
  9115. return String(prefix == null ? '' : prefix) + id;
  9116. }
  9117. /*--------------------------------------------------------------------------*/
  9118. /**
  9119. * Creates a `lodash` object that wraps the given value with explicit
  9120. * method chaining enabled.
  9121. *
  9122. * @static
  9123. * @memberOf _
  9124. * @category Chaining
  9125. * @param {*} value The value to wrap.
  9126. * @returns {Object} Returns the wrapper object.
  9127. * @example
  9128. *
  9129. * var characters = [
  9130. * { 'name': 'barney', 'age': 36 },
  9131. * { 'name': 'fred', 'age': 40 },
  9132. * { 'name': 'pebbles', 'age': 1 }
  9133. * ];
  9134. *
  9135. * var youngest = _.chain(characters)
  9136. * .sortBy('age')
  9137. * .map(function(chr) { return chr.name + ' is ' + chr.age; })
  9138. * .first()
  9139. * .value();
  9140. * // => 'pebbles is 1'
  9141. */
  9142. function chain(value) {
  9143. value = new lodashWrapper(value);
  9144. value.__chain__ = true;
  9145. return value;
  9146. }
  9147. /**
  9148. * Invokes `interceptor` with the `value` as the first argument and then
  9149. * returns `value`. The purpose of this method is to "tap into" a method
  9150. * chain in order to perform operations on intermediate results within
  9151. * the chain.
  9152. *
  9153. * @static
  9154. * @memberOf _
  9155. * @category Chaining
  9156. * @param {*} value The value to provide to `interceptor`.
  9157. * @param {Function} interceptor The function to invoke.
  9158. * @returns {*} Returns `value`.
  9159. * @example
  9160. *
  9161. * _([1, 2, 3, 4])
  9162. * .tap(function(array) { array.pop(); })
  9163. * .reverse()
  9164. * .value();
  9165. * // => [3, 2, 1]
  9166. */
  9167. function tap(value, interceptor) {
  9168. interceptor(value);
  9169. return value;
  9170. }
  9171. /**
  9172. * Enables explicit method chaining on the wrapper object.
  9173. *
  9174. * @name chain
  9175. * @memberOf _
  9176. * @category Chaining
  9177. * @returns {*} Returns the wrapper object.
  9178. * @example
  9179. *
  9180. * var characters = [
  9181. * { 'name': 'barney', 'age': 36 },
  9182. * { 'name': 'fred', 'age': 40 }
  9183. * ];
  9184. *
  9185. * // without explicit chaining
  9186. * _(characters).first();
  9187. * // => { 'name': 'barney', 'age': 36 }
  9188. *
  9189. * // with explicit chaining
  9190. * _(characters).chain()
  9191. * .first()
  9192. * .pick('age')
  9193. * .value();
  9194. * // => { 'age': 36 }
  9195. */
  9196. function wrapperChain() {
  9197. this.__chain__ = true;
  9198. return this;
  9199. }
  9200. /**
  9201. * Produces the `toString` result of the wrapped value.
  9202. *
  9203. * @name toString
  9204. * @memberOf _
  9205. * @category Chaining
  9206. * @returns {string} Returns the string result.
  9207. * @example
  9208. *
  9209. * _([1, 2, 3]).toString();
  9210. * // => '1,2,3'
  9211. */
  9212. function wrapperToString() {
  9213. return String(this.__wrapped__);
  9214. }
  9215. /**
  9216. * Extracts the wrapped value.
  9217. *
  9218. * @name valueOf
  9219. * @memberOf _
  9220. * @alias value
  9221. * @category Chaining
  9222. * @returns {*} Returns the wrapped value.
  9223. * @example
  9224. *
  9225. * _([1, 2, 3]).valueOf();
  9226. * // => [1, 2, 3]
  9227. */
  9228. function wrapperValueOf() {
  9229. return this.__wrapped__;
  9230. }
  9231. /*--------------------------------------------------------------------------*/
  9232. // add functions that return wrapped values when chaining
  9233. lodash.after = after;
  9234. lodash.assign = assign;
  9235. lodash.at = at;
  9236. lodash.bind = bind;
  9237. lodash.bindAll = bindAll;
  9238. lodash.bindKey = bindKey;
  9239. lodash.chain = chain;
  9240. lodash.compact = compact;
  9241. lodash.compose = compose;
  9242. lodash.constant = constant;
  9243. lodash.countBy = countBy;
  9244. lodash.create = create;
  9245. lodash.createCallback = createCallback;
  9246. lodash.curry = curry;
  9247. lodash.debounce = debounce;
  9248. lodash.defaults = defaults;
  9249. lodash.defer = defer;
  9250. lodash.delay = delay;
  9251. lodash.difference = difference;
  9252. lodash.filter = filter;
  9253. lodash.flatten = flatten;
  9254. lodash.forEach = forEach;
  9255. lodash.forEachRight = forEachRight;
  9256. lodash.forIn = forIn;
  9257. lodash.forInRight = forInRight;
  9258. lodash.forOwn = forOwn;
  9259. lodash.forOwnRight = forOwnRight;
  9260. lodash.functions = functions;
  9261. lodash.groupBy = groupBy;
  9262. lodash.indexBy = indexBy;
  9263. lodash.initial = initial;
  9264. lodash.intersection = intersection;
  9265. lodash.invert = invert;
  9266. lodash.invoke = invoke;
  9267. lodash.keys = keys;
  9268. lodash.map = map;
  9269. lodash.mapValues = mapValues;
  9270. lodash.max = max;
  9271. lodash.memoize = memoize;
  9272. lodash.merge = merge;
  9273. lodash.min = min;
  9274. lodash.omit = omit;
  9275. lodash.once = once;
  9276. lodash.pairs = pairs;
  9277. lodash.partial = partial;
  9278. lodash.partialRight = partialRight;
  9279. lodash.pick = pick;
  9280. lodash.pluck = pluck;
  9281. lodash.property = property;
  9282. lodash.pull = pull;
  9283. lodash.range = range;
  9284. lodash.reject = reject;
  9285. lodash.remove = remove;
  9286. lodash.rest = rest;
  9287. lodash.shuffle = shuffle;
  9288. lodash.sortBy = sortBy;
  9289. lodash.tap = tap;
  9290. lodash.throttle = throttle;
  9291. lodash.times = times;
  9292. lodash.toArray = toArray;
  9293. lodash.transform = transform;
  9294. lodash.union = union;
  9295. lodash.uniq = uniq;
  9296. lodash.values = values;
  9297. lodash.where = where;
  9298. lodash.without = without;
  9299. lodash.wrap = wrap;
  9300. lodash.xor = xor;
  9301. lodash.zip = zip;
  9302. lodash.zipObject = zipObject;
  9303. // add aliases
  9304. lodash.collect = map;
  9305. lodash.drop = rest;
  9306. lodash.each = forEach;
  9307. lodash.eachRight = forEachRight;
  9308. lodash.extend = assign;
  9309. lodash.methods = functions;
  9310. lodash.object = zipObject;
  9311. lodash.select = filter;
  9312. lodash.tail = rest;
  9313. lodash.unique = uniq;
  9314. lodash.unzip = zip;
  9315. // add functions to `lodash.prototype`
  9316. mixin(lodash);
  9317. /*--------------------------------------------------------------------------*/
  9318. // add functions that return unwrapped values when chaining
  9319. lodash.clone = clone;
  9320. lodash.cloneDeep = cloneDeep;
  9321. lodash.contains = contains;
  9322. lodash.escape = escape;
  9323. lodash.every = every;
  9324. lodash.find = find;
  9325. lodash.findIndex = findIndex;
  9326. lodash.findKey = findKey;
  9327. lodash.findLast = findLast;
  9328. lodash.findLastIndex = findLastIndex;
  9329. lodash.findLastKey = findLastKey;
  9330. lodash.has = has;
  9331. lodash.identity = identity;
  9332. lodash.indexOf = indexOf;
  9333. lodash.isArguments = isArguments;
  9334. lodash.isArray = isArray;
  9335. lodash.isBoolean = isBoolean;
  9336. lodash.isDate = isDate;
  9337. lodash.isElement = isElement;
  9338. lodash.isEmpty = isEmpty;
  9339. lodash.isEqual = isEqual;
  9340. lodash.isFinite = isFinite;
  9341. lodash.isFunction = isFunction;
  9342. lodash.isNaN = isNaN;
  9343. lodash.isNull = isNull;
  9344. lodash.isNumber = isNumber;
  9345. lodash.isObject = isObject;
  9346. lodash.isPlainObject = isPlainObject;
  9347. lodash.isRegExp = isRegExp;
  9348. lodash.isString = isString;
  9349. lodash.isUndefined = isUndefined;
  9350. lodash.lastIndexOf = lastIndexOf;
  9351. lodash.mixin = mixin;
  9352. lodash.noConflict = noConflict;
  9353. lodash.noop = noop;
  9354. lodash.now = now;
  9355. lodash.parseInt = parseInt;
  9356. lodash.random = random;
  9357. lodash.reduce = reduce;
  9358. lodash.reduceRight = reduceRight;
  9359. lodash.result = result;
  9360. lodash.runInContext = runInContext;
  9361. lodash.size = size;
  9362. lodash.some = some;
  9363. lodash.sortedIndex = sortedIndex;
  9364. lodash.template = template;
  9365. lodash.unescape = unescape;
  9366. lodash.uniqueId = uniqueId;
  9367. // add aliases
  9368. lodash.all = every;
  9369. lodash.any = some;
  9370. lodash.detect = find;
  9371. lodash.findWhere = find;
  9372. lodash.foldl = reduce;
  9373. lodash.foldr = reduceRight;
  9374. lodash.include = contains;
  9375. lodash.inject = reduce;
  9376. mixin(function() {
  9377. var source = {}
  9378. forOwn(lodash, function(func, methodName) {
  9379. if (!lodash.prototype[methodName]) {
  9380. source[methodName] = func;
  9381. }
  9382. });
  9383. return source;
  9384. }(), false);
  9385. /*--------------------------------------------------------------------------*/
  9386. // add functions capable of returning wrapped and unwrapped values when chaining
  9387. lodash.first = first;
  9388. lodash.last = last;
  9389. lodash.sample = sample;
  9390. // add aliases
  9391. lodash.take = first;
  9392. lodash.head = first;
  9393. forOwn(lodash, function(func, methodName) {
  9394. var callbackable = methodName !== 'sample';
  9395. if (!lodash.prototype[methodName]) {
  9396. lodash.prototype[methodName]= function(n, guard) {
  9397. var chainAll = this.__chain__,
  9398. result = func(this.__wrapped__, n, guard);
  9399. return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function')))
  9400. ? result
  9401. : new lodashWrapper(result, chainAll);
  9402. };
  9403. }
  9404. });
  9405. /*--------------------------------------------------------------------------*/
  9406. /**
  9407. * The semantic version number.
  9408. *
  9409. * @static
  9410. * @memberOf _
  9411. * @type string
  9412. */
  9413. lodash.VERSION = '2.4.1';
  9414. // add "Chaining" functions to the wrapper
  9415. lodash.prototype.chain = wrapperChain;
  9416. lodash.prototype.toString = wrapperToString;
  9417. lodash.prototype.value = wrapperValueOf;
  9418. lodash.prototype.valueOf = wrapperValueOf;
  9419. // add `Array` functions that return unwrapped values
  9420. forEach(['join', 'pop', 'shift'], function(methodName) {
  9421. var func = arrayRef[methodName];
  9422. lodash.prototype[methodName] = function() {
  9423. var chainAll = this.__chain__,
  9424. result = func.apply(this.__wrapped__, arguments);
  9425. return chainAll
  9426. ? new lodashWrapper(result, chainAll)
  9427. : result;
  9428. };
  9429. });
  9430. // add `Array` functions that return the existing wrapped value
  9431. forEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
  9432. var func = arrayRef[methodName];
  9433. lodash.prototype[methodName] = function() {
  9434. func.apply(this.__wrapped__, arguments);
  9435. return this;
  9436. };
  9437. });
  9438. // add `Array` functions that return new wrapped values
  9439. forEach(['concat', 'slice', 'splice'], function(methodName) {
  9440. var func = arrayRef[methodName];
  9441. lodash.prototype[methodName] = function() {
  9442. return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__);
  9443. };
  9444. });
  9445. return lodash;
  9446. }
  9447. /*--------------------------------------------------------------------------*/
  9448. // expose Lo-Dash
  9449. var _ = runInContext();
  9450. // some AMD build optimizers like r.js check for condition patterns like the following:
  9451. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  9452. // Expose Lo-Dash to the global object even when an AMD loader is present in
  9453. // case Lo-Dash is loaded with a RequireJS shim config.
  9454. // See http://requirejs.org/docs/api.html#config-shim
  9455. root._ = _;
  9456. // define as an anonymous module so, through path mapping, it can be
  9457. // referenced as the "underscore" module
  9458. define(function() {
  9459. return _;
  9460. });
  9461. }
  9462. // check for `exports` after `define` in case a build optimizer adds an `exports` object
  9463. else if (freeExports && freeModule) {
  9464. // in Node.js or RingoJS
  9465. if (moduleExports) {
  9466. (freeModule.exports = _)._ = _;
  9467. }
  9468. // in Narwhal or Rhino -require
  9469. else {
  9470. freeExports._ = _;
  9471. }
  9472. }
  9473. else {
  9474. // in a browser or Rhino
  9475. root._ = _;
  9476. }
  9477. }.call(this));
  9478. },{}],32:[function(require,module,exports){
  9479. // Underscore.string
  9480. // (c) 2010 Esa-Matti Suuronen <esa-matti aet suuronen dot org>
  9481. // Underscore.string is freely distributable under the terms of the MIT license.
  9482. // Documentation: https://github.com/epeli/underscore.string
  9483. // Some code is borrowed from MooTools and Alexandru Marasteanu.
  9484. // Version '2.3.2'
  9485. !function(root, String){
  9486. 'use strict';
  9487. // Defining helper functions.
  9488. var nativeTrim = String.prototype.trim;
  9489. var nativeTrimRight = String.prototype.trimRight;
  9490. var nativeTrimLeft = String.prototype.trimLeft;
  9491. var parseNumber = function(source) { return source * 1 || 0; };
  9492. var strRepeat = function(str, qty){
  9493. if (qty < 1) return '';
  9494. var result = '';
  9495. while (qty > 0) {
  9496. if (qty & 1) result += str;
  9497. qty >>= 1, str += str;
  9498. }
  9499. return result;
  9500. };
  9501. var slice = [].slice;
  9502. var defaultToWhiteSpace = function(characters) {
  9503. if (characters == null)
  9504. return '\\s';
  9505. else if (characters.source)
  9506. return characters.source;
  9507. else
  9508. return '[' + _s.escapeRegExp(characters) + ']';
  9509. };
  9510. // Helper for toBoolean
  9511. function boolMatch(s, matchers) {
  9512. var i, matcher, down = s.toLowerCase();
  9513. matchers = [].concat(matchers);
  9514. for (i = 0; i < matchers.length; i += 1) {
  9515. matcher = matchers[i];
  9516. if (!matcher) continue;
  9517. if (matcher.test && matcher.test(s)) return true;
  9518. if (matcher.toLowerCase() === down) return true;
  9519. }
  9520. }
  9521. var escapeChars = {
  9522. lt: '<',
  9523. gt: '>',
  9524. quot: '"',
  9525. amp: '&',
  9526. apos: "'"
  9527. };
  9528. var reversedEscapeChars = {};
  9529. for(var key in escapeChars) reversedEscapeChars[escapeChars[key]] = key;
  9530. reversedEscapeChars["'"] = '#39';
  9531. // sprintf() for JavaScript 0.7-beta1
  9532. // http://www.diveintojavascript.com/projects/javascript-sprintf
  9533. //
  9534. // Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
  9535. // All rights reserved.
  9536. var sprintf = (function() {
  9537. function get_type(variable) {
  9538. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  9539. }
  9540. var str_repeat = strRepeat;
  9541. var str_format = function() {
  9542. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  9543. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  9544. }
  9545. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  9546. };
  9547. str_format.format = function(parse_tree, argv) {
  9548. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  9549. for (i = 0; i < tree_length; i++) {
  9550. node_type = get_type(parse_tree[i]);
  9551. if (node_type === 'string') {
  9552. output.push(parse_tree[i]);
  9553. }
  9554. else if (node_type === 'array') {
  9555. match = parse_tree[i]; // convenience purposes only
  9556. if (match[2]) { // keyword argument
  9557. arg = argv[cursor];
  9558. for (k = 0; k < match[2].length; k++) {
  9559. if (!arg.hasOwnProperty(match[2][k])) {
  9560. throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k]));
  9561. }
  9562. arg = arg[match[2][k]];
  9563. }
  9564. } else if (match[1]) { // positional argument (explicit)
  9565. arg = argv[match[1]];
  9566. }
  9567. else { // positional argument (implicit)
  9568. arg = argv[cursor++];
  9569. }
  9570. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  9571. throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg)));
  9572. }
  9573. switch (match[8]) {
  9574. case 'b': arg = arg.toString(2); break;
  9575. case 'c': arg = String.fromCharCode(arg); break;
  9576. case 'd': arg = parseInt(arg, 10); break;
  9577. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  9578. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  9579. case 'o': arg = arg.toString(8); break;
  9580. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  9581. case 'u': arg = Math.abs(arg); break;
  9582. case 'x': arg = arg.toString(16); break;
  9583. case 'X': arg = arg.toString(16).toUpperCase(); break;
  9584. }
  9585. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  9586. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  9587. pad_length = match[6] - String(arg).length;
  9588. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  9589. output.push(match[5] ? arg + pad : pad + arg);
  9590. }
  9591. }
  9592. return output.join('');
  9593. };
  9594. str_format.cache = {};
  9595. str_format.parse = function(fmt) {
  9596. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  9597. while (_fmt) {
  9598. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  9599. parse_tree.push(match[0]);
  9600. }
  9601. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  9602. parse_tree.push('%');
  9603. }
  9604. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  9605. if (match[2]) {
  9606. arg_names |= 1;
  9607. var field_list = [], replacement_field = match[2], field_match = [];
  9608. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  9609. field_list.push(field_match[1]);
  9610. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  9611. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  9612. field_list.push(field_match[1]);
  9613. }
  9614. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  9615. field_list.push(field_match[1]);
  9616. }
  9617. else {
  9618. throw new Error('[_.sprintf] huh?');
  9619. }
  9620. }
  9621. }
  9622. else {
  9623. throw new Error('[_.sprintf] huh?');
  9624. }
  9625. match[2] = field_list;
  9626. }
  9627. else {
  9628. arg_names |= 2;
  9629. }
  9630. if (arg_names === 3) {
  9631. throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported');
  9632. }
  9633. parse_tree.push(match);
  9634. }
  9635. else {
  9636. throw new Error('[_.sprintf] huh?');
  9637. }
  9638. _fmt = _fmt.substring(match[0].length);
  9639. }
  9640. return parse_tree;
  9641. };
  9642. return str_format;
  9643. })();
  9644. // Defining underscore.string
  9645. var _s = {
  9646. VERSION: '2.3.0',
  9647. isBlank: function(str){
  9648. if (str == null) str = '';
  9649. return (/^\s*$/).test(str);
  9650. },
  9651. stripTags: function(str){
  9652. if (str == null) return '';
  9653. return String(str).replace(/<\/?[^>]+>/g, '');
  9654. },
  9655. capitalize : function(str){
  9656. str = str == null ? '' : String(str);
  9657. return str.charAt(0).toUpperCase() + str.slice(1);
  9658. },
  9659. chop: function(str, step){
  9660. if (str == null) return [];
  9661. str = String(str);
  9662. step = ~~step;
  9663. return step > 0 ? str.match(new RegExp('.{1,' + step + '}', 'g')) : [str];
  9664. },
  9665. clean: function(str){
  9666. return _s.strip(str).replace(/\s+/g, ' ');
  9667. },
  9668. count: function(str, substr){
  9669. if (str == null || substr == null) return 0;
  9670. str = String(str);
  9671. substr = String(substr);
  9672. var count = 0,
  9673. pos = 0,
  9674. length = substr.length;
  9675. while (true) {
  9676. pos = str.indexOf(substr, pos);
  9677. if (pos === -1) break;
  9678. count++;
  9679. pos += length;
  9680. }
  9681. return count;
  9682. },
  9683. chars: function(str) {
  9684. if (str == null) return [];
  9685. return String(str).split('');
  9686. },
  9687. swapCase: function(str) {
  9688. if (str == null) return '';
  9689. return String(str).replace(/\S/g, function(c){
  9690. return c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase();
  9691. });
  9692. },
  9693. escapeHTML: function(str) {
  9694. if (str == null) return '';
  9695. return String(str).replace(/[&<>"']/g, function(m){ return '&' + reversedEscapeChars[m] + ';'; });
  9696. },
  9697. unescapeHTML: function(str) {
  9698. if (str == null) return '';
  9699. return String(str).replace(/\&([^;]+);/g, function(entity, entityCode){
  9700. var match;
  9701. if (entityCode in escapeChars) {
  9702. return escapeChars[entityCode];
  9703. } else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
  9704. return String.fromCharCode(parseInt(match[1], 16));
  9705. } else if (match = entityCode.match(/^#(\d+)$/)) {
  9706. return String.fromCharCode(~~match[1]);
  9707. } else {
  9708. return entity;
  9709. }
  9710. });
  9711. },
  9712. escapeRegExp: function(str){
  9713. if (str == null) return '';
  9714. return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  9715. },
  9716. splice: function(str, i, howmany, substr){
  9717. var arr = _s.chars(str);
  9718. arr.splice(~~i, ~~howmany, substr);
  9719. return arr.join('');
  9720. },
  9721. insert: function(str, i, substr){
  9722. return _s.splice(str, i, 0, substr);
  9723. },
  9724. include: function(str, needle){
  9725. if (needle === '') return true;
  9726. if (str == null) return false;
  9727. return String(str).indexOf(needle) !== -1;
  9728. },
  9729. join: function() {
  9730. var args = slice.call(arguments),
  9731. separator = args.shift();
  9732. if (separator == null) separator = '';
  9733. return args.join(separator);
  9734. },
  9735. lines: function(str) {
  9736. if (str == null) return [];
  9737. return String(str).split("\n");
  9738. },
  9739. reverse: function(str){
  9740. return _s.chars(str).reverse().join('');
  9741. },
  9742. startsWith: function(str, starts){
  9743. if (starts === '') return true;
  9744. if (str == null || starts == null) return false;
  9745. str = String(str); starts = String(starts);
  9746. return str.length >= starts.length && str.slice(0, starts.length) === starts;
  9747. },
  9748. endsWith: function(str, ends){
  9749. if (ends === '') return true;
  9750. if (str == null || ends == null) return false;
  9751. str = String(str); ends = String(ends);
  9752. return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
  9753. },
  9754. succ: function(str){
  9755. if (str == null) return '';
  9756. str = String(str);
  9757. return str.slice(0, -1) + String.fromCharCode(str.charCodeAt(str.length-1) + 1);
  9758. },
  9759. titleize: function(str){
  9760. if (str == null) return '';
  9761. str = String(str).toLowerCase();
  9762. return str.replace(/(?:^|\s|-)\S/g, function(c){ return c.toUpperCase(); });
  9763. },
  9764. camelize: function(str){
  9765. return _s.trim(str).replace(/[-_\s]+(.)?/g, function(match, c){ return c ? c.toUpperCase() : ""; });
  9766. },
  9767. underscored: function(str){
  9768. return _s.trim(str).replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
  9769. },
  9770. dasherize: function(str){
  9771. return _s.trim(str).replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase();
  9772. },
  9773. classify: function(str){
  9774. return _s.titleize(String(str).replace(/[\W_]/g, ' ')).replace(/\s/g, '');
  9775. },
  9776. humanize: function(str){
  9777. return _s.capitalize(_s.underscored(str).replace(/_id$/,'').replace(/_/g, ' '));
  9778. },
  9779. trim: function(str, characters){
  9780. if (str == null) return '';
  9781. if (!characters && nativeTrim) return nativeTrim.call(str);
  9782. characters = defaultToWhiteSpace(characters);
  9783. return String(str).replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
  9784. },
  9785. ltrim: function(str, characters){
  9786. if (str == null) return '';
  9787. if (!characters && nativeTrimLeft) return nativeTrimLeft.call(str);
  9788. characters = defaultToWhiteSpace(characters);
  9789. return String(str).replace(new RegExp('^' + characters + '+'), '');
  9790. },
  9791. rtrim: function(str, characters){
  9792. if (str == null) return '';
  9793. if (!characters && nativeTrimRight) return nativeTrimRight.call(str);
  9794. characters = defaultToWhiteSpace(characters);
  9795. return String(str).replace(new RegExp(characters + '+$'), '');
  9796. },
  9797. truncate: function(str, length, truncateStr){
  9798. if (str == null) return '';
  9799. str = String(str); truncateStr = truncateStr || '...';
  9800. length = ~~length;
  9801. return str.length > length ? str.slice(0, length) + truncateStr : str;
  9802. },
  9803. /**
  9804. * _s.prune: a more elegant version of truncate
  9805. * prune extra chars, never leaving a half-chopped word.
  9806. * @author github.com/rwz
  9807. */
  9808. prune: function(str, length, pruneStr){
  9809. if (str == null) return '';
  9810. str = String(str); length = ~~length;
  9811. pruneStr = pruneStr != null ? String(pruneStr) : '...';
  9812. if (str.length <= length) return str;
  9813. var tmpl = function(c){ return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' '; },
  9814. template = str.slice(0, length+1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
  9815. if (template.slice(template.length-2).match(/\w\w/))
  9816. template = template.replace(/\s*\S+$/, '');
  9817. else
  9818. template = _s.rtrim(template.slice(0, template.length-1));
  9819. return (template+pruneStr).length > str.length ? str : str.slice(0, template.length)+pruneStr;
  9820. },
  9821. words: function(str, delimiter) {
  9822. if (_s.isBlank(str)) return [];
  9823. return _s.trim(str, delimiter).split(delimiter || /\s+/);
  9824. },
  9825. pad: function(str, length, padStr, type) {
  9826. str = str == null ? '' : String(str);
  9827. length = ~~length;
  9828. var padlen = 0;
  9829. if (!padStr)
  9830. padStr = ' ';
  9831. else if (padStr.length > 1)
  9832. padStr = padStr.charAt(0);
  9833. switch(type) {
  9834. case 'right':
  9835. padlen = length - str.length;
  9836. return str + strRepeat(padStr, padlen);
  9837. case 'both':
  9838. padlen = length - str.length;
  9839. return strRepeat(padStr, Math.ceil(padlen/2)) + str
  9840. + strRepeat(padStr, Math.floor(padlen/2));
  9841. default: // 'left'
  9842. padlen = length - str.length;
  9843. return strRepeat(padStr, padlen) + str;
  9844. }
  9845. },
  9846. lpad: function(str, length, padStr) {
  9847. return _s.pad(str, length, padStr);
  9848. },
  9849. rpad: function(str, length, padStr) {
  9850. return _s.pad(str, length, padStr, 'right');
  9851. },
  9852. lrpad: function(str, length, padStr) {
  9853. return _s.pad(str, length, padStr, 'both');
  9854. },
  9855. sprintf: sprintf,
  9856. vsprintf: function(fmt, argv){
  9857. argv.unshift(fmt);
  9858. return sprintf.apply(null, argv);
  9859. },
  9860. toNumber: function(str, decimals) {
  9861. if (!str) return 0;
  9862. str = _s.trim(str);
  9863. if (!str.match(/^-?\d+(?:\.\d+)?$/)) return NaN;
  9864. return parseNumber(parseNumber(str).toFixed(~~decimals));
  9865. },
  9866. numberFormat : function(number, dec, dsep, tsep) {
  9867. if (isNaN(number) || number == null) return '';
  9868. number = number.toFixed(~~dec);
  9869. tsep = typeof tsep == 'string' ? tsep : ',';
  9870. var parts = number.split('.'), fnums = parts[0],
  9871. decimals = parts[1] ? (dsep || '.') + parts[1] : '';
  9872. return fnums.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + tsep) + decimals;
  9873. },
  9874. strRight: function(str, sep){
  9875. if (str == null) return '';
  9876. str = String(str); sep = sep != null ? String(sep) : sep;
  9877. var pos = !sep ? -1 : str.indexOf(sep);
  9878. return ~pos ? str.slice(pos+sep.length, str.length) : str;
  9879. },
  9880. strRightBack: function(str, sep){
  9881. if (str == null) return '';
  9882. str = String(str); sep = sep != null ? String(sep) : sep;
  9883. var pos = !sep ? -1 : str.lastIndexOf(sep);
  9884. return ~pos ? str.slice(pos+sep.length, str.length) : str;
  9885. },
  9886. strLeft: function(str, sep){
  9887. if (str == null) return '';
  9888. str = String(str); sep = sep != null ? String(sep) : sep;
  9889. var pos = !sep ? -1 : str.indexOf(sep);
  9890. return ~pos ? str.slice(0, pos) : str;
  9891. },
  9892. strLeftBack: function(str, sep){
  9893. if (str == null) return '';
  9894. str += ''; sep = sep != null ? ''+sep : sep;
  9895. var pos = str.lastIndexOf(sep);
  9896. return ~pos ? str.slice(0, pos) : str;
  9897. },
  9898. toSentence: function(array, separator, lastSeparator, serial) {
  9899. separator = separator || ', ';
  9900. lastSeparator = lastSeparator || ' and ';
  9901. var a = array.slice(), lastMember = a.pop();
  9902. if (array.length > 2 && serial) lastSeparator = _s.rtrim(separator) + lastSeparator;
  9903. return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
  9904. },
  9905. toSentenceSerial: function() {
  9906. var args = slice.call(arguments);
  9907. args[3] = true;
  9908. return _s.toSentence.apply(_s, args);
  9909. },
  9910. slugify: function(str) {
  9911. if (str == null) return '';
  9912. var from = "ąàáäâãåæăćęèéëêìíïîłńòóöôõøśșțùúüûñçżź",
  9913. to = "aaaaaaaaaceeeeeiiiilnoooooosstuuuunczz",
  9914. regex = new RegExp(defaultToWhiteSpace(from), 'g');
  9915. str = String(str).toLowerCase().replace(regex, function(c){
  9916. var index = from.indexOf(c);
  9917. return to.charAt(index) || '-';
  9918. });
  9919. return _s.dasherize(str.replace(/[^\w\s-]/g, ''));
  9920. },
  9921. surround: function(str, wrapper) {
  9922. return [wrapper, str, wrapper].join('');
  9923. },
  9924. quote: function(str, quoteChar) {
  9925. return _s.surround(str, quoteChar || '"');
  9926. },
  9927. unquote: function(str, quoteChar) {
  9928. quoteChar = quoteChar || '"';
  9929. if (str[0] === quoteChar && str[str.length-1] === quoteChar)
  9930. return str.slice(1,str.length-1);
  9931. else return str;
  9932. },
  9933. exports: function() {
  9934. var result = {};
  9935. for (var prop in this) {
  9936. if (!this.hasOwnProperty(prop) || prop.match(/^(?:include|contains|reverse)$/)) continue;
  9937. result[prop] = this[prop];
  9938. }
  9939. return result;
  9940. },
  9941. repeat: function(str, qty, separator){
  9942. if (str == null) return '';
  9943. qty = ~~qty;
  9944. // using faster implementation if separator is not needed;
  9945. if (separator == null) return strRepeat(String(str), qty);
  9946. // this one is about 300x slower in Google Chrome
  9947. for (var repeat = []; qty > 0; repeat[--qty] = str) {}
  9948. return repeat.join(separator);
  9949. },
  9950. naturalCmp: function(str1, str2){
  9951. if (str1 == str2) return 0;
  9952. if (!str1) return -1;
  9953. if (!str2) return 1;
  9954. var cmpRegex = /(\.\d+)|(\d+)|(\D+)/g,
  9955. tokens1 = String(str1).toLowerCase().match(cmpRegex),
  9956. tokens2 = String(str2).toLowerCase().match(cmpRegex),
  9957. count = Math.min(tokens1.length, tokens2.length);
  9958. for(var i = 0; i < count; i++) {
  9959. var a = tokens1[i], b = tokens2[i];
  9960. if (a !== b){
  9961. var num1 = parseInt(a, 10);
  9962. if (!isNaN(num1)){
  9963. var num2 = parseInt(b, 10);
  9964. if (!isNaN(num2) && num1 - num2)
  9965. return num1 - num2;
  9966. }
  9967. return a < b ? -1 : 1;
  9968. }
  9969. }
  9970. if (tokens1.length === tokens2.length)
  9971. return tokens1.length - tokens2.length;
  9972. return str1 < str2 ? -1 : 1;
  9973. },
  9974. levenshtein: function(str1, str2) {
  9975. if (str1 == null && str2 == null) return 0;
  9976. if (str1 == null) return String(str2).length;
  9977. if (str2 == null) return String(str1).length;
  9978. str1 = String(str1); str2 = String(str2);
  9979. var current = [], prev, value;
  9980. for (var i = 0; i <= str2.length; i++)
  9981. for (var j = 0; j <= str1.length; j++) {
  9982. if (i && j)
  9983. if (str1.charAt(j - 1) === str2.charAt(i - 1))
  9984. value = prev;
  9985. else
  9986. value = Math.min(current[j], current[j - 1], prev) + 1;
  9987. else
  9988. value = i + j;
  9989. prev = current[j];
  9990. current[j] = value;
  9991. }
  9992. return current.pop();
  9993. },
  9994. toBoolean: function(str, trueValues, falseValues) {
  9995. if (typeof str === "number") str = "" + str;
  9996. if (typeof str !== "string") return !!str;
  9997. str = _s.trim(str);
  9998. if (boolMatch(str, trueValues || ["true", "1"])) return true;
  9999. if (boolMatch(str, falseValues || ["false", "0"])) return false;
  10000. }
  10001. };
  10002. // Aliases
  10003. _s.strip = _s.trim;
  10004. _s.lstrip = _s.ltrim;
  10005. _s.rstrip = _s.rtrim;
  10006. _s.center = _s.lrpad;
  10007. _s.rjust = _s.lpad;
  10008. _s.ljust = _s.rpad;
  10009. _s.contains = _s.include;
  10010. _s.q = _s.quote;
  10011. _s.toBool = _s.toBoolean;
  10012. // Exporting
  10013. // CommonJS module is defined
  10014. if (typeof exports !== 'undefined') {
  10015. if (typeof module !== 'undefined' && module.exports)
  10016. module.exports = _s;
  10017. exports._s = _s;
  10018. }
  10019. // Register as a named module with AMD.
  10020. if (typeof define === 'function' && define.amd)
  10021. define('underscore.string', [], function(){ return _s; });
  10022. // Integrate with Underscore.js if defined
  10023. // or create our own underscore object.
  10024. root._ = root._ || {};
  10025. root._.string = root._.str = _s;
  10026. }(this, String);
  10027. },{}]},{},[19])
  10028. ;
  10029. //# sourceMappingURL=framer.js.map