PageRenderTime 45ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs//0.3.0/lodash.js

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