PageRenderTime 68ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/ajax/libs//0.1.0/lodash.js

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