PageRenderTime 70ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/node_modules/grunt-bower-task/node_modules/lodash/lodash.js

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