PageRenderTime 36ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/ajax/libs//0.2.0/lodash.js

https://gitlab.com/Mirros/cdnjs
JavaScript | 1561 lines | 618 code | 106 blank | 837 comment | 141 complexity | 430a46679843ca2248f2dc5ee6611a72 MD5 | raw file
  1. /*!
  2. * Lo-Dash v0.2.0 <http://lodash.com>
  3. * Copyright 2012 John-David Dalton <http://allyoucanleet.com/>
  4. * Based on Underscore.js 1.3.3, copyright 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
  5. * <http://documentcloud.github.com/underscore>
  6. * Available under MIT license <http://lodash.com/license>
  7. */
  8. ;(function(window, undefined) {
  9. 'use strict';
  10. /** Detect free variable `exports` */
  11. var freeExports = typeof exports == 'object' && exports &&
  12. (typeof global == 'object' && global && global == global.global && (window = global), exports);
  13. /**
  14. * Used to detect the JavaScript engine's argument length limit.
  15. *
  16. * The initial value of `argsLimit` is low enough not to cause uncatchable
  17. * errors in Java and avoid locking up older browsers like Safari 3.
  18. *
  19. * Some engines have a limit on the number of arguments functions can accept
  20. * before clipping the argument length or throwing an error.
  21. * https://bugs.webkit.org/show_bug.cgi?id=80797
  22. *
  23. * For example Firefox's limits have been observed to be at least:
  24. * Firefox 2 - 35,535
  25. * Firefox 3.6 - 16,777,215
  26. * Firefox 4-7 - 523,264
  27. * Firefox >= 8 - Throws error
  28. */
  29. var argsLimit = 5e4;
  30. try {
  31. (function() {
  32. argsLimit = arguments.length;
  33. }).apply(null, Array(argsLimit));
  34. } catch(e) { }
  35. /** Used to escape characters in templates */
  36. var escapes = {
  37. '\\': '\\',
  38. "'": "'",
  39. '\n': 'n',
  40. '\r': 'r',
  41. '\t': 't',
  42. '\u2028': 'u2028',
  43. '\u2029': 'u2029'
  44. };
  45. /**
  46. * Detect the JScript [[DontEnum]] bug:
  47. * In IE < 9 an objects own properties, shadowing non-enumerable ones, are
  48. * made non-enumerable as well.
  49. */
  50. var hasDontEnumBug = !{ 'valueOf': 0 }.propertyIsEnumerable('valueOf');
  51. /** Used to generate unique IDs */
  52. var idCounter = 0;
  53. /** Used to determine if values are of the language type Object */
  54. var objectTypes = {
  55. 'boolean': false,
  56. 'function': true,
  57. 'object': true,
  58. 'number': false,
  59. 'string': false,
  60. 'undefined': false
  61. };
  62. /** Used to restore the original `_` reference in `noConflict` */
  63. var oldDash = window._;
  64. /** Used to match the "escape" template delimiters */
  65. var reEscapeDelimiter = /<%-([\s\S]+?)%>/g;
  66. /** Used to match the "evaluate" template delimiters */
  67. var reEvaluateDelimiter = /<%([\s\S]+?)%>/g;
  68. /** Used to match the "interpolate" template delimiters */
  69. var reInterpolateDelimiter = /<%=([\s\S]+?)%>/g;
  70. /** Used to detect if a method is native */
  71. var reNative = RegExp('^' + ({}.valueOf + '')
  72. .replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&')
  73. .replace(/valueOf|for [^\]]+/g, '.+?') + '$');
  74. /** Used to match tokens in template text */
  75. var reToken = /__token__(\d+)/g;
  76. /** Used to match unescaped characters in template text */
  77. var reUnescaped = /['\n\r\t\u2028\u2029\\]/g;
  78. /** Used to fix the JScript [[DontEnum]] bug */
  79. var shadowed = [
  80. 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
  81. 'toLocaleString', 'toString', 'valueOf'
  82. ];
  83. /** Used to replace template delimiters */
  84. var token = '__token__';
  85. /** Used to store tokenized template text snippets */
  86. var tokenized = [];
  87. /** Object#toString result shortcuts */
  88. var arrayClass = '[object Array]',
  89. boolClass = '[object Boolean]',
  90. dateClass = '[object Date]',
  91. funcClass = '[object Function]',
  92. numberClass = '[object Number]',
  93. regexpClass = '[object RegExp]',
  94. stringClass = '[object String]';
  95. /** Native prototype shortcuts */
  96. var ArrayProto = Array.prototype,
  97. ObjectProto = Object.prototype;
  98. /** Native method shortcuts */
  99. var concat = ArrayProto.concat,
  100. hasOwnProperty = ObjectProto.hasOwnProperty,
  101. push = ArrayProto.push,
  102. slice = ArrayProto.slice,
  103. toString = ObjectProto.toString;
  104. /* Used if `Function#bind` exists and is inferred to be fast (i.e. all but V8) */
  105. var nativeBind = reNative.test(nativeBind = slice.bind) &&
  106. /\n|Opera/.test(nativeBind + toString.call(window.opera)) && nativeBind;
  107. /* Native method shortcuts for methods with the same name as other `lodash` methods */
  108. var nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
  109. nativeIsFinite = window.isFinite,
  110. nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys;
  111. /** Timer shortcuts */
  112. var clearTimeout = window.clearTimeout,
  113. setTimeout = window.setTimeout;
  114. /*--------------------------------------------------------------------------*/
  115. /**
  116. * The template used to create iterator functions.
  117. *
  118. * @private
  119. * @param {Obect} data The data object used to populate the text.
  120. * @returns {String} Returns the interpolated text.
  121. */
  122. var iteratorTemplate = template(
  123. // assign the `result` variable an initial value
  124. 'var index, result<% if (init) { %> = <%= init %><% } %>;\n' +
  125. // add code to exit early or do so if the first argument is falsey
  126. '<%= exit %>;\n' +
  127. // add code after the exit snippet but before the iteration branches
  128. '<%= top %>;\n' +
  129. // the following branch is for iterating arrays and array-like objects
  130. '<% if (arrayBranch) { %>' +
  131. 'var length = <%= firstArg %>.length; index = -1;' +
  132. ' <% if (objectBranch) { %>\nif (length === +length) {<% } %>\n' +
  133. ' <%= arrayBranch.beforeLoop %>;\n' +
  134. ' while (<%= arrayBranch.loopExp %>) {\n' +
  135. ' <%= arrayBranch.inLoop %>;\n' +
  136. ' }' +
  137. ' <% if (objectBranch) { %>\n}\n<% }' +
  138. '}' +
  139. // the following branch is for iterating an object's own/inherited properties
  140. 'if (objectBranch) {' +
  141. ' if (arrayBranch) { %>else {\n<% }' +
  142. ' if (!hasDontEnumBug) { %> var skipProto = typeof <%= iteratedObject %> == \'function\';\n<% } %>' +
  143. ' <%= objectBranch.beforeLoop %>;\n' +
  144. ' for (<%= objectBranch.loopExp %>) {' +
  145. ' \n<%' +
  146. ' if (hasDontEnumBug) {' +
  147. ' if (useHas) { %> if (<%= hasExp %>) {\n <% } %>' +
  148. ' <%= objectBranch.inLoop %>;<%' +
  149. ' if (useHas) { %>\n }<% }' +
  150. ' }' +
  151. ' else {' +
  152. ' %>' +
  153. // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
  154. // (if the prototype or a property on the prototype has been set)
  155. // incorrectly sets a function's `prototype` property [[Enumerable]]
  156. // value to `true`. Because of this Lo-Dash standardizes on skipping
  157. // the the `prototype` property of functions regardless of its
  158. // [[Enumerable]] value.
  159. ' if (!(skipProto && index == \'prototype\')<% if (useHas) { %> && <%= hasExp %><% } %>) {\n' +
  160. ' <%= objectBranch.inLoop %>;\n' +
  161. ' }' +
  162. ' <% } %>\n' +
  163. ' }' +
  164. // Because IE < 9 can't set the `[[Enumerable]]` attribute of an
  165. // existing property and the `constructor` property of a prototype
  166. // defaults to non-enumerable, Lo-Dash skips the `constructor`
  167. // property when it infers it's iterating over a `prototype` object.
  168. ' <% if (hasDontEnumBug) { %>\n' +
  169. ' var ctor = <%= iteratedObject %>.constructor;\n' +
  170. ' <% for (var k = 0; k < 7; k++) { %>\n' +
  171. ' index = \'<%= shadowed[k] %>\';\n' +
  172. ' if (<%' +
  173. ' if (shadowed[k] == \'constructor\') {' +
  174. ' %>!(ctor && ctor.prototype === <%= iteratedObject %>) && <%' +
  175. ' } %><%= hasExp %>) {\n' +
  176. ' <%= objectBranch.inLoop %>;\n' +
  177. ' }<%' +
  178. ' }' +
  179. ' }' +
  180. ' if (arrayBranch) { %>\n}<% }' +
  181. '} %>\n' +
  182. // add code to the bottom of the iteration function
  183. '<%= bottom %>;\n' +
  184. // finally, return the `result`
  185. 'return result'
  186. , null, {
  187. 'evaluate': reEvaluateDelimiter,
  188. 'interpolate': reInterpolateDelimiter
  189. });
  190. /**
  191. * Reusable iterator options shared by
  192. * `every`, `filter`, `find`, `forEach`,`groupBy`, `map`, `reject`, and `some`.
  193. */
  194. var baseIteratorOptions = {
  195. 'args': 'collection, callback, thisArg',
  196. 'init': 'collection',
  197. 'top':
  198. 'if (!callback) {\n' +
  199. ' callback = identity\n' +
  200. '}\n' +
  201. 'else if (thisArg) {\n' +
  202. ' callback = bind(callback, thisArg)\n' +
  203. '}',
  204. 'inLoop': 'callback(collection[index], index, collection)'
  205. };
  206. /** Reusable iterator options for `every` and `some` */
  207. var everyIteratorOptions = {
  208. 'init': 'true',
  209. 'inLoop': 'if (!callback(collection[index], index, collection)) return !result'
  210. };
  211. /** Reusable iterator options for `defaults` and `extend` */
  212. var extendIteratorOptions = {
  213. 'args': 'object',
  214. 'init': 'object',
  215. 'top':
  216. 'for (var source, sourceIndex = 1, length = arguments.length; sourceIndex < length; sourceIndex++) {\n' +
  217. ' source = arguments[sourceIndex];\n' +
  218. (hasDontEnumBug ? ' if (source) {' : ''),
  219. 'loopExp': 'index in source',
  220. 'useHas': false,
  221. 'inLoop': 'object[index] = source[index]',
  222. 'bottom': (hasDontEnumBug ? ' }\n' : '') + '}'
  223. };
  224. /** Reusable iterator options for `filter` and `reject` */
  225. var filterIteratorOptions = {
  226. 'init': '[]',
  227. 'inLoop': 'callback(collection[index], index, collection) && result.push(collection[index])'
  228. };
  229. /** Reusable iterator options for `map`, `pluck`, and `values` */
  230. var mapIteratorOptions = {
  231. 'init': '',
  232. 'exit': 'if (!collection) return []',
  233. 'beforeLoop': {
  234. 'array': 'result = Array(length)',
  235. 'object': 'result = []'
  236. },
  237. 'inLoop': {
  238. 'array': 'result[index] = callback(collection[index], index, collection)',
  239. 'object': 'result.push(callback(collection[index], index, collection))'
  240. }
  241. };
  242. /*--------------------------------------------------------------------------*/
  243. /**
  244. * The `lodash` function.
  245. *
  246. * @name _
  247. * @constructor
  248. * @param {Mixed} value The value to wrap in a `LoDash` instance.
  249. * @returns {Object} Returns a `LoDash` instance.
  250. */
  251. function lodash(value) {
  252. // allow invoking `lodash` without the `new` operator
  253. return new LoDash(value);
  254. }
  255. /**
  256. * Creates a `LoDash` instance that wraps a value to allow chaining.
  257. *
  258. * @private
  259. * @constructor
  260. * @param {Mixed} value The value to wrap.
  261. */
  262. function LoDash(value) {
  263. // exit early if already wrapped
  264. if (value && value._wrapped) {
  265. return value;
  266. }
  267. this._wrapped = value;
  268. }
  269. /*--------------------------------------------------------------------------*/
  270. /**
  271. * Checks if a `value` is an array.
  272. *
  273. * @static
  274. * @memberOf _
  275. * @category Objects
  276. * @param {Mixed} value The value to check.
  277. * @returns {Boolean} Returns `true` if the `value` is an array, else `false`.
  278. * @example
  279. *
  280. * (function() { return _.isArray(arguments); })();
  281. * // => false
  282. *
  283. * _.isArray([1, 2, 3]);
  284. * // => true
  285. */
  286. var isArray = nativeIsArray || function(value) {
  287. return toString.call(value) == arrayClass;
  288. };
  289. /**
  290. * Checks if a `value` is empty. Arrays or strings with a length of `0` and
  291. * objects with no enumerable own properties are considered "empty".
  292. *
  293. * @static
  294. * @memberOf _
  295. * @category Objects
  296. * @param {Mixed} value The value to check.
  297. * @returns {Boolean} Returns `true` if the `value` is empty, else `false`.
  298. * @example
  299. *
  300. * _.isEmpty([1, 2, 3]);
  301. * // => false
  302. *
  303. * _.isEmpty({});
  304. * // => true
  305. */
  306. var isEmpty = createIterator({
  307. 'args': 'value',
  308. 'init': 'true',
  309. 'top':
  310. 'var className = toString.call(value);\n' +
  311. 'if (className == arrayClass || className == stringClass) return !value.length',
  312. 'inLoop': {
  313. 'object': 'return false'
  314. }
  315. });
  316. /*--------------------------------------------------------------------------*/
  317. /**
  318. * Creates compiled iteration functions. The iteration function will be created
  319. * to iterate over only objects if the first argument of `options.args` is
  320. * "object" or `options.inLoop.array` is falsey.
  321. *
  322. * @private
  323. * @param {Object} [options1, options2, ...] The compile options objects.
  324. *
  325. * args - A string of comma separated arguments the iteration function will
  326. * accept.
  327. *
  328. * init - A string to specify the initial value of the `result` variable.
  329. *
  330. * exit - A string of code to use in place of the default exit-early check
  331. * of `if (!arguments[0]) return result`.
  332. *
  333. * top - A string of code to execute after the exit-early check but before
  334. * the iteration branches.
  335. *
  336. * beforeLoop - A string or object containing an "array" or "object" property
  337. * of code to execute before the array or object loops.
  338. *
  339. * loopExp - A string or object containing an "array" or "object" property
  340. * of code to execute as the array or object loop expression.
  341. *
  342. * useHas - A boolean to specify whether or not to use `hasOwnProperty` checks
  343. * in the object loop.
  344. *
  345. * inLoop - A string or object containing an "array" or "object" property
  346. * of code to execute in the array or object loops.
  347. *
  348. * bottom - A string of code to execute after the iteration branches but
  349. * before the `result` is returned.
  350. *
  351. * @returns {Function} Returns the compiled function.
  352. */
  353. function createIterator() {
  354. var object,
  355. prop,
  356. value,
  357. index = -1,
  358. length = arguments.length;
  359. // merge options into a template data object
  360. var data = {
  361. 'bottom': '',
  362. 'exit': '',
  363. 'init': '',
  364. 'top': '',
  365. 'arrayBranch': { 'loopExp': '++index < length' },
  366. 'objectBranch': {}
  367. };
  368. while (++index < length) {
  369. object = arguments[index];
  370. for (prop in object) {
  371. value = (value = object[prop]) == null ? '' : value;
  372. // keep this regexp explicit for the build pre-process
  373. if (/beforeLoop|loopExp|inLoop/.test(prop)) {
  374. if (typeof value == 'string') {
  375. value = { 'array': value, 'object': value };
  376. }
  377. data.arrayBranch[prop] = value.array;
  378. data.objectBranch[prop] = value.object;
  379. } else {
  380. data[prop] = value;
  381. }
  382. }
  383. }
  384. // set additional template data values
  385. var args = data.args,
  386. arrayBranch = data.arrayBranch,
  387. objectBranch = data.objectBranch,
  388. firstArg = /^[^,]+/.exec(args)[0],
  389. loopExp = objectBranch.loopExp,
  390. iteratedObject = /\S+$/.exec(loopExp || firstArg)[0];
  391. data.firstArg = firstArg;
  392. data.hasDontEnumBug = hasDontEnumBug;
  393. data.hasExp = 'hasOwnProperty.call(' + iteratedObject + ', index)';
  394. data.iteratedObject = iteratedObject;
  395. data.shadowed = shadowed;
  396. data.useHas = data.useHas !== false;
  397. if (!data.exit) {
  398. data.exit = 'if (' + firstArg + ' == null) return result';
  399. }
  400. if (firstArg == 'object' || !arrayBranch.inLoop) {
  401. data.arrayBranch = null;
  402. }
  403. if (!loopExp) {
  404. objectBranch.loopExp = 'index in ' + iteratedObject;
  405. }
  406. // create the function factory
  407. var factory = Function(
  408. 'arrayClass, bind, concat, funcClass, hasOwnProperty, identity, indexOf, ' +
  409. 'isArray, isEmpty, objectTypes, slice, stringClass, toString, undefined',
  410. '"use strict"; return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}'
  411. );
  412. // return the compiled function
  413. return factory(
  414. arrayClass, bind, concat, funcClass, hasOwnProperty, identity, indexOf,
  415. isArray, isEmpty, objectTypes, slice, stringClass, toString
  416. );
  417. }
  418. /**
  419. * Used by `template()` to replace tokens with their corresponding code snippets.
  420. *
  421. * @private
  422. * @param {String} match The matched token.
  423. * @param {String} index The `tokenized` index of the code snippet.
  424. * @returns {String} Returns the code snippet.
  425. */
  426. function detokenize(match, index) {
  427. return tokenized[index];
  428. }
  429. /**
  430. * Used by `template()` to escape characters for inclusion in compiled
  431. * string literals.
  432. *
  433. * @private
  434. * @param {String} match The matched character to escape.
  435. * @returns {String} Returns the escaped character.
  436. */
  437. function escapeChar(match) {
  438. return '\\' + escapes[match];
  439. }
  440. /**
  441. * Used by `template()` to replace "escape" template delimiters with tokens.
  442. *
  443. * @private
  444. * @param {String} match The matched template delimiter.
  445. * @param {String} value The delimiter value.
  446. * @returns {String} Returns a token.
  447. */
  448. function tokenizeEscape(match, value) {
  449. var index = tokenized.length;
  450. tokenized[index] = "'+\n((__t = (" + value + ")) == null ? '' : _.escape(__t)) +\n'";
  451. return token + index;
  452. }
  453. /**
  454. * Used by `template()` to replace "interpolate" template delimiters with tokens.
  455. *
  456. * @private
  457. * @param {String} match The matched template delimiter.
  458. * @param {String} value The delimiter value.
  459. * @returns {String} Returns a token.
  460. */
  461. function tokenizeInterpolate(match, value) {
  462. var index = tokenized.length;
  463. tokenized[index] = "'+\n((__t = (" + value + ")) == null ? '' : __t) +\n'";
  464. return token + index;
  465. }
  466. /**
  467. * Used by `template()` to replace "evaluate" template delimiters with tokens.
  468. *
  469. * @private
  470. * @param {String} match The matched template delimiter.
  471. * @param {String} value The delimiter value.
  472. * @returns {String} Returns a token.
  473. */
  474. function tokenizeEvaluate(match, value) {
  475. var index = tokenized.length;
  476. tokenized[index] = "';\n" + value + ";\n__p += '";
  477. return token + index;
  478. }
  479. /*--------------------------------------------------------------------------*/
  480. /**
  481. * Checks if a given `target` value is present in a `collection` using strict
  482. * equality for comparisons, i.e. `===`.
  483. *
  484. * @static
  485. * @memberOf _
  486. * @alias include
  487. * @category Collections
  488. * @param {Array|Object} collection The collection to iterate over.
  489. * @param {Mixed} target The value to check for.
  490. * @returns {Boolean} Returns `true` if `target` value is found, else `false`.
  491. * @example
  492. *
  493. * _.contains([1, 2, 3], 3);
  494. * // => true
  495. */
  496. var contains = createIterator({
  497. 'args': 'collection, target',
  498. 'init': 'false',
  499. 'inLoop': 'if (collection[index] === target) return true'
  500. });
  501. /**
  502. * Checks if the `callback` returns a truthy value for **all** elements of a
  503. * `collection`. The `callback` is invoked with 3 arguments; for arrays they
  504. * are (value, index, array) and for objects they are (value, key, object).
  505. *
  506. * @static
  507. * @memberOf _
  508. * @alias all
  509. * @category Collections
  510. * @param {Array|Object} collection The collection to iterate over.
  511. * @param {Function} callback The function called per iteration.
  512. * @param {Mixed} [thisArg] The `this` binding for the callback.
  513. * @returns {Boolean} Returns `true` if all values pass the callback check, else `false`.
  514. * @example
  515. *
  516. * _.every([true, 1, null, 'yes'], Boolean);
  517. * // => false
  518. */
  519. var every = createIterator(baseIteratorOptions, everyIteratorOptions);
  520. /**
  521. * Examines each value in a `collection`, returning an array of all values the
  522. * `callback` returns truthy for. The `callback` is invoked with 3 arguments;
  523. * for arrays they are (value, index, array) and for objects they are
  524. * (value, key, object).
  525. *
  526. * @static
  527. * @memberOf _
  528. * @alias select
  529. * @category Collections
  530. * @param {Array|Object} collection The collection to iterate over.
  531. * @param {Function} callback The function called per iteration.
  532. * @param {Mixed} [thisArg] The `this` binding for the callback.
  533. * @returns {Array} Returns a new array of values that passed callback check.
  534. * @example
  535. *
  536. * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  537. * // => [2, 4, 6]
  538. */
  539. var filter = createIterator(baseIteratorOptions, filterIteratorOptions);
  540. /**
  541. * Examines each value in a `collection`, returning the first one the `callback`
  542. * returns truthy for. The function returns as soon as it finds an acceptable
  543. * value, and does not iterate over the entire `collection`. The `callback` is
  544. * invoked with 3 arguments; for arrays they are (value, index, array) and for
  545. * objects they are (value, key, object).
  546. *
  547. * @static
  548. * @memberOf _
  549. * @alias detect
  550. * @category Collections
  551. * @param {Array|Object} collection The collection to iterate over.
  552. * @param {Function} callback The function called per iteration.
  553. * @param {Mixed} [thisArg] The `this` binding for the callback.
  554. * @returns {Mixed} Returns the value that passed the callback check, else `undefined`.
  555. * @example
  556. *
  557. * var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  558. * // => 2
  559. */
  560. var find = createIterator(baseIteratorOptions, {
  561. 'inLoop': 'if (callback(collection[index], index, collection)) return collection[index]'
  562. });
  563. /**
  564. * Iterates over a `collection`, executing the `callback` for each value in the
  565. * `collection`. The `callback` is bound to the `thisArg` value, if one is passed.
  566. * The `callback` is invoked with 3 arguments; for arrays they are
  567. * (value, index, array) and for objects they are (value, key, object).
  568. *
  569. * @static
  570. * @memberOf _
  571. * @alias each
  572. * @category Collections
  573. * @param {Array|Object} collection The collection to iterate over.
  574. * @param {Function} callback The function called per iteration.
  575. * @param {Mixed} [thisArg] The `this` binding for the callback.
  576. * @returns {Array|Object} Returns the `collection`.
  577. * @example
  578. *
  579. * _.forEach({ 'one': 1, 'two': 2, 'three': 3}, function(num) { alert(num); });
  580. * // => alerts each number in turn
  581. *
  582. * _([1, 2, 3]).forEach(function(num) { alert(num); }).join(',');
  583. * // => alerts each number in turn and returns '1,2,3'
  584. */
  585. var forEach = createIterator(baseIteratorOptions, {
  586. 'top': 'if (thisArg) callback = bind(callback, thisArg)'
  587. });
  588. /**
  589. * Splits a `collection` into sets, grouped by the result of running each value
  590. * through `callback`. The `callback` is invoked with 3 arguments; for arrays
  591. * they are (value, index, array) and for objects they are (value, key, object).
  592. * The `callback` argument may also be the name of a property to group by.
  593. *
  594. * @static
  595. * @memberOf _
  596. * @category Collections
  597. * @param {Array|Object} collection The collection to iterate over.
  598. * @param {Function|String} callback The function called per iteration or
  599. * property name to group by.
  600. * @param {Mixed} [thisArg] The `this` binding for the callback.
  601. * @returns {Object} Returns an object of grouped values.
  602. * @example
  603. *
  604. * _.groupBy([1.3, 2.1, 2.4], function(num) { return Math.floor(num); });
  605. * // => { '1': [1.3], '2': [2.1, 2.4] }
  606. *
  607. * _.groupBy([1.3, 2.1, 2.4], function(num) { return this.floor(num); }, Math);
  608. * // => { '1': [1.3], '2': [2.1, 2.4] }
  609. *
  610. * _.groupBy(['one', 'two', 'three'], 'length');
  611. * // => { '3': ['one', 'two'], '5': ['three'] }
  612. */
  613. var groupBy = createIterator(baseIteratorOptions, {
  614. 'init': '{}',
  615. 'top':
  616. 'var prop, isFunc = toString.call(callback) == funcClass;\n' +
  617. 'if (isFunc && thisArg) callback = bind(callback, thisArg)',
  618. 'inLoop':
  619. 'prop = isFunc\n' +
  620. ' ? callback(collection[index], index, collection)\n' +
  621. ' : collection[index][callback];\n' +
  622. '(result[prop] || (result[prop] = [])).push(collection[index])'
  623. });
  624. /**
  625. * Produces a new array of values by mapping each value in the `collection`
  626. * through a transformation `callback`. The `callback` is bound to the `thisArg`
  627. * value, if one is passed. The `callback` is invoked with 3 arguments; for
  628. * arrays they are (value, index, array) and for objects they are (value, key, object).
  629. *
  630. * @static
  631. * @memberOf _
  632. * @alias collect
  633. * @category Collections
  634. * @param {Array|Object} collection The collection to iterate over.
  635. * @param {Function} callback The function called per iteration.
  636. * @param {Mixed} [thisArg] The `this` binding for the callback.
  637. * @returns {Array} Returns a new array of values returned by the callback.
  638. * @example
  639. *
  640. * _.map([1, 2, 3], function(num) { return num * 3; });
  641. * // => [3, 6, 9]
  642. *
  643. * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
  644. * // => [3, 6, 9]
  645. */
  646. var map = createIterator(baseIteratorOptions, mapIteratorOptions);
  647. /**
  648. * Retrieves the value of a specified property from all values in a `collection`.
  649. *
  650. * @static
  651. * @memberOf _
  652. * @category Collections
  653. * @param {Array|Object} collection The collection to iterate over.
  654. * @param {String} property The property to pluck.
  655. * @returns {Array} Returns a new array of property values.
  656. * @example
  657. *
  658. * var stooges = [
  659. * { 'name': 'moe', 'age': 40 },
  660. * { 'name': 'larry', 'age': 50 },
  661. * { 'name': 'curly', 'age': 60 }
  662. * ];
  663. *
  664. * _.pluck(stooges, 'name');
  665. * // => ['moe', 'larry', 'curly']
  666. */
  667. var pluck = createIterator(mapIteratorOptions, {
  668. 'args': 'collection, property',
  669. 'inLoop': {
  670. 'array': 'result[index] = collection[index][property]',
  671. 'object': 'result.push(collection[index][property])'
  672. }
  673. });
  674. /**
  675. * Boils down a `collection` to a single value. The initial state of the
  676. * reduction is `accumulator` and each successive step of it should be returned
  677. * by the `callback`. The `callback` is bound to the `thisArg` value, if one is
  678. * passed. The `callback` is invoked with 4 arguments; for arrays they are
  679. * (accumulator, value, index, array) and for objects they are
  680. * (accumulator, value, key, object).
  681. *
  682. * @static
  683. * @memberOf _
  684. * @alias foldl, inject
  685. * @category Collections
  686. * @param {Array|Object} collection The collection to iterate over.
  687. * @param {Function} callback The function called per iteration.
  688. * @param {Mixed} [accumulator] Initial value of the accumulator.
  689. * @param {Mixed} [thisArg] The `this` binding for the callback.
  690. * @returns {Mixed} Returns the accumulated value.
  691. * @example
  692. *
  693. * var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; });
  694. * // => 6
  695. */
  696. var reduce = createIterator({
  697. 'args': 'collection, callback, accumulator, thisArg',
  698. 'init': 'accumulator',
  699. 'top':
  700. 'var noaccum = arguments.length < 3;\n' +
  701. 'if (thisArg) callback = bind(callback, thisArg)',
  702. 'beforeLoop': {
  703. 'array': 'if (noaccum) result = collection[++index]'
  704. },
  705. 'inLoop': {
  706. 'array':
  707. 'result = callback(result, collection[index], index, collection)',
  708. 'object':
  709. 'result = noaccum\n' +
  710. ' ? (noaccum = false, collection[index])\n' +
  711. ' : callback(result, collection[index], index, collection)'
  712. }
  713. });
  714. /**
  715. * The right-associative version of `_.reduce`. The `callback` is bound to the
  716. * `thisArg` value, if one is passed. The `callback` is invoked with 4 arguments;
  717. * for arrays they are (accumulator, value, index, array) and for objects they
  718. * are (accumulator, value, key, object).
  719. *
  720. * @static
  721. * @memberOf _
  722. * @alias foldr
  723. * @category Collections
  724. * @param {Array|Object} collection The collection to iterate over.
  725. * @param {Function} callback The function called per iteration.
  726. * @param {Mixed} [accumulator] Initial value of the accumulator.
  727. * @param {Mixed} [thisArg] The `this` binding for the callback.
  728. * @returns {Mixed} Returns the accumulated value.
  729. * @example
  730. *
  731. * var list = [[0, 1], [2, 3], [4, 5]];
  732. * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  733. * // => [4, 5, 2, 3, 0, 1]
  734. */
  735. function reduceRight(collection, callback, accumulator, thisArg) {
  736. if (!collection) {
  737. return accumulator;
  738. }
  739. var length = collection.length,
  740. noaccum = arguments.length < 3;
  741. if(thisArg) {
  742. callback = bind(callback, thisArg);
  743. }
  744. if (length === +length) {
  745. if (length && noaccum) {
  746. accumulator = collection[--length];
  747. }
  748. while (length--) {
  749. accumulator = callback(accumulator, collection[length], length, collection);
  750. }
  751. return accumulator;
  752. }
  753. var prop,
  754. props = keys(collection);
  755. length = props.length;
  756. if (length && noaccum) {
  757. accumulator = collection[props[--length]];
  758. }
  759. while (length--) {
  760. prop = props[length];
  761. accumulator = callback(accumulator, collection[prop], prop, collection);
  762. }
  763. return accumulator;
  764. }
  765. /**
  766. * The opposite of `_.filter`, this method returns the values of a `collection`
  767. * that `callback` does **not** return truthy for. The `callback` is invoked
  768. * with 3 arguments; for arrays they are (value, index, array) and for objects
  769. * they are (value, key, object).
  770. *
  771. * @static
  772. * @memberOf _
  773. * @category Collections
  774. * @param {Array|Object} collection The collection to iterate over.
  775. * @param {Function} callback The function called per iteration.
  776. * @param {Mixed} [thisArg] The `this` binding for the callback.
  777. * @returns {Array} Returns a new array of values that did **not** pass the callback check.
  778. * @example
  779. *
  780. * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  781. * // => [1, 3, 5]
  782. */
  783. var reject = createIterator(baseIteratorOptions, filterIteratorOptions, {
  784. 'inLoop': '!' + filterIteratorOptions.inLoop
  785. });
  786. /**
  787. * Gets the number of values in the `collection` or the `length` of a string value.
  788. *
  789. * @static
  790. * @memberOf _
  791. * @category Collections
  792. * @param {Array|Object} collection The collection inspect.
  793. * @returns {Number} Returns the number of values in the collection.
  794. * @example
  795. *
  796. * _.size([1, 2]);
  797. * // => 2
  798. *
  799. * _.size({ 'one': 1, 'two': 2, 'three': 3 });
  800. * // => 3
  801. *
  802. * _.size('curly');
  803. * // => 5
  804. */
  805. function size(collection) {
  806. var className = toString.call(collection);
  807. return className == arrayClass || className == stringClass
  808. ? collection.length
  809. : keys(collection).length;
  810. }
  811. /**
  812. * Produces a new sorted array, ranked in ascending order by the results of
  813. * running each value of a `collection` through `callback`. The `callback` is
  814. * invoked with 3 arguments; for arrays they are (value, index, array) and for
  815. * objects they are (value, key, object). The `callback` argument may also be
  816. * the name of a property to sort by (e.g. 'length').
  817. *
  818. * @static
  819. * @memberOf _
  820. * @category Collections
  821. * @param {Array|Object} collection The collection to iterate over.
  822. * @param {Function|String} callback The function called per iteration or
  823. * property name to sort by.
  824. * @param {Mixed} [thisArg] The `this` binding for the callback.
  825. * @returns {Array} Returns a new array of sorted values.
  826. * @example
  827. *
  828. * _.sortBy([1, 2, 3, 4, 5, 6], function(num) { return Math.sin(num); });
  829. * // => [5, 4, 6, 3, 1, 2]
  830. *
  831. * _.sortBy([1, 2, 3, 4, 5, 6], function(num) { return this.sin(num); }, Math);
  832. * // => [5, 4, 6, 3, 1, 2]
  833. */
  834. function sortBy(collection, callback, thisArg) {
  835. if (toString.call(callback) != funcClass) {
  836. var prop = callback;
  837. callback = function(collection) { return collection[prop]; };
  838. } else if (thisArg) {
  839. callback = bind(callback, thisArg);
  840. }
  841. return pluck(map(collection, function(value, index) {
  842. return {
  843. 'criteria': callback(value, index, collection),
  844. 'value': value
  845. };
  846. }).sort(function(left, right) {
  847. var a = left.criteria,
  848. b = right.criteria;
  849. if (a === undefined) {
  850. return 1;
  851. }
  852. if (b === undefined) {
  853. return -1;
  854. }
  855. return a < b ? -1 : a > b ? 1 : 0;
  856. }), 'value');
  857. }
  858. /**
  859. * Checks if the `callback` returns a truthy value for **any** element of a
  860. * `collection`. The function returns as soon as it finds passing value, and
  861. * does not iterate over the entire `collection`. The `callback` is invoked
  862. * with 3 arguments; for arrays they are (value, index, array) and for objects
  863. * they are (value, key, object).
  864. *
  865. * @static
  866. * @memberOf _
  867. * @alias any
  868. * @category Collections
  869. * @param {Array|Object} collection The collection to iterate over.
  870. * @param {Function} callback The function called per iteration.
  871. * @param {Mixed} [thisArg] The `this` binding for the callback.
  872. * @returns {Boolean} Returns `true` if any value passes the callback check, else `false`.
  873. * @example
  874. *
  875. * _.some([null, 0, 'yes', false]);
  876. * // => true
  877. */
  878. var some = createIterator(baseIteratorOptions, everyIteratorOptions, {
  879. 'init': 'false',
  880. 'inLoop': everyIteratorOptions.inLoop.replace('!', '')
  881. });
  882. /**
  883. * Converts the `collection`, into an array. Useful for converting the
  884. * `arguments` object.
  885. *
  886. * @static
  887. * @memberOf _
  888. * @category Collections
  889. * @param {Array|Object} collection The collection to convert.
  890. * @returns {Array} Returns the new converted array.
  891. * @example
  892. *
  893. * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
  894. * // => [2, 3, 4]
  895. */
  896. function toArray(collection) {
  897. if (!collection) {
  898. return [];
  899. }
  900. if (toString.call(collection.toArray) == funcClass) {
  901. return collection.toArray();
  902. }
  903. var length = collection.length;
  904. if (length === +length) {
  905. return slice.call(collection);
  906. }
  907. return values(collection);
  908. }
  909. /**
  910. * Produces an array of enumerable own property values of the `collection`.
  911. *
  912. * @static
  913. * @memberOf _
  914. * @alias methods
  915. * @category Collections
  916. * @param {Array|Object} collection The collection to inspect.
  917. * @returns {Array} Returns a new array of property values.
  918. * @example
  919. *
  920. * _.values({ 'one': 1, 'two': 2, 'three': 3 });
  921. * // => [1, 2, 3]
  922. */
  923. var values = createIterator(mapIteratorOptions, {
  924. 'args': 'collection',
  925. 'inLoop': {
  926. 'array': 'result[index] = collection[index]',
  927. 'object': 'result.push(collection[index])'
  928. }
  929. });
  930. /*--------------------------------------------------------------------------*/
  931. /**
  932. * Produces a new array with all falsey values of `array` removed. The values
  933. * `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey.
  934. *
  935. * @static
  936. * @memberOf _
  937. * @category Arrays
  938. * @param {Array} array The array to compact.
  939. * @returns {Array} Returns a new filtered array.
  940. * @example
  941. *
  942. * _.compact([0, 1, false, 2, '', 3]);
  943. * // => [1, 2, 3]
  944. */
  945. function compact(array) {
  946. var index = -1,
  947. length = array.length,
  948. result = [];
  949. while (++index < length) {
  950. if (array[index]) {
  951. result.push(array[index]);
  952. }
  953. }
  954. return result;
  955. }
  956. /**
  957. * Produces a new array of `array` values not present in the other arrays
  958. * using strict equality for comparisons, i.e. `===`.
  959. *
  960. * @static
  961. * @memberOf _
  962. * @category Arrays
  963. * @param {Array} array The array to process.
  964. * @param {Array} [array1, array2, ...] Arrays to check.
  965. * @returns {Array} Returns a new array of `array` values not present in the
  966. * other arrays.
  967. * @example
  968. *
  969. * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
  970. * // => [1, 3, 4]
  971. */
  972. function difference(array) {
  973. var index = -1,
  974. length = array.length,
  975. result = [],
  976. flattened = concat.apply(result, slice.call(arguments, 1));
  977. while (++index < length) {
  978. if (indexOf(flattened, array[index]) < 0) {
  979. result.push(array[index]);
  980. }
  981. }
  982. return result;
  983. }
  984. /**
  985. * Gets the first value of the `array`. Pass `n` to return the first `n` values
  986. * of the `array`.
  987. *
  988. * @static
  989. * @memberOf _
  990. * @alias head, take
  991. * @category Arrays
  992. * @param {Array} array The array to query.
  993. * @param {Number} [n] The number of elements to return.
  994. * @param {Object} [guard] Internally used to allow this method to work with
  995. * others like `_.map` without using their callback `index` argument for `n`.
  996. * @returns {Mixed} Returns the first value or an array of the first `n` values
  997. * of the `array`.
  998. * @example
  999. *
  1000. * _.first([5, 4, 3, 2, 1]);
  1001. * // => 5
  1002. */
  1003. function first(array, n, guard) {
  1004. return (n == undefined || guard) ? array[0] : slice.call(array, 0, n);
  1005. }
  1006. /**
  1007. * Flattens a nested array (the nesting can be to any depth). If `shallow` is
  1008. * truthy, `array` will only be flattened a single level.
  1009. *
  1010. * @static
  1011. * @memberOf _
  1012. * @category Arrays
  1013. * @param {Array} array The array to compact.
  1014. * @param {Boolean} shallow A flag to indicate only flattening a single level.
  1015. * @returns {Array} Returns a new flattened array.
  1016. * @example
  1017. *
  1018. * _.flatten([1, [2], [3, [[4]]]]);
  1019. * // => [1, 2, 3, 4];
  1020. *
  1021. * _.flatten([1, [2], [3, [[4]]]], true);
  1022. * // => [1, 2, 3, [[4]]];
  1023. */
  1024. function flatten(array, shallow) {
  1025. if (shallow) {
  1026. return concat.apply(ArrayProto, array);
  1027. }
  1028. var value,
  1029. index = -1,
  1030. length = array.length,
  1031. result = [];
  1032. while (++index < length) {
  1033. value = array[index];
  1034. if (isArray(value)) {
  1035. push.apply(result, flatten(value));
  1036. } else {
  1037. result.push(value);
  1038. }
  1039. }
  1040. return result;
  1041. }
  1042. /**
  1043. * Gets the index at which the first occurrence of `value` is found using
  1044. * strict equality for comparisons, i.e. `===`. If the `array` is already
  1045. * sorted, passing `true` for `isSorted` will run a faster binary search.
  1046. *
  1047. * @static
  1048. * @memberOf _
  1049. * @category Arrays
  1050. * @param {Array} array The array to search.
  1051. * @param {Mixed} value The value to search for.
  1052. * @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted.
  1053. * @returns {Number} Returns the index of the matched value or `-1`.
  1054. * @example
  1055. *
  1056. * _.indexOf([1, 2, 3], 2);
  1057. * // => 1
  1058. */
  1059. function indexOf(array, value, isSorted) {
  1060. var index, length;
  1061. if (!array) {
  1062. return -1;
  1063. }
  1064. if (isSorted) {
  1065. index = sortedIndex(array, value);
  1066. return array[index] === value ? index : -1;
  1067. }
  1068. for (index = 0, length = array.length; index < length; index++) {
  1069. if (array[index] === value) {
  1070. return index;
  1071. }
  1072. }
  1073. return -1;
  1074. }
  1075. /**
  1076. * Gets all but the last value of the `array`. Pass `n` to exclude the last `n`
  1077. * values from the result.
  1078. *
  1079. * @static
  1080. * @memberOf _
  1081. * @category Arrays
  1082. * @param {Array} array The array to query.
  1083. * @param {Number} [n] The number of elements to return.
  1084. * @param {Object} [guard] Internally used to allow this method to work with
  1085. * others like `_.map` without using their callback `index` argument for `n`.
  1086. * @returns {Array} Returns all but the last value or `n` values of the `array`.
  1087. * @example
  1088. *
  1089. * _.initial([5, 4, 3, 2, 1]);
  1090. * // => [5, 4, 3, 2]
  1091. */
  1092. function initial(array, n, guard) {
  1093. return slice.call(array, 0, -((n == undefined || guard) ? 1 : n));
  1094. }
  1095. /**
  1096. * Computes the intersection of all the passed-in arrays.
  1097. *
  1098. * @static
  1099. * @memberOf _
  1100. * @alias intersect
  1101. * @category Arrays
  1102. * @param {Array} [array1, array2, ...] Arrays to process.
  1103. * @returns {Array} Returns a new array of unique values, in order, that are
  1104. * present in **all** of the arrays.
  1105. * @example
  1106. *
  1107. * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  1108. * // => [1, 2]
  1109. */
  1110. function intersection(array) {
  1111. var value,
  1112. index = -1,
  1113. length = array.length,
  1114. others = slice.call(arguments, 1),
  1115. result = [];
  1116. while (++index < length) {
  1117. value = array[index];
  1118. if (indexOf(result, value) < 0 &&
  1119. every(others, function(other) { return indexOf(other, value) > -1; })) {
  1120. result.push(value);
  1121. }
  1122. }
  1123. return result;
  1124. }
  1125. /**
  1126. * Calls the method named by `methodName` for each value of the `collection`.
  1127. * Additional arguments will be passed to each invoked method.
  1128. *
  1129. * @static
  1130. * @memberOf _
  1131. * @category Arrays
  1132. * @param {Array} array The array to iterate over.
  1133. * @param {String} methodName The name of the method to invoke.
  1134. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
  1135. * @returns {Array} Returns a new array of values returned from each invoked method.
  1136. * @example
  1137. *
  1138. * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  1139. * // => [[1, 5, 7], [1, 2, 3]]
  1140. */
  1141. function invoke(array, methodName) {
  1142. var args = slice.call(arguments, 2),
  1143. index = -1,
  1144. length = array.length,
  1145. isFunc = toString.call(methodName) == funcClass,
  1146. result = [];
  1147. while (++index < length) {
  1148. result[index] = (isFunc ? methodName : array[index][methodName]).apply(array[index], args);
  1149. }
  1150. return result;
  1151. }
  1152. /**
  1153. * Gets the last value of the `array`. Pass `n` to return the lasy `n` values
  1154. * of the `array`.
  1155. *
  1156. * @static
  1157. * @memberOf _
  1158. * @category Arrays
  1159. * @param {Array} array The array to query.
  1160. * @param {Number} [n] The number of elements to return.
  1161. * @param {Object} [guard] Internally used to allow this method to work with
  1162. * others like `_.map` without using their callback `index` argument for `n`.
  1163. * @returns {Array} Returns all but the last value or `n` values of the `array`.
  1164. * @example
  1165. *
  1166. * _.last([5, 4, 3, 2, 1]);
  1167. * // => 1
  1168. */
  1169. function last(array, n, guard) {
  1170. var length = array.length;
  1171. return (n == undefined || guard) ? array[length - 1] : slice.call(array, -n || length);
  1172. }
  1173. /**
  1174. * Gets the index at which the last occurrence of `value` is found using
  1175. * strict equality for comparisons, i.e. `===`.
  1176. *
  1177. * @static
  1178. * @memberOf _
  1179. * @category Arrays
  1180. * @param {Array} array The array to search.
  1181. * @param {Mixed} value The value to search for.
  1182. * @returns {Number} Returns the index of the matched value or `-1`.
  1183. * @example
  1184. *
  1185. * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
  1186. * // => 4
  1187. */
  1188. function lastIndexOf(array, value) {
  1189. if (!array) {
  1190. return -1;
  1191. }
  1192. var index = array.length;
  1193. while (index--) {
  1194. if (array[index] === value) {
  1195. return index;
  1196. }
  1197. }
  1198. return -1;
  1199. }
  1200. /**
  1201. * Retrieves the maximum value of an `array`. If `callback` is passed,
  1202. * it will be executed for each value in the `array` to generate the
  1203. * criterion by which the value is ranked. The `callback` is invoked with 3
  1204. * arguments; (value, index, array).
  1205. *
  1206. * @static
  1207. * @memberOf _
  1208. * @category Arrays
  1209. * @param {Array} array The array to iterate over.
  1210. * @param {Function} [callback] The function called per iteration.
  1211. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1212. * @returns {Mixed} Returns the maximum value.
  1213. * @example
  1214. *
  1215. * var stooges = [
  1216. * { 'name': 'moe', 'age': 40 },
  1217. * { 'name': 'larry', 'age': 50 },
  1218. * { 'name': 'curly', 'age': 60 }
  1219. * ];
  1220. *
  1221. * _.max(stooges, function(stooge) { return stooge.age; });
  1222. * // => { 'name': 'curly', 'age': 60 };
  1223. */
  1224. function max(array, callback, thisArg) {
  1225. var current,
  1226. computed = -Infinity,
  1227. index = -1,
  1228. length = array.length,
  1229. result = computed;
  1230. if (!callback) {
  1231. // fast path for arrays of numbers
  1232. if (array[0] === +array[0] && length <= argsLimit) {
  1233. // some JavaScript engines have a limit on the number of arguments functions
  1234. // can accept before clipping the argument length or throwing an error
  1235. try {
  1236. return Math.max.apply(Math, array);
  1237. } catch(e) { }
  1238. }
  1239. if (!array.length) {
  1240. return result;
  1241. }
  1242. } else if (thisArg) {
  1243. callback = bind(callback, thisArg);
  1244. }
  1245. while (++index < length) {
  1246. current = callback ? callback(array[index], index, array) : array[index];
  1247. if (current > computed) {
  1248. computed = current;
  1249. result = array[index];
  1250. }
  1251. }
  1252. return result;
  1253. }
  1254. /**
  1255. * Retrieves the minimum value of an `array`. If `callback` is passed,
  1256. * it will be executed for each value in the `array` to generate the
  1257. * criterion by which the value is ranked. The `callback` is invoked with 3
  1258. * arguments; (value, index, array).
  1259. *
  1260. * @static
  1261. * @memberOf _
  1262. * @category Arrays
  1263. * @param {Array} array The array to iterate over.
  1264. * @param {Function} [callback] The function called per iteration.
  1265. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1266. * @returns {Mixed} Returns the minimum value.
  1267. * @example
  1268. *
  1269. * _.min([10, 5, 100, 2, 1000]);
  1270. * // => 2
  1271. */
  1272. function min(array, callback, thisArg) {
  1273. var current,
  1274. computed = Infinity,
  1275. index = -1,
  1276. length = array.length,
  1277. result = computed;
  1278. if (!callback) {
  1279. if (array[0] === +array[0] && length <= argsLimit) {
  1280. try {
  1281. return Math.min.apply(Math, array);
  1282. } catch(e) { }
  1283. }
  1284. if (!array.length) {
  1285. return result;
  1286. }
  1287. } else if (thisArg) {
  1288. callback = bind(callback, thisArg);
  1289. }
  1290. while (++index < length) {
  1291. current = callback ? callback(array[index], index, array) : array[index];
  1292. if (current < computed) {
  1293. computed = current;
  1294. result = array[index];
  1295. }
  1296. }
  1297. return result;
  1298. }
  1299. /**
  1300. * Creates an array of numbers (positive and/or negative) progressing from
  1301. * `start` up to but not including `stop`. This method is a port of Python's
  1302. * `range()` function. See http://docs.python.org/library/functions.html#range.
  1303. *
  1304. * @static
  1305. * @memberOf _
  1306. * @category Arrays
  1307. * @param {Number} [start=0] The start of the range.
  1308. * @param {Number} end The end of the range.
  1309. * @param {Number} [step=1] The value to increment or descrement by.
  1310. * @returns {Array} Returns a new range array.
  1311. * @example
  1312. *
  1313. * _.range(10);
  1314. * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1315. *
  1316. * _.range(1, 11);
  1317. * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1318. *
  1319. * _.range(0, 30, 5);
  1320. * // => [0, 5, 10, 15, 20, 25]
  1321. *
  1322. * _.range(0, -10, -1);
  1323. * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  1324. *
  1325. * _.range(0);
  1326. * // => []
  1327. */
  1328. function range(start, end, step) {
  1329. step || (step = 1);
  1330. if (arguments.length < 2) {
  1331. end = start || 0;
  1332. start = 0;
  1333. }
  1334. var index = -1,
  1335. length = Math.max(Math.ceil((end - start) / step), 0),
  1336. result = Array(length);
  1337. while (++index < length) {
  1338. result[index] = start;
  1339. start += step;
  1340. }
  1341. return result;
  1342. }
  1343. /**
  1344. * The opposite of `_.initial`, this method gets all but the first value of
  1345. * the `array`. Pass `n` to exclude the first `n` values from the result.
  1346. *
  1347. * @static
  1348. * @memberOf _
  1349. * @alias tail
  1350. * @category Arrays
  1351. * @param {Array} array The array to query.
  1352. * @param {Number} [n] The number of elements to return.
  1353. * @param {Object} [guard] Internally used to allow this method to work with
  1354. * others like `_.map` without using their callback `index` argument for `n`.
  1355. * @returns {Array} Returns all but the first value or `n` values of the `array`.
  1356. * @example
  1357. *
  1358. * _.rest([5, 4, 3, 2, 1]);
  1359. * // => [4, 3, 2, 1]
  1360. */
  1361. function rest(array, n, guard) {
  1362. return slice.call(array, (n == undefined || guard) ? 1 : n);
  1363. }
  1364. /**
  1365. * Produces a new array of shuffled `array` values, using a version of the
  1366. * Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
  1367. *
  1368. * @static
  1369. * @memberOf _
  1370. * @category Arrays
  1371. * @param {Array} array The array to shuffle.
  1372. * @returns {Array} Returns a new shuffled array.
  1373. * @example
  1374. *
  1375. * _.shuffle([1, 2, 3, 4, 5, 6]);
  1376. * // => [4, 1, 6, 3, 5, 2]
  1377. */
  1378. function shuffle(array) {
  1379. var rand,
  1380. index = -1,
  1381. length = array.length,
  1382. result = Array(length);
  1383. while (++index < length) {
  1384. rand = Math.floor(Math.random() * (index + 1));
  1385. result[index] = result[rand];
  1386. result[rand] = array[index];
  1387. }
  1388. return result;
  1389. }
  1390. /**
  1391. * Uses a binary search to determine the smallest index at which the `value`
  1392. * should be inserted into the `collection` in order to maintain the sort order
  1393. * of the `collection`. If `callback` is passed, it will be executed for each
  1394. * value in the `collection` to compute their sort ranking. The `callback` is
  1395. * invoked with 1 argument; (value).
  1396. *
  1397. * @static
  1398. * @memberOf _
  1399. * @category Arrays
  1400. * @param {Array} array The array to iterate over.
  1401. * @param {Mixed} value The value to evaluate.
  1402. * @param {Function} [callback] The function called per iteration.
  1403. * @returns {Number} Returns the index at which the value should be inserted
  1404. * into the collection.
  1405. * @example
  1406. *
  1407. * _.sortedIndex([10, 20, 30, 40, 50], 35);
  1408. * // => 3
  1409. */
  1410. function sortedIndex(array, value, callback) {
  1411. var mid,
  1412. low = 0,
  1413. high = array.length;
  1414. if (callback) {
  1415. value = callback(value);
  1416. }
  1417. while (low < high) {
  1418. mid = (low + high) >> 1;
  1419. if ((callback ? callback(array[mid]) : array[mid]) < value) {
  1420. low = mid + 1;
  1421. } else {
  1422. high = mid;
  1423. }
  1424. }
  1425. return low;
  1426. }
  1427. /**
  1428. * Computes the union of the passed-in arrays.
  1429. *
  1430. * @static
  1431. * @memberOf _
  1432. * @category Arrays
  1433. * @param {Array} [array1, array2, ...] Arrays to process.
  1434. * @returns {Array} Returns a new array of unique values, in order, that are
  1435. * present in one or more of the arrays.
  1436. * @example
  1437. *
  1438. * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  1439. * // => [1, 2, 3, 101, 10]
  1440. */
  1441. function union() {
  1442. var index = -1,
  1443. result = [],
  1444. flattened = concat.apply(result, arguments),
  1445. length = flattened.length;
  1446. while (++index < length) {
  1447. if (indexOf(result, flattened[index]) < 0) {
  1448. result.push(flattened[index]);
  1449. }
  1450. }
  1451. return result;
  1452. }
  1453. /**
  1454. * Produces a duplicate-value-free version of the `array` using strict equality
  1455. * for comparisons, i.e. `===`