PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs//0.3.2/lodash.js

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