PageRenderTime 29ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs//0.2.2/lodash.js

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