PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs//0.3.1/lodash.js

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