PageRenderTime 51ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs//0.4.1/lodash.js

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