PageRenderTime 76ms CodeModel.GetById 40ms RepoModel.GetById 1ms app.codeStats 0ms

/ajax/libs//0.2.1/lodash.js

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