lodash.js 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258
  1. /*!
  2. * Lo-Dash v0.9.2 <http://lodash.com>
  3. * (c) 2012 John-David Dalton <http://allyoucanleet.com/>
  4. * Based on Underscore.js 1.4.2 <http://underscorejs.org>
  5. * (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
  6. * Available under MIT license <http://lodash.com/license>
  7. */
  8. ;(function(window, undefined) {
  9. /** Detect free variable `exports` */
  10. var freeExports = typeof exports == 'object' && exports;
  11. /** Detect free variable `global` and use it as `window` */
  12. var freeGlobal = typeof global == 'object' && global;
  13. if (freeGlobal.global === freeGlobal) {
  14. window = freeGlobal;
  15. }
  16. /** Used for array and object method references */
  17. var arrayRef = [],
  18. // avoid a Closure Compiler bug by creatively creating an object
  19. objectRef = new function(){};
  20. /** Used to generate unique IDs */
  21. var idCounter = 0;
  22. /** Used internally to indicate various things */
  23. var indicatorObject = objectRef;
  24. /** Used by `cachedContains` as the default size when optimizations are enabled for large arrays */
  25. var largeArraySize = 30;
  26. /** Used to restore the original `_` reference in `noConflict` */
  27. var oldDash = window._;
  28. /** Used to detect template delimiter values that require a with-statement */
  29. var reComplexDelimiter = /[-?+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/;
  30. /** Used to match HTML entities */
  31. var reEscapedHtml = /&(?:amp|lt|gt|quot|#x27);/g;
  32. /** Used to match empty string literals in compiled template source */
  33. var reEmptyStringLeading = /\b__p \+= '';/g,
  34. reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
  35. reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
  36. /** Used to match regexp flags from their coerced string values */
  37. var reFlags = /\w*$/;
  38. /** Used to insert the data object variable into compiled template source */
  39. var reInsertVariable = /(?:__e|__t = )\(\s*(?![\d\s"']|this\.)/g;
  40. /** Used to detect if a method is native */
  41. var reNative = RegExp('^' +
  42. (objectRef.valueOf + '')
  43. .replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&')
  44. .replace(/valueOf|for [^\]]+/g, '.+?') + '$'
  45. );
  46. /**
  47. * Used to match ES6 template delimiters
  48. * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6
  49. */
  50. var reEsTemplate = /\$\{((?:(?=\\?)\\?[\s\S])*?)}/g;
  51. /** Used to match "interpolate" template delimiters */
  52. var reInterpolate = /<%=([\s\S]+?)%>/g;
  53. /** Used to ensure capturing order of template delimiters */
  54. var reNoMatch = /($^)/;
  55. /** Used to match HTML characters */
  56. var reUnescapedHtml = /[&<>"']/g;
  57. /** Used to match unescaped characters in compiled string literals */
  58. var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
  59. /** Used to fix the JScript [[DontEnum]] bug */
  60. var shadowed = [
  61. 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
  62. 'toLocaleString', 'toString', 'valueOf'
  63. ];
  64. /** Used to make template sourceURLs easier to identify */
  65. var templateCounter = 0;
  66. /** Native method shortcuts */
  67. var ceil = Math.ceil,
  68. concat = arrayRef.concat,
  69. floor = Math.floor,
  70. getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
  71. hasOwnProperty = objectRef.hasOwnProperty,
  72. push = arrayRef.push,
  73. propertyIsEnumerable = objectRef.propertyIsEnumerable,
  74. slice = arrayRef.slice,
  75. toString = objectRef.toString;
  76. /* Native method shortcuts for methods with the same name as other `lodash` methods */
  77. var nativeBind = reNative.test(nativeBind = slice.bind) && nativeBind,
  78. nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
  79. nativeIsFinite = window.isFinite,
  80. nativeIsNaN = window.isNaN,
  81. nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys,
  82. nativeMax = Math.max,
  83. nativeMin = Math.min,
  84. nativeRandom = Math.random;
  85. /** `Object#toString` result shortcuts */
  86. var argsClass = '[object Arguments]',
  87. arrayClass = '[object Array]',
  88. boolClass = '[object Boolean]',
  89. dateClass = '[object Date]',
  90. funcClass = '[object Function]',
  91. numberClass = '[object Number]',
  92. objectClass = '[object Object]',
  93. regexpClass = '[object RegExp]',
  94. stringClass = '[object String]';
  95. /**
  96. * Detect the JScript [[DontEnum]] bug:
  97. *
  98. * In IE < 9 an objects own properties, shadowing non-enumerable ones, are
  99. * made non-enumerable as well.
  100. */
  101. var hasDontEnumBug;
  102. /** Detect if own properties are iterated after inherited properties (IE < 9) */
  103. var iteratesOwnLast;
  104. /**
  105. * Detect if `Array#shift` and `Array#splice` augment array-like objects
  106. * incorrectly:
  107. *
  108. * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()`
  109. * and `splice()` functions that fail to remove the last element, `value[0]`,
  110. * of array-like objects even though the `length` property is set to `0`.
  111. * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
  112. * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
  113. */
  114. var hasObjectSpliceBug = (hasObjectSpliceBug = { '0': 1, 'length': 1 },
  115. arrayRef.splice.call(hasObjectSpliceBug, 0, 1), hasObjectSpliceBug[0]);
  116. /** Detect if an `arguments` object's indexes are non-enumerable (IE < 9) */
  117. var noArgsEnum = true;
  118. (function() {
  119. var props = [];
  120. function ctor() { this.x = 1; }
  121. ctor.prototype = { 'valueOf': 1, 'y': 1 };
  122. for (var prop in new ctor) { props.push(prop); }
  123. for (prop in arguments) { noArgsEnum = !prop; }
  124. hasDontEnumBug = !/valueOf/.test(props);
  125. iteratesOwnLast = props[0] != 'x';
  126. }(1));
  127. /** Detect if an `arguments` object's [[Class]] is unresolvable (Firefox < 4, IE < 9) */
  128. var noArgsClass = !isArguments(arguments);
  129. /** Detect if `Array#slice` cannot be used to convert strings to arrays (Opera < 10.52) */
  130. var noArraySliceOnStrings = slice.call('x')[0] != 'x';
  131. /**
  132. * Detect lack of support for accessing string characters by index:
  133. *
  134. * IE < 8 can't access characters by index and IE 8 can only access
  135. * characters by index on string literals.
  136. */
  137. var noCharByIndex = ('x'[0] + Object('x')[0]) != 'xx';
  138. /**
  139. * Detect if a node's [[Class]] is unresolvable (IE < 9)
  140. * and that the JS engine won't error when attempting to coerce an object to
  141. * a string without a `toString` property value of `typeof` "function".
  142. */
  143. try {
  144. var noNodeClass = ({ 'toString': 0 } + '', toString.call(window.document || 0) == objectClass);
  145. } catch(e) { }
  146. /* Detect if `Function#bind` exists and is inferred to be fast (all but V8) */
  147. var isBindFast = nativeBind && /\n|Opera/.test(nativeBind + toString.call(window.opera));
  148. /* Detect if `Object.keys` exists and is inferred to be fast (IE, Opera, V8) */
  149. var isKeysFast = nativeKeys && /^.+$|true/.test(nativeKeys + !!window.attachEvent);
  150. /**
  151. * Detect if sourceURL syntax is usable without erroring:
  152. *
  153. * The JS engine in Adobe products, like InDesign, will throw a syntax error
  154. * when it encounters a single line comment beginning with the `@` symbol.
  155. *
  156. * The JS engine in Narwhal will generate the function `function anonymous(){//}`
  157. * and throw a syntax error.
  158. *
  159. * Avoid comments beginning `@` symbols in IE because they are part of its
  160. * non-standard conditional compilation support.
  161. * http://msdn.microsoft.com/en-us/library/121hztk3(v=vs.94).aspx
  162. */
  163. try {
  164. var useSourceURL = (Function('//@')(), !window.attachEvent);
  165. } catch(e) { }
  166. /** Used to identify object classifications that `_.clone` supports */
  167. var cloneableClasses = {};
  168. cloneableClasses[argsClass] = cloneableClasses[funcClass] = false;
  169. cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] =
  170. cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] =
  171. cloneableClasses[stringClass] = true;
  172. /** Used to determine if values are of the language type Object */
  173. var objectTypes = {
  174. 'boolean': false,
  175. 'function': true,
  176. 'object': true,
  177. 'number': false,
  178. 'string': false,
  179. 'undefined': false
  180. };
  181. /** Used to escape characters for inclusion in compiled string literals */
  182. var stringEscapes = {
  183. '\\': '\\',
  184. "'": "'",
  185. '\n': 'n',
  186. '\r': 'r',
  187. '\t': 't',
  188. '\u2028': 'u2028',
  189. '\u2029': 'u2029'
  190. };
  191. /*--------------------------------------------------------------------------*/
  192. /**
  193. * The `lodash` function.
  194. *
  195. * @name _
  196. * @constructor
  197. * @category Chaining
  198. * @param {Mixed} value The value to wrap in a `lodash` instance.
  199. * @returns {Object} Returns a `lodash` instance.
  200. */
  201. function lodash(value) {
  202. // exit early if already wrapped
  203. if (value && value.__wrapped__) {
  204. return value;
  205. }
  206. // allow invoking `lodash` without the `new` operator
  207. if (!(this instanceof lodash)) {
  208. return new lodash(value);
  209. }
  210. this.__wrapped__ = value;
  211. }
  212. /**
  213. * By default, the template delimiters used by Lo-Dash are similar to those in
  214. * embedded Ruby (ERB). Change the following template settings to use alternative
  215. * delimiters.
  216. *
  217. * @static
  218. * @memberOf _
  219. * @type Object
  220. */
  221. lodash.templateSettings = {
  222. /**
  223. * Used to detect `data` property values to be HTML-escaped.
  224. *
  225. * @static
  226. * @memberOf _.templateSettings
  227. * @type RegExp
  228. */
  229. 'escape': /<%-([\s\S]+?)%>/g,
  230. /**
  231. * Used to detect code to be evaluated.
  232. *
  233. * @static
  234. * @memberOf _.templateSettings
  235. * @type RegExp
  236. */
  237. 'evaluate': /<%([\s\S]+?)%>/g,
  238. /**
  239. * Used to detect `data` property values to inject.
  240. *
  241. * @static
  242. * @memberOf _.templateSettings
  243. * @type RegExp
  244. */
  245. 'interpolate': reInterpolate,
  246. /**
  247. * Used to reference the data object in the template text.
  248. *
  249. * @static
  250. * @memberOf _.templateSettings
  251. * @type String
  252. */
  253. 'variable': ''
  254. };
  255. /*--------------------------------------------------------------------------*/
  256. /**
  257. * The template used to create iterator functions.
  258. *
  259. * @private
  260. * @param {Obect} data The data object used to populate the text.
  261. * @returns {String} Returns the interpolated text.
  262. */
  263. var iteratorTemplate = template(
  264. // conditional strict mode
  265. '<% if (obj.useStrict) { %>\'use strict\';\n<% } %>' +
  266. // the `iteratee` may be reassigned by the `top` snippet
  267. 'var index, value, iteratee = <%= firstArg %>, ' +
  268. // assign the `result` variable an initial value
  269. 'result = <%= firstArg %>;\n' +
  270. // exit early if the first argument is falsey
  271. 'if (!<%= firstArg %>) return result;\n' +
  272. // add code before the iteration branches
  273. '<%= top %>;\n' +
  274. // array-like iteration:
  275. '<% if (arrayLoop) { %>' +
  276. 'var length = iteratee.length; index = -1;\n' +
  277. 'if (typeof length == \'number\') {' +
  278. // add support for accessing string characters by index if needed
  279. ' <% if (noCharByIndex) { %>\n' +
  280. ' if (isString(iteratee)) {\n' +
  281. ' iteratee = iteratee.split(\'\')\n' +
  282. ' }' +
  283. ' <% } %>\n' +
  284. // iterate over the array-like value
  285. ' while (++index < length) {\n' +
  286. ' value = iteratee[index];\n' +
  287. ' <%= arrayLoop %>\n' +
  288. ' }\n' +
  289. '}\n' +
  290. 'else {' +
  291. // object iteration:
  292. // add support for iterating over `arguments` objects if needed
  293. ' <% } else if (noArgsEnum) { %>\n' +
  294. ' var length = iteratee.length; index = -1;\n' +
  295. ' if (length && isArguments(iteratee)) {\n' +
  296. ' while (++index < length) {\n' +
  297. ' value = iteratee[index += \'\'];\n' +
  298. ' <%= objectLoop %>\n' +
  299. ' }\n' +
  300. ' } else {' +
  301. ' <% } %>' +
  302. // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
  303. // (if the prototype or a property on the prototype has been set)
  304. // incorrectly sets a function's `prototype` property [[Enumerable]]
  305. // value to `true`. Because of this Lo-Dash standardizes on skipping
  306. // the the `prototype` property of functions regardless of its
  307. // [[Enumerable]] value.
  308. ' <% if (!hasDontEnumBug) { %>\n' +
  309. ' var skipProto = typeof iteratee == \'function\' && \n' +
  310. ' propertyIsEnumerable.call(iteratee, \'prototype\');\n' +
  311. ' <% } %>' +
  312. // iterate own properties using `Object.keys` if it's fast
  313. ' <% if (isKeysFast && useHas) { %>\n' +
  314. ' var ownIndex = -1,\n' +
  315. ' ownProps = objectTypes[typeof iteratee] ? nativeKeys(iteratee) : [],\n' +
  316. ' length = ownProps.length;\n\n' +
  317. ' while (++ownIndex < length) {\n' +
  318. ' index = ownProps[ownIndex];\n' +
  319. ' <% if (!hasDontEnumBug) { %>if (!(skipProto && index == \'prototype\')) {\n <% } %>' +
  320. ' value = iteratee[index];\n' +
  321. ' <%= objectLoop %>\n' +
  322. ' <% if (!hasDontEnumBug) { %>}\n<% } %>' +
  323. ' }' +
  324. // else using a for-in loop
  325. ' <% } else { %>\n' +
  326. ' for (index in iteratee) {<%' +
  327. ' if (!hasDontEnumBug || useHas) { %>\n if (<%' +
  328. ' if (!hasDontEnumBug) { %>!(skipProto && index == \'prototype\')<% }' +
  329. ' if (!hasDontEnumBug && useHas) { %> && <% }' +
  330. ' if (useHas) { %>hasOwnProperty.call(iteratee, index)<% }' +
  331. ' %>) {' +
  332. ' <% } %>\n' +
  333. ' value = iteratee[index];\n' +
  334. ' <%= objectLoop %>;' +
  335. ' <% if (!hasDontEnumBug || useHas) { %>\n }<% } %>\n' +
  336. ' }' +
  337. ' <% } %>' +
  338. // Because IE < 9 can't set the `[[Enumerable]]` attribute of an
  339. // existing property and the `constructor` property of a prototype
  340. // defaults to non-enumerable, Lo-Dash skips the `constructor`
  341. // property when it infers it's iterating over a `prototype` object.
  342. ' <% if (hasDontEnumBug) { %>\n\n' +
  343. ' var ctor = iteratee.constructor;\n' +
  344. ' <% for (var k = 0; k < 7; k++) { %>\n' +
  345. ' index = \'<%= shadowed[k] %>\';\n' +
  346. ' if (<%' +
  347. ' if (shadowed[k] == \'constructor\') {' +
  348. ' %>!(ctor && ctor.prototype === iteratee) && <%' +
  349. ' } %>hasOwnProperty.call(iteratee, index)) {\n' +
  350. ' value = iteratee[index];\n' +
  351. ' <%= objectLoop %>\n' +
  352. ' }' +
  353. ' <% } %>' +
  354. ' <% } %>' +
  355. ' <% if (arrayLoop || noArgsEnum) { %>\n}<% } %>\n' +
  356. // add code to the bottom of the iteration function
  357. '<%= bottom %>;\n' +
  358. // finally, return the `result`
  359. 'return result'
  360. );
  361. /**
  362. * Reusable iterator options shared by `forEach`, `forIn`, and `forOwn`.
  363. */
  364. var forEachIteratorOptions = {
  365. 'args': 'collection, callback, thisArg',
  366. 'top': 'callback = createCallback(callback, thisArg)',
  367. 'arrayLoop': 'if (callback(value, index, collection) === false) return result',
  368. 'objectLoop': 'if (callback(value, index, collection) === false) return result'
  369. };
  370. /** Reusable iterator options for `defaults`, and `extend` */
  371. var extendIteratorOptions = {
  372. 'useHas': false,
  373. 'args': 'object',
  374. 'top':
  375. 'for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {\n' +
  376. ' if (iteratee = arguments[argsIndex]) {',
  377. 'objectLoop': 'result[index] = value',
  378. 'bottom': ' }\n}'
  379. };
  380. /** Reusable iterator options for `forIn` and `forOwn` */
  381. var forOwnIteratorOptions = {
  382. 'arrayLoop': null
  383. };
  384. /*--------------------------------------------------------------------------*/
  385. /**
  386. * Creates a function optimized to search large arrays for a given `value`,
  387. * starting at `fromIndex`, using strict equality for comparisons, i.e. `===`.
  388. *
  389. * @private
  390. * @param {Array} array The array to search.
  391. * @param {Mixed} value The value to search for.
  392. * @param {Number} [fromIndex=0] The index to search from.
  393. * @param {Number} [largeSize=30] The length at which an array is considered large.
  394. * @returns {Boolean} Returns `true` if `value` is found, else `false`.
  395. */
  396. function cachedContains(array, fromIndex, largeSize) {
  397. fromIndex || (fromIndex = 0);
  398. var length = array.length,
  399. isLarge = (length - fromIndex) >= (largeSize || largeArraySize);
  400. if (isLarge) {
  401. var cache = {},
  402. index = fromIndex - 1;
  403. while (++index < length) {
  404. // manually coerce `value` to a string because `hasOwnProperty`, in some
  405. // older versions of Firefox, coerces objects incorrectly
  406. var key = array[index] + '';
  407. (hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = [])).push(array[index]);
  408. }
  409. }
  410. return function(value) {
  411. if (isLarge) {
  412. var key = value + '';
  413. return hasOwnProperty.call(cache, key) && indexOf(cache[key], value) > -1;
  414. }
  415. return indexOf(array, value, fromIndex) > -1;
  416. }
  417. }
  418. /**
  419. * Used by `_.max` and `_.min` as the default `callback` when a given
  420. * `collection` is a string value.
  421. *
  422. * @private
  423. * @param {String} value The character to inspect.
  424. * @returns {Number} Returns the code unit of given character.
  425. */
  426. function charAtCallback(value) {
  427. return value.charCodeAt(0);
  428. }
  429. /**
  430. * Used by `sortBy` to compare transformed `collection` values, stable sorting
  431. * them in ascending order.
  432. *
  433. * @private
  434. * @param {Object} a The object to compare to `b`.
  435. * @param {Object} b The object to compare to `a`.
  436. * @returns {Number} Returns the sort order indicator of `1` or `-1`.
  437. */
  438. function compareAscending(a, b) {
  439. var ai = a.index,
  440. bi = b.index;
  441. a = a.criteria;
  442. b = b.criteria;
  443. // ensure a stable sort in V8 and other engines
  444. // http://code.google.com/p/v8/issues/detail?id=90
  445. if (a !== b) {
  446. if (a > b || a === undefined) {
  447. return 1;
  448. }
  449. if (a < b || b === undefined) {
  450. return -1;
  451. }
  452. }
  453. return ai < bi ? -1 : 1;
  454. }
  455. /**
  456. * Creates a function that, when called, invokes `func` with the `this`
  457. * binding of `thisArg` and prepends any `partailArgs` to the arguments passed
  458. * to the bound function.
  459. *
  460. * @private
  461. * @param {Function|String} func The function to bind or the method name.
  462. * @param {Mixed} [thisArg] The `this` binding of `func`.
  463. * @param {Array} partialArgs An array of arguments to be partially applied.
  464. * @returns {Function} Returns the new bound function.
  465. */
  466. function createBound(func, thisArg, partialArgs) {
  467. var isFunc = isFunction(func),
  468. isPartial = !partialArgs,
  469. methodName = func;
  470. // juggle arguments
  471. if (isPartial) {
  472. partialArgs = thisArg;
  473. }
  474. function bound() {
  475. // `Function#bind` spec
  476. // http://es5.github.com/#x15.3.4.5
  477. var args = arguments,
  478. thisBinding = isPartial ? this : thisArg;
  479. if (!isFunc) {
  480. func = thisArg[methodName];
  481. }
  482. if (partialArgs.length) {
  483. args = args.length
  484. ? partialArgs.concat(slice.call(args))
  485. : partialArgs;
  486. }
  487. if (this instanceof bound) {
  488. // get `func` instance if `bound` is invoked in a `new` expression
  489. noop.prototype = func.prototype;
  490. thisBinding = new noop;
  491. // mimic the constructor's `return` behavior
  492. // http://es5.github.com/#x13.2.2
  493. var result = func.apply(thisBinding, args);
  494. return isObject(result)
  495. ? result
  496. : thisBinding
  497. }
  498. return func.apply(thisBinding, args);
  499. }
  500. return bound;
  501. }
  502. /**
  503. * Produces an iteration callback bound to an optional `thisArg`. If `func` is
  504. * a property name, the callback will return the property value for a given element.
  505. *
  506. * @private
  507. * @param {Function|String} [func=identity|property] The function called per
  508. * iteration or property name to query.
  509. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  510. * @returns {Function} Returns a callback function.
  511. */
  512. function createCallback(func, thisArg) {
  513. if (!func) {
  514. return identity;
  515. }
  516. if (typeof func != 'function') {
  517. return function(object) {
  518. return object[func];
  519. };
  520. }
  521. if (thisArg !== undefined) {
  522. return function(value, index, object) {
  523. return func.call(thisArg, value, index, object);
  524. };
  525. }
  526. return func;
  527. }
  528. /**
  529. * Creates compiled iteration functions.
  530. *
  531. * @private
  532. * @param {Object} [options1, options2, ...] The compile options object(s).
  533. * useHas - A boolean to specify using `hasOwnProperty` checks in the object loop.
  534. * args - A string of comma separated arguments the iteration function will accept.
  535. * top - A string of code to execute before the iteration branches.
  536. * arrayLoop - A string of code to execute in the array loop.
  537. * objectLoop - A string of code to execute in the object loop.
  538. * bottom - A string of code to execute after the iteration branches.
  539. *
  540. * @returns {Function} Returns the compiled function.
  541. */
  542. function createIterator() {
  543. var data = {
  544. 'arrayLoop': '',
  545. 'bottom': '',
  546. 'hasDontEnumBug': hasDontEnumBug,
  547. 'isKeysFast': isKeysFast,
  548. 'objectLoop': '',
  549. 'noArgsEnum': noArgsEnum,
  550. 'noCharByIndex': noCharByIndex,
  551. 'shadowed': shadowed,
  552. 'top': '',
  553. 'useHas': true
  554. };
  555. // merge options into a template data object
  556. for (var object, index = 0; object = arguments[index]; index++) {
  557. for (var key in object) {
  558. data[key] = object[key];
  559. }
  560. }
  561. var args = data.args;
  562. data.firstArg = /^[^,]+/.exec(args)[0];
  563. // create the function factory
  564. var factory = Function(
  565. 'createCallback, hasOwnProperty, isArguments, isString, objectTypes, ' +
  566. 'nativeKeys, propertyIsEnumerable',
  567. 'return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}'
  568. );
  569. // return the compiled function
  570. return factory(
  571. createCallback, hasOwnProperty, isArguments, isString, objectTypes,
  572. nativeKeys, propertyIsEnumerable
  573. );
  574. }
  575. /**
  576. * Used by `template` to escape characters for inclusion in compiled
  577. * string literals.
  578. *
  579. * @private
  580. * @param {String} match The matched character to escape.
  581. * @returns {String} Returns the escaped character.
  582. */
  583. function escapeStringChar(match) {
  584. return '\\' + stringEscapes[match];
  585. }
  586. /**
  587. * Used by `escape` to convert characters to HTML entities.
  588. *
  589. * @private
  590. * @param {String} match The matched character to escape.
  591. * @returns {String} Returns the escaped character.
  592. */
  593. function escapeHtmlChar(match) {
  594. return htmlEscapes[match];
  595. }
  596. /**
  597. * A no-operation function.
  598. *
  599. * @private
  600. */
  601. function noop() {
  602. // no operation performed
  603. }
  604. /**
  605. * Used by `unescape` to convert HTML entities to characters.
  606. *
  607. * @private
  608. * @param {String} match The matched character to unescape.
  609. * @returns {String} Returns the unescaped character.
  610. */
  611. function unescapeHtmlChar(match) {
  612. return htmlUnescapes[match];
  613. }
  614. /*--------------------------------------------------------------------------*/
  615. /**
  616. * Checks if `value` is an `arguments` object.
  617. *
  618. * @static
  619. * @memberOf _
  620. * @category Objects
  621. * @param {Mixed} value The value to check.
  622. * @returns {Boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
  623. * @example
  624. *
  625. * (function() { return _.isArguments(arguments); })(1, 2, 3);
  626. * // => true
  627. *
  628. * _.isArguments([1, 2, 3]);
  629. * // => false
  630. */
  631. function isArguments(value) {
  632. return toString.call(value) == argsClass;
  633. }
  634. // fallback for browsers that can't detect `arguments` objects by [[Class]]
  635. if (noArgsClass) {
  636. isArguments = function(value) {
  637. return value ? hasOwnProperty.call(value, 'callee') : false;
  638. };
  639. }
  640. /**
  641. * Iterates over `object`'s own and inherited enumerable properties, executing
  642. * the `callback` for each property. The `callback` is bound to `thisArg` and
  643. * invoked with three arguments; (value, key, object). Callbacks may exit iteration
  644. * early by explicitly returning `false`.
  645. *
  646. * @static
  647. * @memberOf _
  648. * @category Objects
  649. * @param {Object} object The object to iterate over.
  650. * @param {Function} callback The function called per iteration.
  651. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  652. * @returns {Object} Returns `object`.
  653. * @example
  654. *
  655. * function Dog(name) {
  656. * this.name = name;
  657. * }
  658. *
  659. * Dog.prototype.bark = function() {
  660. * alert('Woof, woof!');
  661. * };
  662. *
  663. * _.forIn(new Dog('Dagny'), function(value, key) {
  664. * alert(key);
  665. * });
  666. * // => alerts 'name' and 'bark' (order is not guaranteed)
  667. */
  668. var forIn = createIterator(forEachIteratorOptions, forOwnIteratorOptions, {
  669. 'useHas': false
  670. });
  671. /**
  672. * Iterates over `object`'s own enumerable properties, executing the `callback`
  673. * for each property. The `callback` is bound to `thisArg` and invoked with three
  674. * arguments; (value, key, object). Callbacks may exit iteration early by explicitly
  675. * returning `false`.
  676. *
  677. * @static
  678. * @memberOf _
  679. * @category Objects
  680. * @param {Object} object The object to iterate over.
  681. * @param {Function} callback The function called per iteration.
  682. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  683. * @returns {Object} Returns `object`.
  684. * @example
  685. *
  686. * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
  687. * alert(key);
  688. * });
  689. * // => alerts '0', '1', and 'length' (order is not guaranteed)
  690. */
  691. var forOwn = createIterator(forEachIteratorOptions, forOwnIteratorOptions);
  692. /**
  693. * A fallback implementation of `isPlainObject` that checks if a given `value`
  694. * is an object created by the `Object` constructor, assuming objects created
  695. * by the `Object` constructor have no inherited enumerable properties and that
  696. * there are no `Object.prototype` extensions.
  697. *
  698. * @private
  699. * @param {Mixed} value The value to check.
  700. * @returns {Boolean} Returns `true` if `value` is a plain object, else `false`.
  701. */
  702. function shimIsPlainObject(value) {
  703. // avoid non-objects and false positives for `arguments` objects
  704. var result = false;
  705. if (!(value && typeof value == 'object') || isArguments(value)) {
  706. return result;
  707. }
  708. // IE < 9 presents DOM nodes as `Object` objects except they have `toString`
  709. // methods that are `typeof` "string" and still can coerce nodes to strings.
  710. // Also check that the constructor is `Object` (i.e. `Object instanceof Object`)
  711. var ctor = value.constructor;
  712. if ((!noNodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) &&
  713. (!isFunction(ctor) || ctor instanceof ctor)) {
  714. // IE < 9 iterates inherited properties before own properties. If the first
  715. // iterated property is an object's own property then there are no inherited
  716. // enumerable properties.
  717. if (iteratesOwnLast) {
  718. forIn(value, function(value, key, object) {
  719. result = !hasOwnProperty.call(object, key);
  720. return false;
  721. });
  722. return result === false;
  723. }
  724. // In most environments an object's own properties are iterated before
  725. // its inherited properties. If the last iterated property is an object's
  726. // own property then there are no inherited enumerable properties.
  727. forIn(value, function(value, key) {
  728. result = key;
  729. });
  730. return result === false || hasOwnProperty.call(value, result);
  731. }
  732. return result;
  733. }
  734. /**
  735. * A fallback implementation of `Object.keys` that produces an array of the
  736. * given object's own enumerable property names.
  737. *
  738. * @private
  739. * @param {Object} object The object to inspect.
  740. * @returns {Array} Returns a new array of property names.
  741. */
  742. function shimKeys(object) {
  743. var result = [];
  744. forOwn(object, function(value, key) {
  745. result.push(key);
  746. });
  747. return result;
  748. }
  749. /**
  750. * Used to convert characters to HTML entities:
  751. *
  752. * Though the `>` character is escaped for symmetry, characters like `>` and `/`
  753. * don't require escaping in HTML and have no special meaning unless they're part
  754. * of a tag or an unquoted attribute value.
  755. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
  756. */
  757. var htmlEscapes = {
  758. '&': '&amp;',
  759. '<': '&lt;',
  760. '>': '&gt;',
  761. '"': '&quot;',
  762. "'": '&#x27;'
  763. };
  764. /** Used to convert HTML entities to characters */
  765. var htmlUnescapes = invert(htmlEscapes);
  766. /*--------------------------------------------------------------------------*/
  767. /**
  768. * Creates a clone of `value`. If `deep` is `true`, all nested objects will
  769. * also be cloned otherwise they will be assigned by reference. Functions, DOM
  770. * nodes, `arguments` objects, and objects created by constructors other than
  771. * `Object` are **not** cloned.
  772. *
  773. * @static
  774. * @memberOf _
  775. * @category Objects
  776. * @param {Mixed} value The value to clone.
  777. * @param {Boolean} deep A flag to indicate a deep clone.
  778. * @param- {Object} [guard] Internally used to allow this method to work with
  779. * others like `_.map` without using their callback `index` argument for `deep`.
  780. * @param- {Array} [stackA=[]] Internally used to track traversed source objects.
  781. * @param- {Array} [stackB=[]] Internally used to associate clones with their
  782. * source counterparts.
  783. * @returns {Mixed} Returns the cloned `value`.
  784. * @example
  785. *
  786. * var stooges = [
  787. * { 'name': 'moe', 'age': 40 },
  788. * { 'name': 'larry', 'age': 50 },
  789. * { 'name': 'curly', 'age': 60 }
  790. * ];
  791. *
  792. * _.clone({ 'name': 'moe' });
  793. * // => { 'name': 'moe' }
  794. *
  795. * var shallow = _.clone(stooges);
  796. * shallow[0] === stooges[0];
  797. * // => true
  798. *
  799. * var deep = _.clone(stooges, true);
  800. * shallow[0] === stooges[0];
  801. * // => false
  802. */
  803. function clone(value, deep, guard, stackA, stackB) {
  804. if (value == null) {
  805. return value;
  806. }
  807. if (guard) {
  808. deep = false;
  809. }
  810. // inspect [[Class]]
  811. var isObj = isObject(value);
  812. if (isObj) {
  813. // don't clone `arguments` objects, functions, or non-object Objects
  814. var className = toString.call(value);
  815. if (!cloneableClasses[className] || (noArgsClass && isArguments(value))) {
  816. return value;
  817. }
  818. var isArr = className == arrayClass;
  819. isObj = isArr || (className == objectClass ? isPlainObject(value) : isObj);
  820. }
  821. // shallow clone
  822. if (!isObj || !deep) {
  823. // don't clone functions
  824. return isObj
  825. ? (isArr ? slice.call(value) : extend({}, value))
  826. : value;
  827. }
  828. var ctor = value.constructor;
  829. switch (className) {
  830. case boolClass:
  831. case dateClass:
  832. return new ctor(+value);
  833. case numberClass:
  834. case stringClass:
  835. return new ctor(value);
  836. case regexpClass:
  837. return ctor(value.source, reFlags.exec(value));
  838. }
  839. // check for circular references and return corresponding clone
  840. stackA || (stackA = []);
  841. stackB || (stackB = []);
  842. var length = stackA.length;
  843. while (length--) {
  844. if (stackA[length] == value) {
  845. return stackB[length];
  846. }
  847. }
  848. // init cloned object
  849. var result = isArr ? ctor(value.length) : {};
  850. // add the source value to the stack of traversed objects
  851. // and associate it with its clone
  852. stackA.push(value);
  853. stackB.push(result);
  854. // recursively populate clone (susceptible to call stack limits)
  855. (isArr ? forEach : forOwn)(value, function(objValue, key) {
  856. result[key] = clone(objValue, deep, null, stackA, stackB);
  857. });
  858. return result;
  859. }
  860. /**
  861. * Assigns enumerable properties of the default object(s) to the `destination`
  862. * object for all `destination` properties that resolve to `null`/`undefined`.
  863. * Once a property is set, additional defaults of the same property will be
  864. * ignored.
  865. *
  866. * @static
  867. * @memberOf _
  868. * @category Objects
  869. * @param {Object} object The destination object.
  870. * @param {Object} [default1, default2, ...] The default objects.
  871. * @returns {Object} Returns the destination object.
  872. * @example
  873. *
  874. * var iceCream = { 'flavor': 'chocolate' };
  875. * _.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' });
  876. * // => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' }
  877. */
  878. var defaults = createIterator(extendIteratorOptions, {
  879. 'objectLoop': 'if (result[index] == null) ' + extendIteratorOptions.objectLoop
  880. });
  881. /**
  882. * Assigns enumerable properties of the source object(s) to the `destination`
  883. * object. Subsequent sources will overwrite propery assignments of previous
  884. * sources.
  885. *
  886. * @static
  887. * @memberOf _
  888. * @category Objects
  889. * @param {Object} object The destination object.
  890. * @param {Object} [source1, source2, ...] The source objects.
  891. * @returns {Object} Returns the destination object.
  892. * @example
  893. *
  894. * _.extend({ 'name': 'moe' }, { 'age': 40 });
  895. * // => { 'name': 'moe', 'age': 40 }
  896. */
  897. var extend = createIterator(extendIteratorOptions);
  898. /**
  899. * Creates a sorted array of all enumerable properties, own and inherited,
  900. * of `object` that have function values.
  901. *
  902. * @static
  903. * @memberOf _
  904. * @alias methods
  905. * @category Objects
  906. * @param {Object} object The object to inspect.
  907. * @returns {Array} Returns a new array of property names that have function values.
  908. * @example
  909. *
  910. * _.functions(_);
  911. * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
  912. */
  913. function functions(object) {
  914. var result = [];
  915. forIn(object, function(value, key) {
  916. if (isFunction(value)) {
  917. result.push(key);
  918. }
  919. });
  920. return result.sort();
  921. }
  922. /**
  923. * Checks if the specified object `property` exists and is a direct property,
  924. * instead of an inherited property.
  925. *
  926. * @static
  927. * @memberOf _
  928. * @category Objects
  929. * @param {Object} object The object to check.
  930. * @param {String} property The property to check for.
  931. * @returns {Boolean} Returns `true` if key is a direct property, else `false`.
  932. * @example
  933. *
  934. * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
  935. * // => true
  936. */
  937. function has(object, property) {
  938. return object ? hasOwnProperty.call(object, property) : false;
  939. }
  940. /**
  941. * Creates an object composed of the inverted keys and values of the given `object`.
  942. *
  943. * @static
  944. * @memberOf _
  945. * @category Objects
  946. * @param {Object} object The object to invert.
  947. * @returns {Object} Returns the created inverted object.
  948. * @example
  949. *
  950. * _.invert({ 'first': 'Moe', 'second': 'Larry', 'third': 'Curly' });
  951. * // => { 'Moe': 'first', 'Larry': 'second', 'Curly': 'third' } (order is not guaranteed)
  952. */
  953. function invert(object) {
  954. var result = {};
  955. forOwn(object, function(value, key) {
  956. result[value] = key;
  957. });
  958. return result;
  959. }
  960. /**
  961. * Checks if `value` is an array.
  962. *
  963. * @static
  964. * @memberOf _
  965. * @category Objects
  966. * @param {Mixed} value The value to check.
  967. * @returns {Boolean} Returns `true` if the `value` is an array, else `false`.
  968. * @example
  969. *
  970. * (function() { return _.isArray(arguments); })();
  971. * // => false
  972. *
  973. * _.isArray([1, 2, 3]);
  974. * // => true
  975. */
  976. var isArray = nativeIsArray || function(value) {
  977. return toString.call(value) == arrayClass;
  978. };
  979. /**
  980. * Checks if `value` is a boolean (`true` or `false`) value.
  981. *
  982. * @static
  983. * @memberOf _
  984. * @category Objects
  985. * @param {Mixed} value The value to check.
  986. * @returns {Boolean} Returns `true` if the `value` is a boolean value, else `false`.
  987. * @example
  988. *
  989. * _.isBoolean(null);
  990. * // => false
  991. */
  992. function isBoolean(value) {
  993. return value === true || value === false || toString.call(value) == boolClass;
  994. }
  995. /**
  996. * Checks if `value` is a date.
  997. *
  998. * @static
  999. * @memberOf _
  1000. * @category Objects
  1001. * @param {Mixed} value The value to check.
  1002. * @returns {Boolean} Returns `true` if the `value` is a date, else `false`.
  1003. * @example
  1004. *
  1005. * _.isDate(new Date);
  1006. * // => true
  1007. */
  1008. function isDate(value) {
  1009. return toString.call(value) == dateClass;
  1010. }
  1011. /**
  1012. * Checks if `value` is a DOM element.
  1013. *
  1014. * @static
  1015. * @memberOf _
  1016. * @category Objects
  1017. * @param {Mixed} value The value to check.
  1018. * @returns {Boolean} Returns `true` if the `value` is a DOM element, else `false`.
  1019. * @example
  1020. *
  1021. * _.isElement(document.body);
  1022. * // => true
  1023. */
  1024. function isElement(value) {
  1025. return value ? value.nodeType === 1 : false;
  1026. }
  1027. /**
  1028. * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
  1029. * length of `0` and objects with no own enumerable properties are considered
  1030. * "empty".
  1031. *
  1032. * @static
  1033. * @memberOf _
  1034. * @category Objects
  1035. * @param {Array|Object|String} value The value to inspect.
  1036. * @returns {Boolean} Returns `true` if the `value` is empty, else `false`.
  1037. * @example
  1038. *
  1039. * _.isEmpty([1, 2, 3]);
  1040. * // => false
  1041. *
  1042. * _.isEmpty({});
  1043. * // => true
  1044. *
  1045. * _.isEmpty('');
  1046. * // => true
  1047. */
  1048. function isEmpty(value) {
  1049. var result = true;
  1050. if (!value) {
  1051. return result;
  1052. }
  1053. var className = toString.call(value),
  1054. length = value.length;
  1055. if ((className == arrayClass || className == stringClass ||
  1056. className == argsClass || (noArgsClass && isArguments(value))) ||
  1057. (className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
  1058. return !length;
  1059. }
  1060. forOwn(value, function() {
  1061. return (result = false);
  1062. });
  1063. return result;
  1064. }
  1065. /**
  1066. * Performs a deep comparison between two values to determine if they are
  1067. * equivalent to each other.
  1068. *
  1069. * @static
  1070. * @memberOf _
  1071. * @category Objects
  1072. * @param {Mixed} a The value to compare.
  1073. * @param {Mixed} b The other value to compare.
  1074. * @param- {Object} [stackA=[]] Internally used track traversed `a` objects.
  1075. * @param- {Object} [stackB=[]] Internally used track traversed `b` objects.
  1076. * @returns {Boolean} Returns `true` if the values are equvalent, else `false`.
  1077. * @example
  1078. *
  1079. * var moe = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
  1080. * var clone = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
  1081. *
  1082. * moe == clone;
  1083. * // => false
  1084. *
  1085. * _.isEqual(moe, clone);
  1086. * // => true
  1087. */
  1088. function isEqual(a, b, stackA, stackB) {
  1089. // exit early for identical values
  1090. if (a === b) {
  1091. // treat `+0` vs. `-0` as not equal
  1092. return a !== 0 || (1 / a == 1 / b);
  1093. }
  1094. // a strict comparison is necessary because `null == undefined`
  1095. if (a == null || b == null) {
  1096. return a === b;
  1097. }
  1098. // compare [[Class]] names
  1099. var className = toString.call(a);
  1100. if (className != toString.call(b)) {
  1101. return false;
  1102. }
  1103. switch (className) {
  1104. case boolClass:
  1105. case dateClass:
  1106. // coerce dates and booleans to numbers, dates to milliseconds and booleans
  1107. // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
  1108. return +a == +b;
  1109. case numberClass:
  1110. // treat `NaN` vs. `NaN` as equal
  1111. return a != +a
  1112. ? b != +b
  1113. // but treat `+0` vs. `-0` as not equal
  1114. : (a == 0 ? (1 / a == 1 / b) : a == +b);
  1115. case regexpClass:
  1116. case stringClass:
  1117. // coerce regexes to strings (http://es5.github.com/#x15.10.6.4)
  1118. // treat string primitives and their corresponding object instances as equal
  1119. return a == b + '';
  1120. }
  1121. // exit early, in older browsers, if `a` is array-like but not `b`
  1122. var isArr = className == arrayClass || className == argsClass;
  1123. if (noArgsClass && !isArr && (isArr = isArguments(a)) && !isArguments(b)) {
  1124. return false;
  1125. }
  1126. if (!isArr) {
  1127. // unwrap any `lodash` wrapped values
  1128. if (a.__wrapped__ || b.__wrapped__) {
  1129. return isEqual(a.__wrapped__ || a, b.__wrapped__ || b);
  1130. }
  1131. // exit for functions and DOM nodes
  1132. if (className != objectClass || (noNodeClass && (
  1133. (typeof a.toString != 'function' && typeof (a + '') == 'string') ||
  1134. (typeof b.toString != 'function' && typeof (b + '') == 'string')))) {
  1135. return false;
  1136. }
  1137. var ctorA = a.constructor,
  1138. ctorB = b.constructor;
  1139. // non `Object` object instances with different constructors are not equal
  1140. if (ctorA != ctorB && !(
  1141. isFunction(ctorA) && ctorA instanceof ctorA &&
  1142. isFunction(ctorB) && ctorB instanceof ctorB
  1143. )) {
  1144. return false;
  1145. }
  1146. }
  1147. // assume cyclic structures are equal
  1148. // the algorithm for detecting cyclic structures is adapted from ES 5.1
  1149. // section 15.12.3, abstract operation `JO` (http://es5.github.com/#x15.12.3)
  1150. stackA || (stackA = []);
  1151. stackB || (stackB = []);
  1152. var length = stackA.length;
  1153. while (length--) {
  1154. if (stackA[length] == a) {
  1155. return stackB[length] == b;
  1156. }
  1157. }
  1158. var index = -1,
  1159. result = true,
  1160. size = 0;
  1161. // add `a` and `b` to the stack of traversed objects
  1162. stackA.push(a);
  1163. stackB.push(b);
  1164. // recursively compare objects and arrays (susceptible to call stack limits)
  1165. if (isArr) {
  1166. // compare lengths to determine if a deep comparison is necessary
  1167. size = a.length;
  1168. result = size == b.length;
  1169. if (result) {
  1170. // deep compare the contents, ignoring non-numeric properties
  1171. while (size--) {
  1172. if (!(result = isEqual(a[size], b[size], stackA, stackB))) {
  1173. break;
  1174. }
  1175. }
  1176. }
  1177. return result;
  1178. }
  1179. // deep compare objects
  1180. for (var key in a) {
  1181. if (hasOwnProperty.call(a, key)) {
  1182. // count the number of properties.
  1183. size++;
  1184. // deep compare each property value.
  1185. if (!(hasOwnProperty.call(b, key) && isEqual(a[key], b[key], stackA, stackB))) {
  1186. return false;
  1187. }
  1188. }
  1189. }
  1190. // ensure both objects have the same number of properties
  1191. for (key in b) {
  1192. // The JS engine in Adobe products, like InDesign, has a bug that causes
  1193. // `!size--` to throw an error so it must be wrapped in parentheses.
  1194. // https://github.com/documentcloud/underscore/issues/355
  1195. if (hasOwnProperty.call(b, key) && !(size--)) {
  1196. // `size` will be `-1` if `b` has more properties than `a`
  1197. return false;
  1198. }
  1199. }
  1200. // handle JScript [[DontEnum]] bug
  1201. if (hasDontEnumBug) {
  1202. while (++index < 7) {
  1203. key = shadowed[index];
  1204. if (hasOwnProperty.call(a, key) &&
  1205. !(hasOwnProperty.call(b, key) && isEqual(a[key], b[key], stackA, stackB))) {
  1206. return false;
  1207. }
  1208. }
  1209. }
  1210. return true;
  1211. }
  1212. /**
  1213. * Checks if `value` is, or can be coerced to, a finite number.
  1214. *
  1215. * Note: This is not the same as native `isFinite`, which will return true for
  1216. * booleans and empty strings. See http://es5.github.com/#x15.1.2.5.
  1217. *
  1218. * @deprecated
  1219. * @static
  1220. * @memberOf _
  1221. * @category Objects
  1222. * @param {Mixed} value The value to check.
  1223. * @returns {Boolean} Returns `true` if the `value` is a finite number, else `false`.
  1224. * @example
  1225. *
  1226. * _.isFinite(-101);
  1227. * // => true
  1228. *
  1229. * _.isFinite('10');
  1230. * // => true
  1231. *
  1232. * _.isFinite(true);
  1233. * // => false
  1234. *
  1235. * _.isFinite('');
  1236. * // => false
  1237. *
  1238. * _.isFinite(Infinity);
  1239. * // => false
  1240. */
  1241. function isFinite(value) {
  1242. return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
  1243. }
  1244. /**
  1245. * Checks if `value` is a function.
  1246. *
  1247. * @static
  1248. * @memberOf _
  1249. * @category Objects
  1250. * @param {Mixed} value The value to check.
  1251. * @returns {Boolean} Returns `true` if the `value` is a function, else `false`.
  1252. * @example
  1253. *
  1254. * _.isFunction(_);
  1255. * // => true
  1256. */
  1257. function isFunction(value) {
  1258. return typeof value == 'function';
  1259. }
  1260. // fallback for older versions of Chrome and Safari
  1261. if (isFunction(/x/)) {
  1262. isFunction = function(value) {
  1263. return toString.call(value) == funcClass;
  1264. };
  1265. }
  1266. /**
  1267. * Checks if `value` is the language type of Object.
  1268. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  1269. *
  1270. * @static
  1271. * @memberOf _
  1272. * @category Objects
  1273. * @param {Mixed} value The value to check.
  1274. * @returns {Boolean} Returns `true` if the `value` is an object, else `false`.
  1275. * @example
  1276. *
  1277. * _.isObject({});
  1278. * // => true
  1279. *
  1280. * _.isObject([1, 2, 3]);
  1281. * // => true
  1282. *
  1283. * _.isObject(1);
  1284. * // => false
  1285. */
  1286. function isObject(value) {
  1287. // check if the value is the ECMAScript language type of Object
  1288. // http://es5.github.com/#x8
  1289. // and avoid a V8 bug
  1290. // http://code.google.com/p/v8/issues/detail?id=2291
  1291. return value ? objectTypes[typeof value] : false;
  1292. }
  1293. /**
  1294. * Checks if `value` is `NaN`.
  1295. *
  1296. * Note: This is not the same as native `isNaN`, which will return true for
  1297. * `undefined` and other values. See http://es5.github.com/#x15.1.2.4.
  1298. *
  1299. * @deprecated
  1300. * @static
  1301. * @memberOf _
  1302. * @category Objects
  1303. * @param {Mixed} value The value to check.
  1304. * @returns {Boolean} Returns `true` if the `value` is `NaN`, else `false`.
  1305. * @example
  1306. *
  1307. * _.isNaN(NaN);
  1308. * // => true
  1309. *
  1310. * _.isNaN(new Number(NaN));
  1311. * // => true
  1312. *
  1313. * isNaN(undefined);
  1314. * // => true
  1315. *
  1316. * _.isNaN(undefined);
  1317. * // => false
  1318. */
  1319. function isNaN(value) {
  1320. // `NaN` as a primitive is the only value that is not equal to itself
  1321. // (perform the [[Class]] check first to avoid errors with some host objects in IE)
  1322. return toString.call(value) == numberClass && value != +value
  1323. }
  1324. /**
  1325. * Checks if `value` is `null`.
  1326. *
  1327. * @deprecated
  1328. * @static
  1329. * @memberOf _
  1330. * @category Objects
  1331. * @param {Mixed} value The value to check.
  1332. * @returns {Boolean} Returns `true` if the `value` is `null`, else `false`.
  1333. * @example
  1334. *
  1335. * _.isNull(null);
  1336. * // => true
  1337. *
  1338. * _.isNull(undefined);
  1339. * // => false
  1340. */
  1341. function isNull(value) {
  1342. return value === null;
  1343. }
  1344. /**
  1345. * Checks if `value` is a number.
  1346. *
  1347. * @static
  1348. * @memberOf _
  1349. * @category Objects
  1350. * @param {Mixed} value The value to check.
  1351. * @returns {Boolean} Returns `true` if the `value` is a number, else `false`.
  1352. * @example
  1353. *
  1354. * _.isNumber(8.4 * 5);
  1355. * // => true
  1356. */
  1357. function isNumber(value) {
  1358. return toString.call(value) == numberClass;
  1359. }
  1360. /**
  1361. * Checks if a given `value` is an object created by the `Object` constructor.
  1362. *
  1363. * @static
  1364. * @memberOf _
  1365. * @category Objects
  1366. * @param {Mixed} value The value to check.
  1367. * @returns {Boolean} Returns `true` if `value` is a plain object, else `false`.
  1368. * @example
  1369. *
  1370. * function Stooge(name, age) {
  1371. * this.name = name;
  1372. * this.age = age;
  1373. * }
  1374. *
  1375. * _.isPlainObject(new Stooge('moe', 40));
  1376. * // => false
  1377. *
  1378. * _.isPlainObject([1, 2, 3]);
  1379. * // => false
  1380. *
  1381. * _.isPlainObject({ 'name': 'moe', 'age': 40 });
  1382. * // => true
  1383. */
  1384. var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
  1385. if (!(value && typeof value == 'object')) {
  1386. return false;
  1387. }
  1388. var valueOf = value.valueOf,
  1389. objProto = typeof valueOf == 'function' && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
  1390. return objProto
  1391. ? value == objProto || (getPrototypeOf(value) == objProto && !isArguments(value))
  1392. : shimIsPlainObject(value);
  1393. };
  1394. /**
  1395. * Checks if `value` is a regular expression.
  1396. *
  1397. * @static
  1398. * @memberOf _
  1399. * @category Objects
  1400. * @param {Mixed} value The value to check.
  1401. * @returns {Boolean} Returns `true` if the `value` is a regular expression, else `false`.
  1402. * @example
  1403. *
  1404. * _.isRegExp(/moe/);
  1405. * // => true
  1406. */
  1407. function isRegExp(value) {
  1408. return toString.call(value) == regexpClass;
  1409. }
  1410. /**
  1411. * Checks if `value` is a string.
  1412. *
  1413. * @static
  1414. * @memberOf _
  1415. * @category Objects
  1416. * @param {Mixed} value The value to check.
  1417. * @returns {Boolean} Returns `true` if the `value` is a string, else `false`.
  1418. * @example
  1419. *
  1420. * _.isString('moe');
  1421. * // => true
  1422. */
  1423. function isString(value) {
  1424. return toString.call(value) == stringClass;
  1425. }
  1426. /**
  1427. * Checks if `value` is `undefined`.
  1428. *
  1429. * @deprecated
  1430. * @static
  1431. * @memberOf _
  1432. * @category Objects
  1433. * @param {Mixed} value The value to check.
  1434. * @returns {Boolean} Returns `true` if the `value` is `undefined`, else `false`.
  1435. * @example
  1436. *
  1437. * _.isUndefined(void 0);
  1438. * // => true
  1439. */
  1440. function isUndefined(value) {
  1441. return value === undefined;
  1442. }
  1443. /**
  1444. * Creates an array composed of the own enumerable property names of `object`.
  1445. *
  1446. * @static
  1447. * @memberOf _
  1448. * @category Objects
  1449. * @param {Object} object The object to inspect.
  1450. * @returns {Array} Returns a new array of property names.
  1451. * @example
  1452. *
  1453. * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
  1454. * // => ['one', 'two', 'three'] (order is not guaranteed)
  1455. */
  1456. var keys = !nativeKeys ? shimKeys : function(object) {
  1457. // avoid iterating over the `prototype` property
  1458. return typeof object == 'function' && propertyIsEnumerable.call(object, 'prototype')
  1459. ? shimKeys(object)
  1460. : (isObject(object) ? nativeKeys(object) : []);
  1461. };
  1462. /**
  1463. * Merges enumerable properties of the source object(s) into the `destination`
  1464. * object. Subsequent sources will overwrite propery assignments of previous
  1465. * sources.
  1466. *
  1467. * @static
  1468. * @memberOf _
  1469. * @category Objects
  1470. * @param {Object} object The destination object.
  1471. * @param {Object} [source1, source2, ...] The source objects.
  1472. * @param- {Object} [indicator] Internally used to indicate that the `stack`
  1473. * argument is an array of traversed objects instead of another source object.
  1474. * @param- {Array} [stackA=[]] Internally used to track traversed source objects.
  1475. * @param- {Array} [stackB=[]] Internally used to associate values with their
  1476. * source counterparts.
  1477. * @returns {Object} Returns the destination object.
  1478. * @example
  1479. *
  1480. * var stooges = [
  1481. * { 'name': 'moe' },
  1482. * { 'name': 'larry' }
  1483. * ];
  1484. *
  1485. * var ages = [
  1486. * { 'age': 40 },
  1487. * { 'age': 50 }
  1488. * ];
  1489. *
  1490. * _.merge(stooges, ages);
  1491. * // => [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }]
  1492. */
  1493. function merge(object, source, indicator) {
  1494. var args = arguments,
  1495. index = 0,
  1496. length = 2,
  1497. stackA = args[3],
  1498. stackB = args[4];
  1499. if (indicator !== objectRef) {
  1500. stackA = [];
  1501. stackB = [];
  1502. length = args.length;
  1503. }
  1504. while (++index < length) {
  1505. forOwn(args[index], function(source, key) {
  1506. var found, isArr, value;
  1507. if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
  1508. // avoid merging previously merged cyclic sources
  1509. var stackLength = stackA.length;
  1510. while (stackLength--) {
  1511. found = stackA[stackLength] == source;
  1512. if (found) {
  1513. break;
  1514. }
  1515. }
  1516. if (found) {
  1517. object[key] = stackB[stackLength];
  1518. }
  1519. else {
  1520. // add `source` and associated `value` to the stack of traversed objects
  1521. stackA.push(source);
  1522. stackB.push(value = (value = object[key], isArr)
  1523. ? (isArray(value) ? value : [])
  1524. : (isPlainObject(value) ? value : {})
  1525. );
  1526. // recursively merge objects and arrays (susceptible to call stack limits)
  1527. object[key] = merge(value, source, objectRef, stackA, stackB);
  1528. }
  1529. } else if (source != null) {
  1530. object[key] = source;
  1531. }
  1532. });
  1533. }
  1534. return object;
  1535. }
  1536. /**
  1537. * Creates a shallow clone of `object` excluding the specified properties.
  1538. * Property names may be specified as individual arguments or as arrays of
  1539. * property names. If `callback` is passed, it will be executed for each property
  1540. * in the `object`, omitting the properties `callback` returns truthy for. The
  1541. * `callback` is bound to `thisArg` and invoked with three arguments; (value, key, object).
  1542. *
  1543. * @static
  1544. * @memberOf _
  1545. * @category Objects
  1546. * @param {Object} object The source object.
  1547. * @param {Function|String} callback|[prop1, prop2, ...] The properties to omit
  1548. * or the function called per iteration.
  1549. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1550. * @returns {Object} Returns an object without the omitted properties.
  1551. * @example
  1552. *
  1553. * _.omit({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'userid');
  1554. * // => { 'name': 'moe', 'age': 40 }
  1555. *
  1556. * _.omit({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) {
  1557. * return key.charAt(0) == '_';
  1558. * });
  1559. * // => { 'name': 'moe' }
  1560. */
  1561. function omit(object, callback, thisArg) {
  1562. var isFunc = typeof callback == 'function',
  1563. result = {};
  1564. if (isFunc) {
  1565. callback = createCallback(callback, thisArg);
  1566. } else {
  1567. var props = concat.apply(arrayRef, arguments);
  1568. }
  1569. forIn(object, function(value, key, object) {
  1570. if (isFunc
  1571. ? !callback(value, key, object)
  1572. : indexOf(props, key, 1) < 0
  1573. ) {
  1574. result[key] = value;
  1575. }
  1576. });
  1577. return result;
  1578. }
  1579. /**
  1580. * Creates a two dimensional array of the given object's key-value pairs,
  1581. * i.e. `[[key1, value1], [key2, value2]]`.
  1582. *
  1583. * @static
  1584. * @memberOf _
  1585. * @category Objects
  1586. * @param {Object} object The object to inspect.
  1587. * @returns {Array} Returns new array of key-value pairs.
  1588. * @example
  1589. *
  1590. * _.pairs({ 'moe': 30, 'larry': 40, 'curly': 50 });
  1591. * // => [['moe', 30], ['larry', 40], ['curly', 50]] (order is not guaranteed)
  1592. */
  1593. function pairs(object) {
  1594. var result = [];
  1595. forOwn(object, function(value, key) {
  1596. result.push([key, value]);
  1597. });
  1598. return result;
  1599. }
  1600. /**
  1601. * Creates a shallow clone of `object` composed of the specified properties.
  1602. * Property names may be specified as individual arguments or as arrays of
  1603. * property names. If `callback` is passed, it will be executed for each property
  1604. * in the `object`, picking the properties `callback` returns truthy for. The
  1605. * `callback` is bound to `thisArg` and invoked with three arguments; (value, key, object).
  1606. *
  1607. * @static
  1608. * @memberOf _
  1609. * @category Objects
  1610. * @param {Object} object The source object.
  1611. * @param {Function|String} callback|[prop1, prop2, ...] The properties to pick
  1612. * or the function called per iteration.
  1613. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1614. * @returns {Object} Returns an object composed of the picked properties.
  1615. * @example
  1616. *
  1617. * _.pick({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'name', 'age');
  1618. * // => { 'name': 'moe', 'age': 40 }
  1619. *
  1620. * _.pick({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) {
  1621. * return key.charAt(0) != '_';
  1622. * });
  1623. * // => { 'name': 'moe' }
  1624. */
  1625. function pick(object, callback, thisArg) {
  1626. var result = {};
  1627. if (typeof callback != 'function') {
  1628. var index = 0,
  1629. props = concat.apply(arrayRef, arguments),
  1630. length = props.length;
  1631. while (++index < length) {
  1632. var key = props[index];
  1633. if (key in object) {
  1634. result[key] = object[key];
  1635. }
  1636. }
  1637. } else {
  1638. callback = createCallback(callback, thisArg);
  1639. forIn(object, function(value, key, object) {
  1640. if (callback(value, key, object)) {
  1641. result[key] = value;
  1642. }
  1643. });
  1644. }
  1645. return result;
  1646. }
  1647. /**
  1648. * Creates an array composed of the own enumerable property values of `object`.
  1649. *
  1650. * @static
  1651. * @memberOf _
  1652. * @category Objects
  1653. * @param {Object} object The object to inspect.
  1654. * @returns {Array} Returns a new array of property values.
  1655. * @example
  1656. *
  1657. * _.values({ 'one': 1, 'two': 2, 'three': 3 });
  1658. * // => [1, 2, 3]
  1659. */
  1660. function values(object) {
  1661. var result = [];
  1662. forOwn(object, function(value) {
  1663. result.push(value);
  1664. });
  1665. return result;
  1666. }
  1667. /*--------------------------------------------------------------------------*/
  1668. /**
  1669. * Checks if a given `target` element is present in a `collection` using strict
  1670. * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
  1671. * as the offset from the end of the collection.
  1672. *
  1673. * @static
  1674. * @memberOf _
  1675. * @alias include
  1676. * @category Collections
  1677. * @param {Array|Object|String} collection The collection to iterate over.
  1678. * @param {Mixed} target The value to check for.
  1679. * @param {Number} [fromIndex=0] The index to search from.
  1680. * @returns {Boolean} Returns `true` if the `target` element is found, else `false`.
  1681. * @example
  1682. *
  1683. * _.contains([1, 2, 3], 1);
  1684. * // => true
  1685. *
  1686. * _.contains([1, 2, 3], 1, 2);
  1687. * // => false
  1688. *
  1689. * _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
  1690. * // => true
  1691. *
  1692. * _.contains('curly', 'ur');
  1693. * // => true
  1694. */
  1695. function contains(collection, target, fromIndex) {
  1696. var index = -1,
  1697. length = collection ? collection.length : 0;
  1698. fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
  1699. if (typeof length == 'number') {
  1700. return (isString(collection)
  1701. ? collection.indexOf(target, fromIndex)
  1702. : indexOf(collection, target, fromIndex)
  1703. ) > -1;
  1704. }
  1705. return some(collection, function(value) {
  1706. return ++index >= fromIndex && value === target;
  1707. });
  1708. }
  1709. /**
  1710. * Creates an object composed of keys returned from running each element of
  1711. * `collection` through a `callback`. The corresponding value of each key is
  1712. * the number of times the key was returned by `callback`. The `callback` is
  1713. * bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
  1714. * The `callback` argument may also be the name of a property to count by (e.g. 'length').
  1715. *
  1716. * @static
  1717. * @memberOf _
  1718. * @category Collections
  1719. * @param {Array|Object|String} collection The collection to iterate over.
  1720. * @param {Function|String} callback|property The function called per iteration
  1721. * or property name to count by.
  1722. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1723. * @returns {Object} Returns the composed aggregate object.
  1724. * @example
  1725. *
  1726. * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
  1727. * // => { '4': 1, '6': 2 }
  1728. *
  1729. * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  1730. * // => { '4': 1, '6': 2 }
  1731. *
  1732. * _.countBy(['one', 'two', 'three'], 'length');
  1733. * // => { '3': 2, '5': 1 }
  1734. */
  1735. function countBy(collection, callback, thisArg) {
  1736. var result = {};
  1737. callback = createCallback(callback, thisArg);
  1738. forEach(collection, function(value, key, collection) {
  1739. key = callback(value, key, collection);
  1740. (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
  1741. });
  1742. return result;
  1743. }
  1744. /**
  1745. * Checks if the `callback` returns a truthy value for **all** elements of a
  1746. * `collection`. The `callback` is bound to `thisArg` and invoked with three
  1747. * arguments; (value, index|key, collection).
  1748. *
  1749. * @static
  1750. * @memberOf _
  1751. * @alias all
  1752. * @category Collections
  1753. * @param {Array|Object|String} collection The collection to iterate over.
  1754. * @param {Function} [callback=identity] The function called per iteration.
  1755. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1756. * @returns {Boolean} Returns `true` if all elements pass the callback check,
  1757. * else `false`.
  1758. * @example
  1759. *
  1760. * _.every([true, 1, null, 'yes'], Boolean);
  1761. * // => false
  1762. */
  1763. function every(collection, callback, thisArg) {
  1764. var result = true;
  1765. callback = createCallback(callback, thisArg);
  1766. if (isArray(collection)) {
  1767. var index = -1,
  1768. length = collection.length;
  1769. while (++index < length) {
  1770. if (!(result = !!callback(collection[index], index, collection))) {
  1771. break;
  1772. }
  1773. }
  1774. } else {
  1775. forEach(collection, function(value, index, collection) {
  1776. return (result = !!callback(value, index, collection));
  1777. });
  1778. }
  1779. return result;
  1780. }
  1781. /**
  1782. * Examines each element in a `collection`, returning an array of all elements
  1783. * the `callback` returns truthy for. The `callback` is bound to `thisArg` and
  1784. * invoked with three arguments; (value, index|key, collection).
  1785. *
  1786. * @static
  1787. * @memberOf _
  1788. * @alias select
  1789. * @category Collections
  1790. * @param {Array|Object|String} collection The collection to iterate over.
  1791. * @param {Function} [callback=identity] The function called per iteration.
  1792. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1793. * @returns {Array} Returns a new array of elements that passed the callback check.
  1794. * @example
  1795. *
  1796. * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  1797. * // => [2, 4, 6]
  1798. */
  1799. function filter(collection, callback, thisArg) {
  1800. var result = [];
  1801. callback = createCallback(callback, thisArg);
  1802. forEach(collection, function(value, index, collection) {
  1803. if (callback(value, index, collection)) {
  1804. result.push(value);
  1805. }
  1806. });
  1807. return result;
  1808. }
  1809. /**
  1810. * Examines each element in a `collection`, returning the first one the `callback`
  1811. * returns truthy for. The function returns as soon as it finds an acceptable
  1812. * element, and does not iterate over the entire `collection`. The `callback` is
  1813. * bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
  1814. *
  1815. * @static
  1816. * @memberOf _
  1817. * @alias detect
  1818. * @category Collections
  1819. * @param {Array|Object|String} collection The collection to iterate over.
  1820. * @param {Function} callback The function called per iteration.
  1821. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1822. * @returns {Mixed} Returns the element that passed the callback check,
  1823. * else `undefined`.
  1824. * @example
  1825. *
  1826. * var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  1827. * // => 2
  1828. */
  1829. function find(collection, callback, thisArg) {
  1830. var result;
  1831. callback = createCallback(callback, thisArg);
  1832. forEach(collection, function(value, index, collection) {
  1833. if (callback(value, index, collection)) {
  1834. result = value;
  1835. return false;
  1836. }
  1837. });
  1838. return result;
  1839. }
  1840. /**
  1841. * Iterates over a `collection`, executing the `callback` for each element in
  1842. * the `collection`. The `callback` is bound to `thisArg` and invoked with three
  1843. * arguments; (value, index|key, collection). Callbacks may exit iteration early
  1844. * by explicitly returning `false`.
  1845. *
  1846. * @static
  1847. * @memberOf _
  1848. * @alias each
  1849. * @category Collections
  1850. * @param {Array|Object|String} collection The collection to iterate over.
  1851. * @param {Function} callback The function called per iteration.
  1852. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1853. * @returns {Array|Object|String} Returns `collection`.
  1854. * @example
  1855. *
  1856. * _([1, 2, 3]).forEach(alert).join(',');
  1857. * // => alerts each number and returns '1,2,3'
  1858. *
  1859. * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
  1860. * // => alerts each number (order is not guaranteed)
  1861. */
  1862. var forEach = createIterator(forEachIteratorOptions);
  1863. /**
  1864. * Creates an object composed of keys returned from running each element of
  1865. * `collection` through a `callback`. The corresponding value of each key is an
  1866. * array of elements passed to `callback` that returned the key. The `callback`
  1867. * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
  1868. * The `callback` argument may also be the name of a property to group by (e.g. 'length').
  1869. *
  1870. * @static
  1871. * @memberOf _
  1872. * @category Collections
  1873. * @param {Array|Object|String} collection The collection to iterate over.
  1874. * @param {Function|String} callback|property The function called per iteration
  1875. * or property name to group by.
  1876. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1877. * @returns {Object} Returns the composed aggregate object.
  1878. * @example
  1879. *
  1880. * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
  1881. * // => { '4': [4.2], '6': [6.1, 6.4] }
  1882. *
  1883. * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  1884. * // => { '4': [4.2], '6': [6.1, 6.4] }
  1885. *
  1886. * _.groupBy(['one', 'two', 'three'], 'length');
  1887. * // => { '3': ['one', 'two'], '5': ['three'] }
  1888. */
  1889. function groupBy(collection, callback, thisArg) {
  1890. var result = {};
  1891. callback = createCallback(callback, thisArg);
  1892. forEach(collection, function(value, key, collection) {
  1893. key = callback(value, key, collection);
  1894. (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
  1895. });
  1896. return result;
  1897. }
  1898. /**
  1899. * Invokes the method named by `methodName` on each element in the `collection`,
  1900. * returning an array of the results of each invoked method. Additional arguments
  1901. * will be passed to each invoked method. If `methodName` is a function it will
  1902. * be invoked for, and `this` bound to, each element in the `collection`.
  1903. *
  1904. * @static
  1905. * @memberOf _
  1906. * @category Collections
  1907. * @param {Array|Object|String} collection The collection to iterate over.
  1908. * @param {Function|String} methodName The name of the method to invoke or
  1909. * the function invoked per iteration.
  1910. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
  1911. * @returns {Array} Returns a new array of the results of each invoked method.
  1912. * @example
  1913. *
  1914. * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  1915. * // => [[1, 5, 7], [1, 2, 3]]
  1916. *
  1917. * _.invoke([123, 456], String.prototype.split, '');
  1918. * // => [['1', '2', '3'], ['4', '5', '6']]
  1919. */
  1920. function invoke(collection, methodName) {
  1921. var args = slice.call(arguments, 2),
  1922. isFunc = typeof methodName == 'function',
  1923. result = [];
  1924. forEach(collection, function(value) {
  1925. result.push((isFunc ? methodName : value[methodName]).apply(value, args));
  1926. });
  1927. return result;
  1928. }
  1929. /**
  1930. * Creates an array of values by running each element in the `collection`
  1931. * through a `callback`. The `callback` is bound to `thisArg` and invoked with
  1932. * three arguments; (value, index|key, collection).
  1933. *
  1934. * @static
  1935. * @memberOf _
  1936. * @alias collect
  1937. * @category Collections
  1938. * @param {Array|Object|String} collection The collection to iterate over.
  1939. * @param {Function} [callback=identity] The function called per iteration.
  1940. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1941. * @returns {Array} Returns a new array of the results of each `callback` execution.
  1942. * @example
  1943. *
  1944. * _.map([1, 2, 3], function(num) { return num * 3; });
  1945. * // => [3, 6, 9]
  1946. *
  1947. * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
  1948. * // => [3, 6, 9] (order is not guaranteed)
  1949. */
  1950. function map(collection, callback, thisArg) {
  1951. var index = -1,
  1952. length = collection ? collection.length : 0,
  1953. result = Array(typeof length == 'number' ? length : 0);
  1954. callback = createCallback(callback, thisArg);
  1955. if (isArray(collection)) {
  1956. while (++index < length) {
  1957. result[index] = callback(collection[index], index, collection);
  1958. }
  1959. } else {
  1960. forEach(collection, function(value, key, collection) {
  1961. result[++index] = callback(value, key, collection);
  1962. });
  1963. }
  1964. return result;
  1965. }
  1966. /**
  1967. * Retrieves the maximum value of an `array`. If `callback` is passed,
  1968. * it will be executed for each value in the `array` to generate the
  1969. * criterion by which the value is ranked. The `callback` is bound to
  1970. * `thisArg` and invoked with three arguments; (value, index, collection).
  1971. *
  1972. * @static
  1973. * @memberOf _
  1974. * @category Collections
  1975. * @param {Array|Object|String} collection The collection to iterate over.
  1976. * @param {Function} [callback] The function called per iteration.
  1977. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  1978. * @returns {Mixed} Returns the maximum value.
  1979. * @example
  1980. *
  1981. * var stooges = [
  1982. * { 'name': 'moe', 'age': 40 },
  1983. * { 'name': 'larry', 'age': 50 },
  1984. * { 'name': 'curly', 'age': 60 }
  1985. * ];
  1986. *
  1987. * _.max(stooges, function(stooge) { return stooge.age; });
  1988. * // => { 'name': 'curly', 'age': 60 };
  1989. */
  1990. function max(collection, callback, thisArg) {
  1991. var computed = -Infinity,
  1992. index = -1,
  1993. length = collection ? collection.length : 0,
  1994. result = computed;
  1995. if (callback || !isArray(collection)) {
  1996. callback = !callback && isString(collection)
  1997. ? charAtCallback
  1998. : createCallback(callback, thisArg);
  1999. forEach(collection, function(value, index, collection) {
  2000. var current = callback(value, index, collection);
  2001. if (current > computed) {
  2002. computed = current;
  2003. result = value;
  2004. }
  2005. });
  2006. } else {
  2007. while (++index < length) {
  2008. if (collection[index] > result) {
  2009. result = collection[index];
  2010. }
  2011. }
  2012. }
  2013. return result;
  2014. }
  2015. /**
  2016. * Retrieves the minimum value of an `array`. If `callback` is passed,
  2017. * it will be executed for each value in the `array` to generate the
  2018. * criterion by which the value is ranked. The `callback` is bound to `thisArg`
  2019. * and invoked with three arguments; (value, index, collection).
  2020. *
  2021. * @static
  2022. * @memberOf _
  2023. * @category Collections
  2024. * @param {Array|Object|String} collection The collection to iterate over.
  2025. * @param {Function} [callback] The function called per iteration.
  2026. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  2027. * @returns {Mixed} Returns the minimum value.
  2028. * @example
  2029. *
  2030. * _.min([10, 5, 100, 2, 1000]);
  2031. * // => 2
  2032. */
  2033. function min(collection, callback, thisArg) {
  2034. var computed = Infinity,
  2035. index = -1,
  2036. length = collection ? collection.length : 0,
  2037. result = computed;
  2038. if (callback || !isArray(collection)) {
  2039. callback = !callback && isString(collection)
  2040. ? charAtCallback
  2041. : createCallback(callback, thisArg);
  2042. forEach(collection, function(value, index, collection) {
  2043. var current = callback(value, index, collection);
  2044. if (current < computed) {
  2045. computed = current;
  2046. result = value;
  2047. }
  2048. });
  2049. } else {
  2050. while (++index < length) {
  2051. if (collection[index] < result) {
  2052. result = collection[index];
  2053. }
  2054. }
  2055. }
  2056. return result;
  2057. }
  2058. /**
  2059. * Retrieves the value of a specified property from all elements in
  2060. * the `collection`.
  2061. *
  2062. * @static
  2063. * @memberOf _
  2064. * @category Collections
  2065. * @param {Array|Object|String} collection The collection to iterate over.
  2066. * @param {String} property The property to pluck.
  2067. * @returns {Array} Returns a new array of property values.
  2068. * @example
  2069. *
  2070. * var stooges = [
  2071. * { 'name': 'moe', 'age': 40 },
  2072. * { 'name': 'larry', 'age': 50 },
  2073. * { 'name': 'curly', 'age': 60 }
  2074. * ];
  2075. *
  2076. * _.pluck(stooges, 'name');
  2077. * // => ['moe', 'larry', 'curly']
  2078. */
  2079. function pluck(collection, property) {
  2080. var result = [];
  2081. forEach(collection, function(value) {
  2082. result.push(value[property]);
  2083. });
  2084. return result;
  2085. }
  2086. /**
  2087. * Boils down a `collection` to a single value. The initial state of the
  2088. * reduction is `accumulator` and each successive step of it should be returned
  2089. * by the `callback`. The `callback` is bound to `thisArg` and invoked with 4
  2090. * arguments; for arrays they are (accumulator, value, index|key, collection).
  2091. *
  2092. * @static
  2093. * @memberOf _
  2094. * @alias foldl, inject
  2095. * @category Collections
  2096. * @param {Array|Object|String} collection The collection to iterate over.
  2097. * @param {Function} callback The function called per iteration.
  2098. * @param {Mixed} [accumulator] Initial value of the accumulator.
  2099. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  2100. * @returns {Mixed} Returns the accumulated value.
  2101. * @example
  2102. *
  2103. * var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; });
  2104. * // => 6
  2105. */
  2106. function reduce(collection, callback, accumulator, thisArg) {
  2107. var noaccum = arguments.length < 3;
  2108. callback = createCallback(callback, thisArg);
  2109. forEach(collection, function(value, index, collection) {
  2110. accumulator = noaccum
  2111. ? (noaccum = false, value)
  2112. : callback(accumulator, value, index, collection)
  2113. });
  2114. return accumulator;
  2115. }
  2116. /**
  2117. * The right-associative version of `_.reduce`.
  2118. *
  2119. * @static
  2120. * @memberOf _
  2121. * @alias foldr
  2122. * @category Collections
  2123. * @param {Array|Object|String} collection The collection to iterate over.
  2124. * @param {Function} callback The function called per iteration.
  2125. * @param {Mixed} [accumulator] Initial value of the accumulator.
  2126. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  2127. * @returns {Mixed} Returns the accumulated value.
  2128. * @example
  2129. *
  2130. * var list = [[0, 1], [2, 3], [4, 5]];
  2131. * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  2132. * // => [4, 5, 2, 3, 0, 1]
  2133. */
  2134. function reduceRight(collection, callback, accumulator, thisArg) {
  2135. var iteratee = collection,
  2136. length = collection ? collection.length : 0,
  2137. noaccum = arguments.length < 3;
  2138. if (typeof length != 'number') {
  2139. var props = keys(collection);
  2140. length = props.length;
  2141. } else if (noCharByIndex && isString(collection)) {
  2142. iteratee = collection.split('');
  2143. }
  2144. forEach(collection, function(value, index, collection) {
  2145. index = props ? props[--length] : --length;
  2146. accumulator = noaccum
  2147. ? (noaccum = false, iteratee[index])
  2148. : callback.call(thisArg, accumulator, iteratee[index], index, collection);
  2149. });
  2150. return accumulator;
  2151. }
  2152. /**
  2153. * The opposite of `_.filter`, this method returns the values of a
  2154. * `collection` that `callback` does **not** return truthy for.
  2155. *
  2156. * @static
  2157. * @memberOf _
  2158. * @category Collections
  2159. * @param {Array|Object|String} collection The collection to iterate over.
  2160. * @param {Function} [callback=identity] The function called per iteration.
  2161. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  2162. * @returns {Array} Returns a new array of elements that did **not** pass the
  2163. * callback check.
  2164. * @example
  2165. *
  2166. * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  2167. * // => [1, 3, 5]
  2168. */
  2169. function reject(collection, callback, thisArg) {
  2170. callback = createCallback(callback, thisArg);
  2171. return filter(collection, function(value, index, collection) {
  2172. return !callback(value, index, collection);
  2173. });
  2174. }
  2175. /**
  2176. * Creates an array of shuffled `array` values, using a version of the
  2177. * Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
  2178. *
  2179. * @static
  2180. * @memberOf _
  2181. * @category Collections
  2182. * @param {Array|Object|String} collection The collection to shuffle.
  2183. * @returns {Array} Returns a new shuffled collection.
  2184. * @example
  2185. *
  2186. * _.shuffle([1, 2, 3, 4, 5, 6]);
  2187. * // => [4, 1, 6, 3, 5, 2]
  2188. */
  2189. function shuffle(collection) {
  2190. var index = -1,
  2191. result = Array(collection ? collection.length : 0);
  2192. forEach(collection, function(value) {
  2193. var rand = floor(nativeRandom() * (++index + 1));
  2194. result[index] = result[rand];
  2195. result[rand] = value;
  2196. });
  2197. return result;
  2198. }
  2199. /**
  2200. * Gets the size of the `collection` by returning `collection.length` for arrays
  2201. * and array-like objects or the number of own enumerable properties for objects.
  2202. *
  2203. * @static
  2204. * @memberOf _
  2205. * @category Collections
  2206. * @param {Array|Object|String} collection The collection to inspect.
  2207. * @returns {Number} Returns `collection.length` or number of own enumerable properties.
  2208. * @example
  2209. *
  2210. * _.size([1, 2]);
  2211. * // => 2
  2212. *
  2213. * _.size({ 'one': 1, 'two': 2, 'three': 3 });
  2214. * // => 3
  2215. *
  2216. * _.size('curly');
  2217. * // => 5
  2218. */
  2219. function size(collection) {
  2220. var length = collection ? collection.length : 0;
  2221. return typeof length == 'number' ? length : keys(collection).length;
  2222. }
  2223. /**
  2224. * Checks if the `callback` returns a truthy value for **any** element of a
  2225. * `collection`. The function returns as soon as it finds passing value, and
  2226. * does not iterate over the entire `collection`. The `callback` is bound to
  2227. * `thisArg` and invoked with three arguments; (value, index|key, collection).
  2228. *
  2229. * @static
  2230. * @memberOf _
  2231. * @alias any
  2232. * @category Collections
  2233. * @param {Array|Object|String} collection The collection to iterate over.
  2234. * @param {Function} [callback=identity] The function called per iteration.
  2235. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  2236. * @returns {Boolean} Returns `true` if any element passes the callback check,
  2237. * else `false`.
  2238. * @example
  2239. *
  2240. * _.some([null, 0, 'yes', false]);
  2241. * // => true
  2242. */
  2243. function some(collection, callback, thisArg) {
  2244. var result;
  2245. callback = createCallback(callback, thisArg);
  2246. if (isArray(collection)) {
  2247. var index = -1,
  2248. length = collection.length;
  2249. while (++index < length) {
  2250. if (result = callback(collection[index], index, collection)) {
  2251. break;
  2252. }
  2253. }
  2254. } else {
  2255. forEach(collection, function(value, index, collection) {
  2256. return !(result = callback(value, index, collection));
  2257. });
  2258. }
  2259. return !!result;
  2260. }
  2261. /**
  2262. * Creates an array, stable sorted in ascending order by the results of
  2263. * running each element of `collection` through a `callback`. The `callback`
  2264. * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
  2265. * The `callback` argument may also be the name of a property to sort by (e.g. 'length').
  2266. *
  2267. * @static
  2268. * @memberOf _
  2269. * @category Collections
  2270. * @param {Array|Object|String} collection The collection to iterate over.
  2271. * @param {Function|String} callback|property The function called per iteration
  2272. * or property name to sort by.
  2273. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  2274. * @returns {Array} Returns a new array of sorted elements.
  2275. * @example
  2276. *
  2277. * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
  2278. * // => [3, 1, 2]
  2279. *
  2280. * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
  2281. * // => [3, 1, 2]
  2282. *
  2283. * _.sortBy(['larry', 'brendan', 'moe'], 'length');
  2284. * // => ['moe', 'larry', 'brendan']
  2285. */
  2286. function sortBy(collection, callback, thisArg) {
  2287. var result = [];
  2288. callback = createCallback(callback, thisArg);
  2289. forEach(collection, function(value, index, collection) {
  2290. result.push({
  2291. 'criteria': callback(value, index, collection),
  2292. 'index': index,
  2293. 'value': value
  2294. });
  2295. });
  2296. var length = result.length;
  2297. result.sort(compareAscending);
  2298. while (length--) {
  2299. result[length] = result[length].value;
  2300. }
  2301. return result;
  2302. }
  2303. /**
  2304. * Converts the `collection`, to an array.
  2305. *
  2306. * @static
  2307. * @memberOf _
  2308. * @category Collections
  2309. * @param {Array|Object|String} collection The collection to convert.
  2310. * @returns {Array} Returns the new converted array.
  2311. * @example
  2312. *
  2313. * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
  2314. * // => [2, 3, 4]
  2315. */
  2316. function toArray(collection) {
  2317. if (collection && typeof collection.length == 'number') {
  2318. return (noArraySliceOnStrings ? isString(collection) : typeof collection == 'string')
  2319. ? collection.split('')
  2320. : slice.call(collection);
  2321. }
  2322. return values(collection);
  2323. }
  2324. /**
  2325. * Examines each element in a `collection`, returning an array of all elements
  2326. * that contain the given `properties`.
  2327. *
  2328. * @static
  2329. * @memberOf _
  2330. * @category Collections
  2331. * @param {Array|Object|String} collection The collection to iterate over.
  2332. * @param {Object} properties The object of property values to filter by.
  2333. * @returns {Array} Returns a new array of elements that contain the given `properties`.
  2334. * @example
  2335. *
  2336. * var stooges = [
  2337. * { 'name': 'moe', 'age': 40 },
  2338. * { 'name': 'larry', 'age': 50 },
  2339. * { 'name': 'curly', 'age': 60 }
  2340. * ];
  2341. *
  2342. * _.where(stooges, { 'age': 40 });
  2343. * // => [{ 'name': 'moe', 'age': 40 }]
  2344. */
  2345. function where(collection, properties) {
  2346. var props = [];
  2347. forIn(properties, function(value, prop) {
  2348. props.push(prop);
  2349. });
  2350. return filter(collection, function(object) {
  2351. var length = props.length;
  2352. while (length--) {
  2353. var result = object[props[length]] === properties[props[length]];
  2354. if (!result) {
  2355. break;
  2356. }
  2357. }
  2358. return !!result;
  2359. });
  2360. }
  2361. /*--------------------------------------------------------------------------*/
  2362. /**
  2363. * Creates an array with all falsey values of `array` removed. The values
  2364. * `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey.
  2365. *
  2366. * @static
  2367. * @memberOf _
  2368. * @category Arrays
  2369. * @param {Array} array The array to compact.
  2370. * @returns {Array} Returns a new filtered array.
  2371. * @example
  2372. *
  2373. * _.compact([0, 1, false, 2, '', 3]);
  2374. * // => [1, 2, 3]
  2375. */
  2376. function compact(array) {
  2377. var index = -1,
  2378. length = array ? array.length : 0,
  2379. result = [];
  2380. while (++index < length) {
  2381. var value = array[index];
  2382. if (value) {
  2383. result.push(value);
  2384. }
  2385. }
  2386. return result;
  2387. }
  2388. /**
  2389. * Creates an array of `array` elements not present in the other arrays
  2390. * using strict equality for comparisons, i.e. `===`.
  2391. *
  2392. * @static
  2393. * @memberOf _
  2394. * @category Arrays
  2395. * @param {Array} array The array to process.
  2396. * @param {Array} [array1, array2, ...] Arrays to check.
  2397. * @returns {Array} Returns a new array of `array` elements not present in the
  2398. * other arrays.
  2399. * @example
  2400. *
  2401. * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
  2402. * // => [1, 3, 4]
  2403. */
  2404. function difference(array) {
  2405. var index = -1,
  2406. length = array ? array.length : 0,
  2407. flattened = concat.apply(arrayRef, arguments),
  2408. contains = cachedContains(flattened, length),
  2409. result = [];
  2410. while (++index < length) {
  2411. var value = array[index];
  2412. if (!contains(value)) {
  2413. result.push(value);
  2414. }
  2415. }
  2416. return result;
  2417. }
  2418. /**
  2419. * Gets the first element of the `array`. Pass `n` to return the first `n`
  2420. * elements of the `array`.
  2421. *
  2422. * @static
  2423. * @memberOf _
  2424. * @alias head, take
  2425. * @category Arrays
  2426. * @param {Array} array The array to query.
  2427. * @param {Number} [n] The number of elements to return.
  2428. * @param- {Object} [guard] Internally used to allow this method to work with
  2429. * others like `_.map` without using their callback `index` argument for `n`.
  2430. * @returns {Mixed} Returns the first element or an array of the first `n`
  2431. * elements of `array`.
  2432. * @example
  2433. *
  2434. * _.first([5, 4, 3, 2, 1]);
  2435. * // => 5
  2436. */
  2437. function first(array, n, guard) {
  2438. if (array) {
  2439. return (n == null || guard) ? array[0] : slice.call(array, 0, n);
  2440. }
  2441. }
  2442. /**
  2443. * Flattens a nested array (the nesting can be to any depth). If `shallow` is
  2444. * truthy, `array` will only be flattened a single level.
  2445. *
  2446. * @static
  2447. * @memberOf _
  2448. * @category Arrays
  2449. * @param {Array} array The array to compact.
  2450. * @param {Boolean} shallow A flag to indicate only flattening a single level.
  2451. * @returns {Array} Returns a new flattened array.
  2452. * @example
  2453. *
  2454. * _.flatten([1, [2], [3, [[4]]]]);
  2455. * // => [1, 2, 3, 4];
  2456. *
  2457. * _.flatten([1, [2], [3, [[4]]]], true);
  2458. * // => [1, 2, 3, [[4]]];
  2459. */
  2460. function flatten(array, shallow) {
  2461. var index = -1,
  2462. length = array ? array.length : 0,
  2463. result = [];
  2464. while (++index < length) {
  2465. var value = array[index];
  2466. // recursively flatten arrays (susceptible to call stack limits)
  2467. if (isArray(value)) {
  2468. push.apply(result, shallow ? value : flatten(value));
  2469. } else {
  2470. result.push(value);
  2471. }
  2472. }
  2473. return result;
  2474. }
  2475. /**
  2476. * Gets the index at which the first occurrence of `value` is found using
  2477. * strict equality for comparisons, i.e. `===`. If the `array` is already
  2478. * sorted, passing `true` for `fromIndex` will run a faster binary search.
  2479. *
  2480. * @static
  2481. * @memberOf _
  2482. * @category Arrays
  2483. * @param {Array} array The array to search.
  2484. * @param {Mixed} value The value to search for.
  2485. * @param {Boolean|Number} [fromIndex=0] The index to search from or `true` to
  2486. * perform a binary search on a sorted `array`.
  2487. * @returns {Number} Returns the index of the matched value or `-1`.
  2488. * @example
  2489. *
  2490. * _.indexOf([1, 2, 3, 1, 2, 3], 2);
  2491. * // => 1
  2492. *
  2493. * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
  2494. * // => 4
  2495. *
  2496. * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
  2497. * // => 2
  2498. */
  2499. function indexOf(array, value, fromIndex) {
  2500. var index = -1,
  2501. length = array ? array.length : 0;
  2502. if (typeof fromIndex == 'number') {
  2503. index = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0) - 1;
  2504. } else if (fromIndex) {
  2505. index = sortedIndex(array, value);
  2506. return array[index] === value ? index : -1;
  2507. }
  2508. while (++index < length) {
  2509. if (array[index] === value) {
  2510. return index;
  2511. }
  2512. }
  2513. return -1;
  2514. }
  2515. /**
  2516. * Gets all but the last element of `array`. Pass `n` to exclude the last `n`
  2517. * elements from the result.
  2518. *
  2519. * @static
  2520. * @memberOf _
  2521. * @category Arrays
  2522. * @param {Array} array The array to query.
  2523. * @param {Number} [n=1] The number of elements to exclude.
  2524. * @param- {Object} [guard] Internally used to allow this method to work with
  2525. * others like `_.map` without using their callback `index` argument for `n`.
  2526. * @returns {Array} Returns all but the last element or `n` elements of `array`.
  2527. * @example
  2528. *
  2529. * _.initial([3, 2, 1]);
  2530. * // => [3, 2]
  2531. */
  2532. function initial(array, n, guard) {
  2533. return array
  2534. ? slice.call(array, 0, -((n == null || guard) ? 1 : n))
  2535. : [];
  2536. }
  2537. /**
  2538. * Computes the intersection of all the passed-in arrays using strict equality
  2539. * for comparisons, i.e. `===`.
  2540. *
  2541. * @static
  2542. * @memberOf _
  2543. * @category Arrays
  2544. * @param {Array} [array1, array2, ...] Arrays to process.
  2545. * @returns {Array} Returns a new array of unique elements, in order, that are
  2546. * present in **all** of the arrays.
  2547. * @example
  2548. *
  2549. * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  2550. * // => [1, 2]
  2551. */
  2552. function intersection(array) {
  2553. var args = arguments,
  2554. argsLength = args.length,
  2555. cache = {},
  2556. result = [];
  2557. forEach(array, function(value) {
  2558. if (indexOf(result, value) < 0) {
  2559. var length = argsLength;
  2560. while (--length) {
  2561. if (!(cache[length] || (cache[length] = cachedContains(args[length])))(value)) {
  2562. return;
  2563. }
  2564. }
  2565. result.push(value);
  2566. }
  2567. });
  2568. return result;
  2569. }
  2570. /**
  2571. * Gets the last element of the `array`. Pass `n` to return the last `n`
  2572. * elements of the `array`.
  2573. *
  2574. * @static
  2575. * @memberOf _
  2576. * @category Arrays
  2577. * @param {Array} array The array to query.
  2578. * @param {Number} [n] The number of elements to return.
  2579. * @param- {Object} [guard] Internally used to allow this method to work with
  2580. * others like `_.map` without using their callback `index` argument for `n`.
  2581. * @returns {Mixed} Returns the last element or an array of the last `n`
  2582. * elements of `array`.
  2583. * @example
  2584. *
  2585. * _.last([3, 2, 1]);
  2586. * // => 1
  2587. */
  2588. function last(array, n, guard) {
  2589. if (array) {
  2590. var length = array.length;
  2591. return (n == null || guard) ? array[length - 1] : slice.call(array, -n || length);
  2592. }
  2593. }
  2594. /**
  2595. * Gets the index at which the last occurrence of `value` is found using strict
  2596. * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
  2597. * as the offset from the end of the collection.
  2598. *
  2599. * @static
  2600. * @memberOf _
  2601. * @category Arrays
  2602. * @param {Array} array The array to search.
  2603. * @param {Mixed} value The value to search for.
  2604. * @param {Number} [fromIndex=array.length-1] The index to search from.
  2605. * @returns {Number} Returns the index of the matched value or `-1`.
  2606. * @example
  2607. *
  2608. * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
  2609. * // => 4
  2610. *
  2611. * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
  2612. * // => 1
  2613. */
  2614. function lastIndexOf(array, value, fromIndex) {
  2615. var index = array ? array.length : 0;
  2616. if (typeof fromIndex == 'number') {
  2617. index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
  2618. }
  2619. while (index--) {
  2620. if (array[index] === value) {
  2621. return index;
  2622. }
  2623. }
  2624. return -1;
  2625. }
  2626. /**
  2627. * Creates an object composed from arrays of `keys` and `values`. Pass either
  2628. * a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or
  2629. * two arrays, one of `keys` and one of corresponding `values`.
  2630. *
  2631. * @static
  2632. * @memberOf _
  2633. * @category Arrays
  2634. * @param {Array} keys The array of keys.
  2635. * @param {Array} [values=[]] The array of values.
  2636. * @returns {Object} Returns an object composed of the given keys and
  2637. * corresponding values.
  2638. * @example
  2639. *
  2640. * _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
  2641. * // => { 'moe': 30, 'larry': 40, 'curly': 50 }
  2642. */
  2643. function object(keys, values) {
  2644. var index = -1,
  2645. length = keys ? keys.length : 0,
  2646. result = {};
  2647. while (++index < length) {
  2648. var key = keys[index];
  2649. if (values) {
  2650. result[key] = values[index];
  2651. } else {
  2652. result[key[0]] = key[1];
  2653. }
  2654. }
  2655. return result;
  2656. }
  2657. /**
  2658. * Creates an array of numbers (positive and/or negative) progressing from
  2659. * `start` up to but not including `stop`. This method is a port of Python's
  2660. * `range()` function. See http://docs.python.org/library/functions.html#range.
  2661. *
  2662. * @static
  2663. * @memberOf _
  2664. * @category Arrays
  2665. * @param {Number} [start=0] The start of the range.
  2666. * @param {Number} end The end of the range.
  2667. * @param {Number} [step=1] The value to increment or descrement by.
  2668. * @returns {Array} Returns a new range array.
  2669. * @example
  2670. *
  2671. * _.range(10);
  2672. * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  2673. *
  2674. * _.range(1, 11);
  2675. * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2676. *
  2677. * _.range(0, 30, 5);
  2678. * // => [0, 5, 10, 15, 20, 25]
  2679. *
  2680. * _.range(0, -10, -1);
  2681. * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  2682. *
  2683. * _.range(0);
  2684. * // => []
  2685. */
  2686. function range(start, end, step) {
  2687. start = +start || 0;
  2688. step = +step || 1;
  2689. if (end == null) {
  2690. end = start;
  2691. start = 0;
  2692. }
  2693. // use `Array(length)` so V8 will avoid the slower "dictionary" mode
  2694. // http://www.youtube.com/watch?v=XAqIpGU8ZZk#t=16m27s
  2695. var index = -1,
  2696. length = nativeMax(0, ceil((end - start) / step)),
  2697. result = Array(length);
  2698. while (++index < length) {
  2699. result[index] = start;
  2700. start += step;
  2701. }
  2702. return result;
  2703. }
  2704. /**
  2705. * The opposite of `_.initial`, this method gets all but the first value of
  2706. * `array`. Pass `n` to exclude the first `n` values from the result.
  2707. *
  2708. * @static
  2709. * @memberOf _
  2710. * @alias drop, tail
  2711. * @category Arrays
  2712. * @param {Array} array The array to query.
  2713. * @param {Number} [n=1] The number of elements to exclude.
  2714. * @param- {Object} [guard] Internally used to allow this method to work with
  2715. * others like `_.map` without using their callback `index` argument for `n`.
  2716. * @returns {Array} Returns all but the first value or `n` values of `array`.
  2717. * @example
  2718. *
  2719. * _.rest([3, 2, 1]);
  2720. * // => [2, 1]
  2721. */
  2722. function rest(array, n, guard) {
  2723. return array
  2724. ? slice.call(array, (n == null || guard) ? 1 : n)
  2725. : [];
  2726. }
  2727. /**
  2728. * Uses a binary search to determine the smallest index at which the `value`
  2729. * should be inserted into `array` in order to maintain the sort order of the
  2730. * sorted `array`. If `callback` is passed, it will be executed for `value` and
  2731. * each element in `array` to compute their sort ranking. The `callback` is
  2732. * bound to `thisArg` and invoked with one argument; (value). The `callback`
  2733. * argument may also be the name of a property to order by.
  2734. *
  2735. * @static
  2736. * @memberOf _
  2737. * @category Arrays
  2738. * @param {Array} array The array to iterate over.
  2739. * @param {Mixed} value The value to evaluate.
  2740. * @param {Function|String} [callback=identity|property] The function called
  2741. * per iteration or property name to order by.
  2742. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  2743. * @returns {Number} Returns the index at which the value should be inserted
  2744. * into `array`.
  2745. * @example
  2746. *
  2747. * _.sortedIndex([20, 30, 50], 40);
  2748. * // => 2
  2749. *
  2750. * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
  2751. * // => 2
  2752. *
  2753. * var dict = {
  2754. * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
  2755. * };
  2756. *
  2757. * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
  2758. * return dict.wordToNumber[word];
  2759. * });
  2760. * // => 2
  2761. *
  2762. * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
  2763. * return this.wordToNumber[word];
  2764. * }, dict);
  2765. * // => 2
  2766. */
  2767. function sortedIndex(array, value, callback, thisArg) {
  2768. var low = 0,
  2769. high = array ? array.length : low;
  2770. // explicitly reference `identity` for better engine inlining
  2771. callback = callback ? createCallback(callback, thisArg) : identity;
  2772. value = callback(value);
  2773. while (low < high) {
  2774. var mid = (low + high) >>> 1;
  2775. callback(array[mid]) < value
  2776. ? low = mid + 1
  2777. : high = mid;
  2778. }
  2779. return low;
  2780. }
  2781. /**
  2782. * Computes the union of the passed-in arrays using strict equality for
  2783. * comparisons, i.e. `===`.
  2784. *
  2785. * @static
  2786. * @memberOf _
  2787. * @category Arrays
  2788. * @param {Array} [array1, array2, ...] Arrays to process.
  2789. * @returns {Array} Returns a new array of unique values, in order, that are
  2790. * present in one or more of the arrays.
  2791. * @example
  2792. *
  2793. * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  2794. * // => [1, 2, 3, 101, 10]
  2795. */
  2796. function union() {
  2797. return uniq(concat.apply(arrayRef, arguments));
  2798. }
  2799. /**
  2800. * Creates a duplicate-value-free version of the `array` using strict equality
  2801. * for comparisons, i.e. `===`. If the `array` is already sorted, passing `true`
  2802. * for `isSorted` will run a faster algorithm. If `callback` is passed, each
  2803. * element of `array` is passed through a callback` before uniqueness is computed.
  2804. * The `callback` is bound to `thisArg` and invoked with three arguments; (value, index, array).
  2805. *
  2806. * @static
  2807. * @memberOf _
  2808. * @alias unique
  2809. * @category Arrays
  2810. * @param {Array} array The array to process.
  2811. * @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted.
  2812. * @param {Function} [callback=identity] The function called per iteration.
  2813. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  2814. * @returns {Array} Returns a duplicate-value-free array.
  2815. * @example
  2816. *
  2817. * _.uniq([1, 2, 1, 3, 1]);
  2818. * // => [1, 2, 3]
  2819. *
  2820. * _.uniq([1, 1, 2, 2, 3], true);
  2821. * // => [1, 2, 3]
  2822. *
  2823. * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); });
  2824. * // => [1, 2, 3]
  2825. *
  2826. * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math);
  2827. * // => [1, 2, 3]
  2828. */
  2829. function uniq(array, isSorted, callback, thisArg) {
  2830. var index = -1,
  2831. length = array ? array.length : 0,
  2832. result = [],
  2833. seen = result;
  2834. // juggle arguments
  2835. if (typeof isSorted == 'function') {
  2836. thisArg = callback;
  2837. callback = isSorted;
  2838. isSorted = false;
  2839. }
  2840. // init value cache for large arrays
  2841. var isLarge = !isSorted && length > 74;
  2842. if (isLarge) {
  2843. var cache = {};
  2844. }
  2845. if (callback) {
  2846. seen = [];
  2847. callback = createCallback(callback, thisArg);
  2848. }
  2849. while (++index < length) {
  2850. var value = array[index],
  2851. computed = callback ? callback(value, index, array) : value;
  2852. if (isLarge) {
  2853. // manually coerce `computed` to a string because `hasOwnProperty`, in
  2854. // some older versions of Firefox, coerces objects incorrectly
  2855. seen = hasOwnProperty.call(cache, computed + '') ? cache[computed] : (cache[computed] = []);
  2856. }
  2857. if (isSorted
  2858. ? !index || seen[seen.length - 1] !== computed
  2859. : indexOf(seen, computed) < 0
  2860. ) {
  2861. if (callback || isLarge) {
  2862. seen.push(computed);
  2863. }
  2864. result.push(value);
  2865. }
  2866. }
  2867. return result;
  2868. }
  2869. /**
  2870. * Creates an array with all occurrences of the passed values removed using
  2871. * strict equality for comparisons, i.e. `===`.
  2872. *
  2873. * @static
  2874. * @memberOf _
  2875. * @category Arrays
  2876. * @param {Array} array The array to filter.
  2877. * @param {Mixed} [value1, value2, ...] Values to remove.
  2878. * @returns {Array} Returns a new filtered array.
  2879. * @example
  2880. *
  2881. * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
  2882. * // => [2, 3, 4]
  2883. */
  2884. function without(array) {
  2885. var index = -1,
  2886. length = array ? array.length : 0,
  2887. contains = cachedContains(arguments, 1, 20),
  2888. result = [];
  2889. while (++index < length) {
  2890. var value = array[index];
  2891. if (!contains(value)) {
  2892. result.push(value);
  2893. }
  2894. }
  2895. return result;
  2896. }
  2897. /**
  2898. * Groups the elements of each array at their corresponding indexes. Useful for
  2899. * separate data sources that are coordinated through matching array indexes.
  2900. * For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix
  2901. * in a similar fashion.
  2902. *
  2903. * @static
  2904. * @memberOf _
  2905. * @category Arrays
  2906. * @param {Array} [array1, array2, ...] Arrays to process.
  2907. * @returns {Array} Returns a new array of grouped elements.
  2908. * @example
  2909. *
  2910. * _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
  2911. * // => [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]]
  2912. */
  2913. function zip(array) {
  2914. var index = -1,
  2915. length = array ? max(pluck(arguments, 'length')) : 0,
  2916. result = Array(length);
  2917. while (++index < length) {
  2918. result[index] = pluck(arguments, index);
  2919. }
  2920. return result;
  2921. }
  2922. /*--------------------------------------------------------------------------*/
  2923. /**
  2924. * Creates a function that is restricted to executing `func` only after it is
  2925. * called `n` times. The `func` is executed with the `this` binding of the
  2926. * created function.
  2927. *
  2928. * @static
  2929. * @memberOf _
  2930. * @category Functions
  2931. * @param {Number} n The number of times the function must be called before
  2932. * it is executed.
  2933. * @param {Function} func The function to restrict.
  2934. * @returns {Function} Returns the new restricted function.
  2935. * @example
  2936. *
  2937. * var renderNotes = _.after(notes.length, render);
  2938. * _.forEach(notes, function(note) {
  2939. * note.asyncSave({ 'success': renderNotes });
  2940. * });
  2941. * // `renderNotes` is run once, after all notes have saved
  2942. */
  2943. function after(n, func) {
  2944. if (n < 1) {
  2945. return func();
  2946. }
  2947. return function() {
  2948. if (--n < 1) {
  2949. return func.apply(this, arguments);
  2950. }
  2951. };
  2952. }
  2953. /**
  2954. * Creates a function that, when called, invokes `func` with the `this`
  2955. * binding of `thisArg` and prepends any additional `bind` arguments to those
  2956. * passed to the bound function.
  2957. *
  2958. * @static
  2959. * @memberOf _
  2960. * @category Functions
  2961. * @param {Function} func The function to bind.
  2962. * @param {Mixed} [thisArg] The `this` binding of `func`.
  2963. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
  2964. * @returns {Function} Returns the new bound function.
  2965. * @example
  2966. *
  2967. * var func = function(greeting) {
  2968. * return greeting + ' ' + this.name;
  2969. * };
  2970. *
  2971. * func = _.bind(func, { 'name': 'moe' }, 'hi');
  2972. * func();
  2973. * // => 'hi moe'
  2974. */
  2975. function bind(func, thisArg) {
  2976. // use `Function#bind` if it exists and is fast
  2977. // (in V8 `Function#bind` is slower except when partially applied)
  2978. return isBindFast || (nativeBind && arguments.length > 2)
  2979. ? nativeBind.call.apply(nativeBind, arguments)
  2980. : createBound(func, thisArg, slice.call(arguments, 2));
  2981. }
  2982. /**
  2983. * Binds methods on `object` to `object`, overwriting the existing method.
  2984. * If no method names are provided, all the function properties of `object`
  2985. * will be bound.
  2986. *
  2987. * @static
  2988. * @memberOf _
  2989. * @category Functions
  2990. * @param {Object} object The object to bind and assign the bound methods to.
  2991. * @param {String} [methodName1, methodName2, ...] Method names on the object to bind.
  2992. * @returns {Object} Returns `object`.
  2993. * @example
  2994. *
  2995. * var buttonView = {
  2996. * 'label': 'lodash',
  2997. * 'onClick': function() { alert('clicked: ' + this.label); }
  2998. * };
  2999. *
  3000. * _.bindAll(buttonView);
  3001. * jQuery('#lodash_button').on('click', buttonView.onClick);
  3002. * // => When the button is clicked, `this.label` will have the correct value
  3003. */
  3004. function bindAll(object) {
  3005. var funcs = arguments,
  3006. index = funcs.length > 1 ? 0 : (funcs = functions(object), -1),
  3007. length = funcs.length;
  3008. while (++index < length) {
  3009. var key = funcs[index];
  3010. object[key] = bind(object[key], object);
  3011. }
  3012. return object;
  3013. }
  3014. /**
  3015. * Creates a function that is the composition of the passed functions,
  3016. * where each function consumes the return value of the function that follows.
  3017. * In math terms, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
  3018. * Each function is executed with the `this` binding of the composed function.
  3019. *
  3020. * @static
  3021. * @memberOf _
  3022. * @category Functions
  3023. * @param {Function} [func1, func2, ...] Functions to compose.
  3024. * @returns {Function} Returns the new composed function.
  3025. * @example
  3026. *
  3027. * var greet = function(name) { return 'hi: ' + name; };
  3028. * var exclaim = function(statement) { return statement + '!'; };
  3029. * var welcome = _.compose(exclaim, greet);
  3030. * welcome('moe');
  3031. * // => 'hi: moe!'
  3032. */
  3033. function compose() {
  3034. var funcs = arguments;
  3035. return function() {
  3036. var args = arguments,
  3037. length = funcs.length;
  3038. while (length--) {
  3039. args = [funcs[length].apply(this, args)];
  3040. }
  3041. return args[0];
  3042. };
  3043. }
  3044. /**
  3045. * Creates a function that will delay the execution of `func` until after
  3046. * `wait` milliseconds have elapsed since the last time it was invoked. Pass
  3047. * `true` for `immediate` to cause debounce to invoke `func` on the leading,
  3048. * instead of the trailing, edge of the `wait` timeout. Subsequent calls to
  3049. * the debounced function will return the result of the last `func` call.
  3050. *
  3051. * @static
  3052. * @memberOf _
  3053. * @category Functions
  3054. * @param {Function} func The function to debounce.
  3055. * @param {Number} wait The number of milliseconds to delay.
  3056. * @param {Boolean} immediate A flag to indicate execution is on the leading
  3057. * edge of the timeout.
  3058. * @returns {Function} Returns the new debounced function.
  3059. * @example
  3060. *
  3061. * var lazyLayout = _.debounce(calculateLayout, 300);
  3062. * jQuery(window).on('resize', lazyLayout);
  3063. */
  3064. function debounce(func, wait, immediate) {
  3065. var args,
  3066. result,
  3067. thisArg,
  3068. timeoutId;
  3069. function delayed() {
  3070. timeoutId = null;
  3071. if (!immediate) {
  3072. result = func.apply(thisArg, args);
  3073. }
  3074. }
  3075. return function() {
  3076. var isImmediate = immediate && !timeoutId;
  3077. args = arguments;
  3078. thisArg = this;
  3079. clearTimeout(timeoutId);
  3080. timeoutId = setTimeout(delayed, wait);
  3081. if (isImmediate) {
  3082. result = func.apply(thisArg, args);
  3083. }
  3084. return result;
  3085. };
  3086. }
  3087. /**
  3088. * Executes the `func` function after `wait` milliseconds. Additional arguments
  3089. * will be passed to `func` when it is invoked.
  3090. *
  3091. * @static
  3092. * @memberOf _
  3093. * @category Functions
  3094. * @param {Function} func The function to delay.
  3095. * @param {Number} wait The number of milliseconds to delay execution.
  3096. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
  3097. * @returns {Number} Returns the `setTimeout` timeout id.
  3098. * @example
  3099. *
  3100. * var log = _.bind(console.log, console);
  3101. * _.delay(log, 1000, 'logged later');
  3102. * // => 'logged later' (Appears after one second.)
  3103. */
  3104. function delay(func, wait) {
  3105. var args = slice.call(arguments, 2);
  3106. return setTimeout(function() { func.apply(undefined, args); }, wait);
  3107. }
  3108. /**
  3109. * Defers executing the `func` function until the current call stack has cleared.
  3110. * Additional arguments will be passed to `func` when it is invoked.
  3111. *
  3112. * @static
  3113. * @memberOf _
  3114. * @category Functions
  3115. * @param {Function} func The function to defer.
  3116. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
  3117. * @returns {Number} Returns the `setTimeout` timeout id.
  3118. * @example
  3119. *
  3120. * _.defer(function() { alert('deferred'); });
  3121. * // returns from the function before `alert` is called
  3122. */
  3123. function defer(func) {
  3124. var args = slice.call(arguments, 1);
  3125. return setTimeout(function() { func.apply(undefined, args); }, 1);
  3126. }
  3127. /**
  3128. * Creates a function that, when called, invokes `object[methodName]` and
  3129. * prepends any additional `lateBind` arguments to those passed to the bound
  3130. * function. This method differs from `_.bind` by allowing bound functions to
  3131. * reference methods that will be redefined or don't yet exist.
  3132. *
  3133. * @static
  3134. * @memberOf _
  3135. * @category Functions
  3136. * @param {Object} object The object the method belongs to.
  3137. * @param {String} methodName The method name.
  3138. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
  3139. * @returns {Function} Returns the new bound function.
  3140. * @example
  3141. *
  3142. * var object = {
  3143. * 'name': 'moe',
  3144. * 'greet': function(greeting) {
  3145. * return greeting + ' ' + this.name;
  3146. * }
  3147. * };
  3148. *
  3149. * var func = _.lateBind(object, 'greet', 'hi');
  3150. * func();
  3151. * // => 'hi moe'
  3152. *
  3153. * object.greet = function(greeting) {
  3154. * return greeting + ', ' + this.name + '!';
  3155. * };
  3156. *
  3157. * func();
  3158. * // => 'hi, moe!'
  3159. */
  3160. function lateBind(object, methodName) {
  3161. return createBound(methodName, object, slice.call(arguments, 2));
  3162. }
  3163. /**
  3164. * Creates a function that memoizes the result of `func`. If `resolver` is
  3165. * passed, it will be used to determine the cache key for storing the result
  3166. * based on the arguments passed to the memoized function. By default, the first
  3167. * argument passed to the memoized function is used as the cache key. The `func`
  3168. * is executed with the `this` binding of the memoized function.
  3169. *
  3170. * @static
  3171. * @memberOf _
  3172. * @category Functions
  3173. * @param {Function} func The function to have its output memoized.
  3174. * @param {Function} [resolver] A function used to resolve the cache key.
  3175. * @returns {Function} Returns the new memoizing function.
  3176. * @example
  3177. *
  3178. * var fibonacci = _.memoize(function(n) {
  3179. * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
  3180. * });
  3181. */
  3182. function memoize(func, resolver) {
  3183. var cache = {};
  3184. return function() {
  3185. var key = resolver ? resolver.apply(this, arguments) : arguments[0];
  3186. return hasOwnProperty.call(cache, key)
  3187. ? cache[key]
  3188. : (cache[key] = func.apply(this, arguments));
  3189. };
  3190. }
  3191. /**
  3192. * Creates a function that is restricted to execute `func` once. Repeat calls to
  3193. * the function will return the value of the first call. The `func` is executed
  3194. * with the `this` binding of the created function.
  3195. *
  3196. * @static
  3197. * @memberOf _
  3198. * @category Functions
  3199. * @param {Function} func The function to restrict.
  3200. * @returns {Function} Returns the new restricted function.
  3201. * @example
  3202. *
  3203. * var initialize = _.once(createApplication);
  3204. * initialize();
  3205. * initialize();
  3206. * // Application is only created once.
  3207. */
  3208. function once(func) {
  3209. var result,
  3210. ran = false;
  3211. return function() {
  3212. if (ran) {
  3213. return result;
  3214. }
  3215. ran = true;
  3216. result = func.apply(this, arguments);
  3217. // clear the `func` variable so the function may be garbage collected
  3218. func = null;
  3219. return result;
  3220. };
  3221. }
  3222. /**
  3223. * Creates a function that, when called, invokes `func` with any additional
  3224. * `partial` arguments prepended to those passed to the new function. This
  3225. * method is similar to `bind`, except it does **not** alter the `this` binding.
  3226. *
  3227. * @static
  3228. * @memberOf _
  3229. * @category Functions
  3230. * @param {Function} func The function to partially apply arguments to.
  3231. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
  3232. * @returns {Function} Returns the new partially applied function.
  3233. * @example
  3234. *
  3235. * var greet = function(greeting, name) { return greeting + ': ' + name; };
  3236. * var hi = _.partial(greet, 'hi');
  3237. * hi('moe');
  3238. * // => 'hi: moe'
  3239. */
  3240. function partial(func) {
  3241. return createBound(func, slice.call(arguments, 1));
  3242. }
  3243. /**
  3244. * Creates a function that, when executed, will only call the `func`
  3245. * function at most once per every `wait` milliseconds. If the throttled
  3246. * function is invoked more than once during the `wait` timeout, `func` will
  3247. * also be called on the trailing edge of the timeout. Subsequent calls to the
  3248. * throttled function will return the result of the last `func` call.
  3249. *
  3250. * @static
  3251. * @memberOf _
  3252. * @category Functions
  3253. * @param {Function} func The function to throttle.
  3254. * @param {Number} wait The number of milliseconds to throttle executions to.
  3255. * @returns {Function} Returns the new throttled function.
  3256. * @example
  3257. *
  3258. * var throttled = _.throttle(updatePosition, 100);
  3259. * jQuery(window).on('scroll', throttled);
  3260. */
  3261. function throttle(func, wait) {
  3262. var args,
  3263. result,
  3264. thisArg,
  3265. timeoutId,
  3266. lastCalled = 0;
  3267. function trailingCall() {
  3268. lastCalled = new Date;
  3269. timeoutId = null;
  3270. result = func.apply(thisArg, args);
  3271. }
  3272. return function() {
  3273. var now = new Date,
  3274. remaining = wait - (now - lastCalled);
  3275. args = arguments;
  3276. thisArg = this;
  3277. if (remaining <= 0) {
  3278. clearTimeout(timeoutId);
  3279. lastCalled = now;
  3280. result = func.apply(thisArg, args);
  3281. }
  3282. else if (!timeoutId) {
  3283. timeoutId = setTimeout(trailingCall, remaining);
  3284. }
  3285. return result;
  3286. };
  3287. }
  3288. /**
  3289. * Creates a function that passes `value` to the `wrapper` function as its
  3290. * first argument. Additional arguments passed to the function are appended
  3291. * to those passed to the `wrapper` function. The `wrapper` is executed with
  3292. * the `this` binding of the created function.
  3293. *
  3294. * @static
  3295. * @memberOf _
  3296. * @category Functions
  3297. * @param {Mixed} value The value to wrap.
  3298. * @param {Function} wrapper The wrapper function.
  3299. * @returns {Function} Returns the new function.
  3300. * @example
  3301. *
  3302. * var hello = function(name) { return 'hello ' + name; };
  3303. * hello = _.wrap(hello, function(func) {
  3304. * return 'before, ' + func('moe') + ', after';
  3305. * });
  3306. * hello();
  3307. * // => 'before, hello moe, after'
  3308. */
  3309. function wrap(value, wrapper) {
  3310. return function() {
  3311. var args = [value];
  3312. push.apply(args, arguments);
  3313. return wrapper.apply(this, args);
  3314. };
  3315. }
  3316. /*--------------------------------------------------------------------------*/
  3317. /**
  3318. * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
  3319. * corresponding HTML entities.
  3320. *
  3321. * @static
  3322. * @memberOf _
  3323. * @category Utilities
  3324. * @param {String} string The string to escape.
  3325. * @returns {String} Returns the escaped string.
  3326. * @example
  3327. *
  3328. * _.escape('Moe, Larry & Curly');
  3329. * // => "Moe, Larry &amp; Curly"
  3330. */
  3331. function escape(string) {
  3332. return string == null ? '' : (string + '').replace(reUnescapedHtml, escapeHtmlChar);
  3333. }
  3334. /**
  3335. * This function returns the first argument passed to it.
  3336. *
  3337. * Note: It is used throughout Lo-Dash as a default callback.
  3338. *
  3339. * @static
  3340. * @memberOf _
  3341. * @category Utilities
  3342. * @param {Mixed} value Any value.
  3343. * @returns {Mixed} Returns `value`.
  3344. * @example
  3345. *
  3346. * var moe = { 'name': 'moe' };
  3347. * moe === _.identity(moe);
  3348. * // => true
  3349. */
  3350. function identity(value) {
  3351. return value;
  3352. }
  3353. /**
  3354. * Adds functions properties of `object` to the `lodash` function and chainable
  3355. * wrapper.
  3356. *
  3357. * @static
  3358. * @memberOf _
  3359. * @category Utilities
  3360. * @param {Object} object The object of function properties to add to `lodash`.
  3361. * @example
  3362. *
  3363. * _.mixin({
  3364. * 'capitalize': function(string) {
  3365. * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
  3366. * }
  3367. * });
  3368. *
  3369. * _.capitalize('larry');
  3370. * // => 'Larry'
  3371. *
  3372. * _('curly').capitalize();
  3373. * // => 'Curly'
  3374. */
  3375. function mixin(object) {
  3376. forEach(functions(object), function(methodName) {
  3377. var func = lodash[methodName] = object[methodName];
  3378. lodash.prototype[methodName] = function() {
  3379. var args = [this.__wrapped__];
  3380. push.apply(args, arguments);
  3381. var result = func.apply(lodash, args);
  3382. if (this.__chain__) {
  3383. result = new lodash(result);
  3384. result.__chain__ = true;
  3385. }
  3386. return result;
  3387. };
  3388. });
  3389. }
  3390. /**
  3391. * Reverts the '_' variable to its previous value and returns a reference to
  3392. * the `lodash` function.
  3393. *
  3394. * @static
  3395. * @memberOf _
  3396. * @category Utilities
  3397. * @returns {Function} Returns the `lodash` function.
  3398. * @example
  3399. *
  3400. * var lodash = _.noConflict();
  3401. */
  3402. function noConflict() {
  3403. window._ = oldDash;
  3404. return this;
  3405. }
  3406. /**
  3407. * Produces a random number between `min` and `max` (inclusive). If only one
  3408. * argument is passed, a number between `0` and the given number will be returned.
  3409. *
  3410. * @static
  3411. * @memberOf _
  3412. * @category Utilities
  3413. * @param {Number} [min=0] The minimum possible value.
  3414. * @param {Number} [max=1] The maximum possible value.
  3415. * @returns {Number} Returns a random number.
  3416. * @example
  3417. *
  3418. * _.random(0, 5);
  3419. * // => a number between 1 and 5
  3420. *
  3421. * _.random(5);
  3422. * // => also a number between 1 and 5
  3423. */
  3424. function random(min, max) {
  3425. if (min == null && max == null) {
  3426. max = 1;
  3427. }
  3428. min = +min || 0;
  3429. if (max == null) {
  3430. max = min;
  3431. min = 0;
  3432. }
  3433. return min + floor(nativeRandom() * ((+max || 0) - min + 1));
  3434. }
  3435. /**
  3436. * Resolves the value of `property` on `object`. If `property` is a function
  3437. * it will be invoked and its result returned, else the property value is
  3438. * returned. If `object` is falsey, then `null` is returned.
  3439. *
  3440. * @deprecated
  3441. * @static
  3442. * @memberOf _
  3443. * @category Utilities
  3444. * @param {Object} object The object to inspect.
  3445. * @param {String} property The property to get the value of.
  3446. * @returns {Mixed} Returns the resolved value.
  3447. * @example
  3448. *
  3449. * var object = {
  3450. * 'cheese': 'crumpets',
  3451. * 'stuff': function() {
  3452. * return 'nonsense';
  3453. * }
  3454. * };
  3455. *
  3456. * _.result(object, 'cheese');
  3457. * // => 'crumpets'
  3458. *
  3459. * _.result(object, 'stuff');
  3460. * // => 'nonsense'
  3461. */
  3462. function result(object, property) {
  3463. // based on Backbone's private `getValue` function
  3464. // https://github.com/documentcloud/backbone/blob/0.9.2/backbone.js#L1419-1424
  3465. var value = object ? object[property] : null;
  3466. return isFunction(value) ? object[property]() : value;
  3467. }
  3468. /**
  3469. * A micro-templating method that handles arbitrary delimiters, preserves
  3470. * whitespace, and correctly escapes quotes within interpolated code.
  3471. *
  3472. * Note: In the development build `_.template` utilizes sourceURLs for easier
  3473. * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
  3474. *
  3475. * Note: Lo-Dash may be used in Chrome extensions by either creating a `lodash csp`
  3476. * build and avoiding `_.template` use, or loading Lo-Dash in a sandboxed page.
  3477. * See http://developer.chrome.com/trunk/extensions/sandboxingEval.html
  3478. *
  3479. * @static
  3480. * @memberOf _
  3481. * @category Utilities
  3482. * @param {String} text The template text.
  3483. * @param {Obect} data The data object used to populate the text.
  3484. * @param {Object} options The options object.
  3485. * escape - The "escape" delimiter regexp.
  3486. * evaluate - The "evaluate" delimiter regexp.
  3487. * interpolate - The "interpolate" delimiter regexp.
  3488. * sourceURL - The sourceURL of the template's compiled source.
  3489. * variable - The data object variable name.
  3490. *
  3491. * @returns {Function|String} Returns a compiled function when no `data` object
  3492. * is given, else it returns the interpolated text.
  3493. * @example
  3494. *
  3495. * // using a compiled template
  3496. * var compiled = _.template('hello <%= name %>');
  3497. * compiled({ 'name': 'moe' });
  3498. * // => 'hello moe'
  3499. *
  3500. * var list = '<% _.forEach(people, function(name) { %><li><%= name %></li><% }); %>';
  3501. * _.template(list, { 'people': ['moe', 'larry', 'curly'] });
  3502. * // => '<li>moe</li><li>larry</li><li>curly</li>'
  3503. *
  3504. * // using the "escape" delimiter to escape HTML in data property values
  3505. * _.template('<b><%- value %></b>', { 'value': '<script>' });
  3506. * // => '<b>&lt;script&gt;</b>'
  3507. *
  3508. * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
  3509. * _.template('hello ${ name }', { 'name': 'curly' });
  3510. * // => 'hello curly'
  3511. *
  3512. * // using the internal `print` function in "evaluate" delimiters
  3513. * _.template('<% print("hello " + epithet); %>!', { 'epithet': 'stooge' });
  3514. * // => 'hello stooge!'
  3515. *
  3516. * // using custom template delimiters
  3517. * _.templateSettings = {
  3518. * 'interpolate': /{{([\s\S]+?)}}/g
  3519. * };
  3520. *
  3521. * _.template('hello {{ name }}!', { 'name': 'mustache' });
  3522. * // => 'hello mustache!'
  3523. *
  3524. * // using the `sourceURL` option to specify a custom sourceURL for the template
  3525. * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
  3526. * compiled(data);
  3527. * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
  3528. *
  3529. * // using the `variable` option to ensure a with-statement isn't used in the compiled template
  3530. * var compiled = _.template('hello <%= data.name %>!', null, { 'variable': 'data' });
  3531. * compiled.source;
  3532. * // => function(data) {
  3533. * var __t, __p = '', __e = _.escape;
  3534. * __p += 'hello ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
  3535. * return __p;
  3536. * }
  3537. *
  3538. * // using the `source` property to inline compiled templates for meaningful
  3539. * // line numbers in error messages and a stack trace
  3540. * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
  3541. * var JST = {\
  3542. * "main": ' + _.template(mainText).source + '\
  3543. * };\
  3544. * ');
  3545. */
  3546. function template(text, data, options) {
  3547. // based on John Resig's `tmpl` implementation
  3548. // http://ejohn.org/blog/javascript-micro-templating/
  3549. // and Laura Doktorova's doT.js
  3550. // https://github.com/olado/doT
  3551. text || (text = '');
  3552. options || (options = {});
  3553. var isEvaluating,
  3554. result,
  3555. settings = lodash.templateSettings,
  3556. index = 0,
  3557. interpolate = options.interpolate || settings.interpolate || reNoMatch,
  3558. source = "__p += '",
  3559. variable = options.variable || settings.variable,
  3560. hasVariable = variable;
  3561. // compile regexp to match each delimiter
  3562. var reDelimiters = RegExp(
  3563. (options.escape || settings.escape || reNoMatch).source + '|' +
  3564. interpolate.source + '|' +
  3565. (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
  3566. (options.evaluate || settings.evaluate || reNoMatch).source + '|$'
  3567. , 'g');
  3568. text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
  3569. interpolateValue || (interpolateValue = esTemplateValue);
  3570. // escape characters that cannot be included in string literals
  3571. source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);
  3572. // replace delimiters with snippets
  3573. source +=
  3574. escapeValue ? "' +\n__e(" + escapeValue + ") +\n'" :
  3575. evaluateValue ? "';\n" + evaluateValue + ";\n__p += '" :
  3576. interpolateValue ? "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'" : '';
  3577. isEvaluating || (isEvaluating = evaluateValue || reComplexDelimiter.test(escapeValue || interpolateValue));
  3578. index = offset + match.length;
  3579. });
  3580. source += "';\n";
  3581. // if `variable` is not specified and the template contains "evaluate"
  3582. // delimiters, wrap a with-statement around the generated code to add the
  3583. // data object to the top of the scope chain
  3584. if (!hasVariable) {
  3585. variable = 'obj';
  3586. if (isEvaluating) {
  3587. source = 'with (' + variable + ') {\n' + source + '\n}\n';
  3588. }
  3589. else {
  3590. // avoid a with-statement by prepending data object references to property names
  3591. var reDoubleVariable = RegExp('(\\(\\s*)' + variable + '\\.' + variable + '\\b', 'g');
  3592. source = source
  3593. .replace(reInsertVariable, '$&' + variable + '.')
  3594. .replace(reDoubleVariable, '$1__d');
  3595. }
  3596. }
  3597. // cleanup code by stripping empty strings
  3598. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
  3599. .replace(reEmptyStringMiddle, '$1')
  3600. .replace(reEmptyStringTrailing, '$1;');
  3601. // frame code as the function body
  3602. source = 'function(' + variable + ') {\n' +
  3603. (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
  3604. 'var __t, __p = \'\', __e = _.escape' +
  3605. (isEvaluating
  3606. ? ', __j = Array.prototype.join;\n' +
  3607. 'function print() { __p += __j.call(arguments, \'\') }\n'
  3608. : (hasVariable ? '' : ', __d = ' + variable + '.' + variable + ' || ' + variable) + ';\n'
  3609. ) +
  3610. source +
  3611. 'return __p\n}';
  3612. // use a sourceURL for easier debugging
  3613. // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
  3614. var sourceURL = useSourceURL
  3615. ? '\n//@ sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']')
  3616. : '';
  3617. try {
  3618. result = Function('_', 'return ' + source + sourceURL)(lodash);
  3619. } catch(e) {
  3620. e.source = source;
  3621. throw e;
  3622. }
  3623. if (data) {
  3624. return result(data);
  3625. }
  3626. // provide the compiled function's source via its `toString` method, in
  3627. // supported environments, or the `source` property as a convenience for
  3628. // inlining compiled templates during the build process
  3629. result.source = source;
  3630. return result;
  3631. }
  3632. /**
  3633. * Executes the `callback` function `n` times, returning an array of the results
  3634. * of each `callback` execution. The `callback` is bound to `thisArg` and invoked
  3635. * with one argument; (index).
  3636. *
  3637. * @static
  3638. * @memberOf _
  3639. * @category Utilities
  3640. * @param {Number} n The number of times to execute the callback.
  3641. * @param {Function} callback The function called per iteration.
  3642. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  3643. * @returns {Array} Returns a new array of the results of each `callback` execution.
  3644. * @example
  3645. *
  3646. * var diceRolls = _.times(3, _.partial(_.random, 1, 6));
  3647. * // => [3, 6, 4]
  3648. *
  3649. * _.times(3, function(n) { mage.castSpell(n); });
  3650. * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
  3651. *
  3652. * _.times(3, function(n) { this.cast(n); }, mage);
  3653. * // => also calls `mage.castSpell(n)` three times
  3654. */
  3655. function times(n, callback, thisArg) {
  3656. n = +n || 0;
  3657. var index = -1,
  3658. result = Array(n);
  3659. while (++index < n) {
  3660. result[index] = callback.call(thisArg, index);
  3661. }
  3662. return result;
  3663. }
  3664. /**
  3665. * The opposite of `_.escape`, this method converts the HTML entities
  3666. * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#x27;` in `string` to their
  3667. * corresponding characters.
  3668. *
  3669. * @static
  3670. * @memberOf _
  3671. * @category Utilities
  3672. * @param {String} string The string to unescape.
  3673. * @returns {String} Returns the unescaped string.
  3674. * @example
  3675. *
  3676. * _.unescape('Moe, Larry &amp; Curly');
  3677. * // => "Moe, Larry & Curly"
  3678. */
  3679. function unescape(string) {
  3680. return string == null ? '' : (string + '').replace(reEscapedHtml, unescapeHtmlChar);
  3681. }
  3682. /**
  3683. * Generates a unique id. If `prefix` is passed, the id will be appended to it.
  3684. *
  3685. * @static
  3686. * @memberOf _
  3687. * @category Utilities
  3688. * @param {String} [prefix] The value to prefix the id with.
  3689. * @returns {Number|String} Returns a numeric id if no prefix is passed, else
  3690. * a string id may be returned.
  3691. * @example
  3692. *
  3693. * _.uniqueId('contact_');
  3694. * // => 'contact_104'
  3695. */
  3696. function uniqueId(prefix) {
  3697. var id = idCounter++;
  3698. return prefix ? prefix + id : id;
  3699. }
  3700. /*--------------------------------------------------------------------------*/
  3701. /**
  3702. * Wraps the value in a `lodash` wrapper object.
  3703. *
  3704. * @static
  3705. * @memberOf _
  3706. * @category Chaining
  3707. * @param {Mixed} value The value to wrap.
  3708. * @returns {Object} Returns the wrapper object.
  3709. * @example
  3710. *
  3711. * var stooges = [
  3712. * { 'name': 'moe', 'age': 40 },
  3713. * { 'name': 'larry', 'age': 50 },
  3714. * { 'name': 'curly', 'age': 60 }
  3715. * ];
  3716. *
  3717. * var youngest = _.chain(stooges)
  3718. * .sortBy(function(stooge) { return stooge.age; })
  3719. * .map(function(stooge) { return stooge.name + ' is ' + stooge.age; })
  3720. * .first()
  3721. * .value();
  3722. * // => 'moe is 40'
  3723. */
  3724. function chain(value) {
  3725. value = new lodash(value);
  3726. value.__chain__ = true;
  3727. return value;
  3728. }
  3729. /**
  3730. * Invokes `interceptor` with the `value` as the first argument, and then
  3731. * returns `value`. The purpose of this method is to "tap into" a method chain,
  3732. * in order to perform operations on intermediate results within the chain.
  3733. *
  3734. * @static
  3735. * @memberOf _
  3736. * @category Chaining
  3737. * @param {Mixed} value The value to pass to `interceptor`.
  3738. * @param {Function} interceptor The function to invoke.
  3739. * @returns {Mixed} Returns `value`.
  3740. * @example
  3741. *
  3742. * _.chain([1, 2, 3, 200])
  3743. * .filter(function(num) { return num % 2 == 0; })
  3744. * .tap(alert)
  3745. * .map(function(num) { return num * num })
  3746. * .value();
  3747. * // => // [2, 200] (alerted)
  3748. * // => [4, 40000]
  3749. */
  3750. function tap(value, interceptor) {
  3751. interceptor(value);
  3752. return value;
  3753. }
  3754. /**
  3755. * Enables method chaining on the wrapper object.
  3756. *
  3757. * @name chain
  3758. * @deprecated
  3759. * @memberOf _
  3760. * @category Chaining
  3761. * @returns {Mixed} Returns the wrapper object.
  3762. * @example
  3763. *
  3764. * _([1, 2, 3]).value();
  3765. * // => [1, 2, 3]
  3766. */
  3767. function wrapperChain() {
  3768. this.__chain__ = true;
  3769. return this;
  3770. }
  3771. /**
  3772. * Extracts the wrapped value.
  3773. *
  3774. * @name value
  3775. * @memberOf _
  3776. * @category Chaining
  3777. * @returns {Mixed} Returns the wrapped value.
  3778. * @example
  3779. *
  3780. * _([1, 2, 3]).value();
  3781. * // => [1, 2, 3]
  3782. */
  3783. function wrapperValue() {
  3784. return this.__wrapped__;
  3785. }
  3786. /*--------------------------------------------------------------------------*/
  3787. /**
  3788. * The semantic version number.
  3789. *
  3790. * @static
  3791. * @memberOf _
  3792. * @type String
  3793. */
  3794. lodash.VERSION = '0.9.2';
  3795. // assign static methods
  3796. lodash.after = after;
  3797. lodash.bind = bind;
  3798. lodash.bindAll = bindAll;
  3799. lodash.chain = chain;
  3800. lodash.clone = clone;
  3801. lodash.compact = compact;
  3802. lodash.compose = compose;
  3803. lodash.contains = contains;
  3804. lodash.countBy = countBy;
  3805. lodash.debounce = debounce;
  3806. lodash.defaults = defaults;
  3807. lodash.defer = defer;
  3808. lodash.delay = delay;
  3809. lodash.difference = difference;
  3810. lodash.escape = escape;
  3811. lodash.every = every;
  3812. lodash.extend = extend;
  3813. lodash.filter = filter;
  3814. lodash.find = find;
  3815. lodash.first = first;
  3816. lodash.flatten = flatten;
  3817. lodash.forEach = forEach;
  3818. lodash.forIn = forIn;
  3819. lodash.forOwn = forOwn;
  3820. lodash.functions = functions;
  3821. lodash.groupBy = groupBy;
  3822. lodash.has = has;
  3823. lodash.identity = identity;
  3824. lodash.indexOf = indexOf;
  3825. lodash.initial = initial;
  3826. lodash.intersection = intersection;
  3827. lodash.invert = invert;
  3828. lodash.invoke = invoke;
  3829. lodash.isArguments = isArguments;
  3830. lodash.isArray = isArray;
  3831. lodash.isBoolean = isBoolean;
  3832. lodash.isDate = isDate;
  3833. lodash.isElement = isElement;
  3834. lodash.isEmpty = isEmpty;
  3835. lodash.isEqual = isEqual;
  3836. lodash.isFinite = isFinite;
  3837. lodash.isFunction = isFunction;
  3838. lodash.isNaN = isNaN;
  3839. lodash.isNull = isNull;
  3840. lodash.isNumber = isNumber;
  3841. lodash.isObject = isObject;
  3842. lodash.isPlainObject = isPlainObject;
  3843. lodash.isRegExp = isRegExp;
  3844. lodash.isString = isString;
  3845. lodash.isUndefined = isUndefined;
  3846. lodash.keys = keys;
  3847. lodash.last = last;
  3848. lodash.lastIndexOf = lastIndexOf;
  3849. lodash.lateBind = lateBind;
  3850. lodash.map = map;
  3851. lodash.max = max;
  3852. lodash.memoize = memoize;
  3853. lodash.merge = merge;
  3854. lodash.min = min;
  3855. lodash.mixin = mixin;
  3856. lodash.noConflict = noConflict;
  3857. lodash.object = object;
  3858. lodash.omit = omit;
  3859. lodash.once = once;
  3860. lodash.pairs = pairs;
  3861. lodash.partial = partial;
  3862. lodash.pick = pick;
  3863. lodash.pluck = pluck;
  3864. lodash.random = random;
  3865. lodash.range = range;
  3866. lodash.reduce = reduce;
  3867. lodash.reduceRight = reduceRight;
  3868. lodash.reject = reject;
  3869. lodash.rest = rest;
  3870. lodash.result = result;
  3871. lodash.shuffle = shuffle;
  3872. lodash.size = size;
  3873. lodash.some = some;
  3874. lodash.sortBy = sortBy;
  3875. lodash.sortedIndex = sortedIndex;
  3876. lodash.tap = tap;
  3877. lodash.template = template;
  3878. lodash.throttle = throttle;
  3879. lodash.times = times;
  3880. lodash.toArray = toArray;
  3881. lodash.unescape = unescape;
  3882. lodash.union = union;
  3883. lodash.uniq = uniq;
  3884. lodash.uniqueId = uniqueId;
  3885. lodash.values = values;
  3886. lodash.where = where;
  3887. lodash.without = without;
  3888. lodash.wrap = wrap;
  3889. lodash.zip = zip;
  3890. // assign aliases
  3891. lodash.all = every;
  3892. lodash.any = some;
  3893. lodash.collect = map;
  3894. lodash.detect = find;
  3895. lodash.drop = rest;
  3896. lodash.each = forEach;
  3897. lodash.foldl = reduce;
  3898. lodash.foldr = reduceRight;
  3899. lodash.head = first;
  3900. lodash.include = contains;
  3901. lodash.inject = reduce;
  3902. lodash.methods = functions;
  3903. lodash.select = filter;
  3904. lodash.tail = rest;
  3905. lodash.take = first;
  3906. lodash.unique = uniq;
  3907. // add pseudo private property to be used and removed during the build process
  3908. lodash._iteratorTemplate = iteratorTemplate;
  3909. /*--------------------------------------------------------------------------*/
  3910. // add all static functions to `lodash.prototype`
  3911. mixin(lodash);
  3912. // add `lodash.prototype.chain` after calling `mixin()` to avoid overwriting
  3913. // it with the wrapped `lodash.chain`
  3914. lodash.prototype.chain = wrapperChain;
  3915. lodash.prototype.value = wrapperValue;
  3916. // add all mutator Array functions to the wrapper.
  3917. forEach(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
  3918. var func = arrayRef[methodName];
  3919. lodash.prototype[methodName] = function() {
  3920. var value = this.__wrapped__;
  3921. func.apply(value, arguments);
  3922. // avoid array-like object bugs with `Array#shift` and `Array#splice` in
  3923. // Firefox < 10 and IE < 9
  3924. if (hasObjectSpliceBug && value.length === 0) {
  3925. delete value[0];
  3926. }
  3927. if (this.__chain__) {
  3928. value = new lodash(value);
  3929. value.__chain__ = true;
  3930. }
  3931. return value;
  3932. };
  3933. });
  3934. // add all accessor Array functions to the wrapper.
  3935. forEach(['concat', 'join', 'slice'], function(methodName) {
  3936. var func = arrayRef[methodName];
  3937. lodash.prototype[methodName] = function() {
  3938. var value = this.__wrapped__,
  3939. result = func.apply(value, arguments);
  3940. if (this.__chain__) {
  3941. result = new lodash(result);
  3942. result.__chain__ = true;
  3943. }
  3944. return result;
  3945. };
  3946. });
  3947. /*--------------------------------------------------------------------------*/
  3948. // expose Lo-Dash
  3949. // some AMD build optimizers, like r.js, check for specific condition patterns like the following:
  3950. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  3951. // Expose Lo-Dash to the global object even when an AMD loader is present in
  3952. // case Lo-Dash was injected by a third-party script and not intended to be
  3953. // loaded as a module. The global assignment can be reverted in the Lo-Dash
  3954. // module via its `noConflict()` method.
  3955. window._ = lodash;
  3956. // define as an anonymous module so, through path mapping, it can be
  3957. // referenced as the "underscore" module
  3958. define(function() {
  3959. return lodash;
  3960. });
  3961. }
  3962. // check for `exports` after `define` in case a build optimizer adds an `exports` object
  3963. else if (freeExports) {
  3964. // in Node.js or RingoJS v0.8.0+
  3965. if (typeof module == 'object' && module && module.exports == freeExports) {
  3966. (module.exports = lodash)._ = lodash;
  3967. }
  3968. // in Narwhal or RingoJS v0.7.0-
  3969. else {
  3970. freeExports._ = lodash;
  3971. }
  3972. }
  3973. else {
  3974. // in a browser or Rhino
  3975. window._ = lodash;
  3976. }
  3977. }(this));