PageRenderTime 38ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/node_modules/grunt-contrib-jshint/node_modules/jshint/tests/stable/regression/libs/lodash.js

https://bitbucket.org/biojazzard/gantry-eboracast
JavaScript | 4454 lines | 1801 code | 291 blank | 2362 comment | 475 complexity | 913b539b8245e34f553c81368197c807 MD5 | raw file
Possible License(s): MIT, JSON, BSD-2-Clause, Unlicense, GPL-2.0, WTFPL, LGPL-3.0, Apache-2.0, 0BSD, BSD-3-Clause, CC-BY-SA-3.0
  1. /*!
  2. * Lo-Dash v0.6.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. BoolProto = Boolean.prototype,
  37. ObjectProto = Object.prototype,
  38. NumberProto = Number.prototype,
  39. StringProto = String.prototype;
  40. /** Used to generate unique IDs */
  41. var idCounter = 0;
  42. /** Used by `cachedContains` as the default size when optimizations are enabled for large arrays */
  43. var largeArraySize = 30;
  44. /** Used to restore the original `_` reference in `noConflict` */
  45. var oldDash = window._;
  46. /** Used to detect delimiter values that should be processed by `tokenizeEvaluate` */
  47. var reComplexDelimiter = /[-+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/;
  48. /** Used to match HTML entities */
  49. var reEscapedHtml = /&(?:amp|lt|gt|quot|#x27);/g;
  50. /** Used to match empty string literals in compiled template source */
  51. var reEmptyStringLeading = /\b__p \+= '';/g,
  52. reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
  53. reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
  54. /** Used to match regexp flags from their coerced string values */
  55. var reFlags = /\w*$/;
  56. /** Used to insert the data object variable into compiled template source */
  57. var reInsertVariable = /(?:__e|__t = )\(\s*(?![\d\s"']|this\.)/g;
  58. /** Used to detect if a method is native */
  59. var reNative = RegExp('^' +
  60. (ObjectProto.valueOf + '')
  61. .replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&')
  62. .replace(/valueOf|for [^\]]+/g, '.+?') + '$'
  63. );
  64. /** Used to match internally used tokens in template text */
  65. var reToken = /__token(\d+)__/g;
  66. /** Used to match HTML characters */
  67. var reUnescapedHtml = /[&<>"']/g;
  68. /** Used to match unescaped characters in compiled string literals */
  69. var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
  70. /** Used to fix the JScript [[DontEnum]] bug */
  71. var shadowed = [
  72. 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
  73. 'toLocaleString', 'toString', 'valueOf'
  74. ];
  75. /** Used to make template sourceURLs easier to identify */
  76. var templateCounter = 0;
  77. /** Used to replace template delimiters */
  78. var tokenHead = '__token',
  79. tokenFoot = '__';
  80. /** Used to store tokenized template text snippets */
  81. var tokenized = [];
  82. /** Native method shortcuts */
  83. var concat = ArrayProto.concat,
  84. hasOwnProperty = ObjectProto.hasOwnProperty,
  85. push = ArrayProto.push,
  86. propertyIsEnumerable = ObjectProto.propertyIsEnumerable,
  87. slice = ArrayProto.slice,
  88. toString = ObjectProto.toString;
  89. /* Native method shortcuts for methods with the same name as other `lodash` methods */
  90. var nativeBind = reNative.test(nativeBind = slice.bind) && nativeBind,
  91. nativeFloor = Math.floor,
  92. nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
  93. nativeIsFinite = window.isFinite,
  94. nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys,
  95. nativeMax = Math.max,
  96. nativeMin = Math.min,
  97. nativeRandom = Math.random;
  98. /** `Object#toString` result shortcuts */
  99. var argsClass = '[object Arguments]',
  100. arrayClass = '[object Array]',
  101. boolClass = '[object Boolean]',
  102. dateClass = '[object Date]',
  103. funcClass = '[object Function]',
  104. numberClass = '[object Number]',
  105. objectClass = '[object Object]',
  106. regexpClass = '[object RegExp]',
  107. stringClass = '[object String]';
  108. /** Timer shortcuts */
  109. var clearTimeout = window.clearTimeout,
  110. setTimeout = window.setTimeout;
  111. /**
  112. * Detect the JScript [[DontEnum]] bug:
  113. *
  114. * In IE < 9 an objects own properties, shadowing non-enumerable ones, are
  115. * made non-enumerable as well.
  116. */
  117. var hasDontEnumBug;
  118. /**
  119. * Detect if `Array#shift` and `Array#splice` augment array-like objects
  120. * incorrectly:
  121. *
  122. * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()`
  123. * and `splice()` functions that fail to remove the last element, `value[0]`,
  124. * of array-like objects even though the `length` property is set to `0`.
  125. * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
  126. * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
  127. */
  128. var hasObjectSpliceBug;
  129. /** Detect if own properties are iterated after inherited properties (IE < 9) */
  130. var iteratesOwnLast;
  131. /** Detect if an `arguments` object's indexes are non-enumerable (IE < 9) */
  132. var noArgsEnum = true;
  133. (function() {
  134. var object = { '0': 1, 'length': 1 },
  135. props = [];
  136. function ctor() { this.x = 1; }
  137. ctor.prototype = { 'valueOf': 1, 'y': 1 };
  138. for (var prop in new ctor) { props.push(prop); }
  139. for (prop in arguments) { noArgsEnum = !prop; }
  140. hasDontEnumBug = (props + '').length < 4;
  141. iteratesOwnLast = props[0] != 'x';
  142. hasObjectSpliceBug = (props.splice.call(object, 0, 1), object[0]);
  143. }(1));
  144. /** Detect if an `arguments` object's [[Class]] is unresolvable (Firefox < 4, IE < 9) */
  145. var noArgsClass = !isArguments(arguments);
  146. /** Detect if `Array#slice` cannot be used to convert strings to arrays (Opera < 10.52) */
  147. var noArraySliceOnStrings = slice.call('x')[0] != 'x';
  148. /**
  149. * Detect lack of support for accessing string characters by index:
  150. *
  151. * IE < 8 can't access characters by index and IE 8 can only access
  152. * characters by index on string literals.
  153. */
  154. var noCharByIndex = ('x'[0] + Object('x')[0]) != 'xx';
  155. /**
  156. * Detect if a node's [[Class]] is unresolvable (IE < 9)
  157. * and that the JS engine won't error when attempting to coerce an object to
  158. * a string without a `toString` property value of `typeof` "function".
  159. */
  160. try {
  161. var noNodeClass = ({ 'toString': 0 } + '', toString.call(window.document || 0) == objectClass);
  162. } catch(e) { }
  163. /* Detect if `Function#bind` exists and is inferred to be fast (all but V8) */
  164. var isBindFast = nativeBind && /\n|Opera/.test(nativeBind + toString.call(window.opera));
  165. /* Detect if `Object.keys` exists and is inferred to be fast (IE, Opera, V8) */
  166. var isKeysFast = nativeKeys && /^.+$|true/.test(nativeKeys + !!window.attachEvent);
  167. /* Detect if strict mode, "use strict", is inferred to be fast (V8) */
  168. var isStrictFast = !isBindFast;
  169. /**
  170. * Detect if sourceURL syntax is usable without erroring:
  171. *
  172. * The JS engine in Adobe products, like InDesign, will throw a syntax error
  173. * when it encounters a single line comment beginning with the `@` symbol.
  174. *
  175. * The JS engine in Narwhal will generate the function `function anonymous(){//}`
  176. * and throw a syntax error.
  177. *
  178. * Avoid comments beginning `@` symbols in IE because they are part of its
  179. * non-standard conditional compilation support.
  180. * http://msdn.microsoft.com/en-us/library/121hztk3(v=vs.94).aspx
  181. */
  182. try {
  183. var useSourceURL = (Function('//@')(), !window.attachEvent);
  184. } catch(e){ }
  185. /** Used to identify object classifications that are array-like */
  186. var arrayLikeClasses = {};
  187. arrayLikeClasses[boolClass] = arrayLikeClasses[dateClass] = arrayLikeClasses[funcClass] =
  188. arrayLikeClasses[numberClass] = arrayLikeClasses[objectClass] = arrayLikeClasses[regexpClass] = false;
  189. arrayLikeClasses[argsClass] = arrayLikeClasses[arrayClass] = arrayLikeClasses[stringClass] = true;
  190. /** Used to identify object classifications that `_.clone` supports */
  191. var cloneableClasses = {};
  192. cloneableClasses[argsClass] = cloneableClasses[funcClass] = false;
  193. cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] =
  194. cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] =
  195. cloneableClasses[stringClass] = true;
  196. /**
  197. * Used to convert characters to HTML entities:
  198. *
  199. * Though the `>` character is escaped for symmetry, characters like `>` and `/`
  200. * don't require escaping in HTML and have no special meaning unless they're part
  201. * of a tag or an unquoted attribute value.
  202. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
  203. */
  204. var htmlEscapes = {
  205. '&': '&amp;',
  206. '<': '&lt;',
  207. '>': '&gt;',
  208. '"': '&quot;',
  209. "'": '&#x27;'
  210. };
  211. /** Used to convert HTML entities to characters */
  212. var htmlUnescapes = {
  213. '&amp;': '&',
  214. '&lt;': '<',
  215. '&gt;': '>',
  216. '&quot;': '"',
  217. '&#x27;': "'"
  218. };
  219. /** Used to determine if values are of the language type Object */
  220. var objectTypes = {
  221. 'boolean': false,
  222. 'function': true,
  223. 'object': true,
  224. 'number': false,
  225. 'string': false,
  226. 'undefined': false,
  227. 'unknown': true
  228. };
  229. /** Used to escape characters for inclusion in compiled string literals */
  230. var stringEscapes = {
  231. '\\': '\\',
  232. "'": "'",
  233. '\n': 'n',
  234. '\r': 'r',
  235. '\t': 't',
  236. '\u2028': 'u2028',
  237. '\u2029': 'u2029'
  238. };
  239. /*--------------------------------------------------------------------------*/
  240. /**
  241. * The `lodash` function.
  242. *
  243. * @name _
  244. * @constructor
  245. * @param {Mixed} value The value to wrap in a `LoDash` instance.
  246. * @returns {Object} Returns a `LoDash` instance.
  247. */
  248. function lodash(value) {
  249. // allow invoking `lodash` without the `new` operator
  250. return new LoDash(value);
  251. }
  252. /**
  253. * Creates a `LoDash` instance that wraps a value to allow chaining.
  254. *
  255. * @private
  256. * @constructor
  257. * @param {Mixed} value The value to wrap.
  258. */
  259. function LoDash(value) {
  260. // exit early if already wrapped
  261. if (value && value.__wrapped__) {
  262. return value;
  263. }
  264. this.__wrapped__ = value;
  265. }
  266. /**
  267. * By default, the template delimiters used by Lo-Dash are similar to those in
  268. * embedded Ruby (ERB). Change the following template settings to use alternative
  269. * delimiters.
  270. *
  271. * @static
  272. * @memberOf _
  273. * @type Object
  274. */
  275. lodash.templateSettings = {
  276. /**
  277. * Used to detect `data` property values to be HTML-escaped.
  278. *
  279. * @static
  280. * @memberOf _.templateSettings
  281. * @type RegExp
  282. */
  283. 'escape': /<%-([\s\S]+?)%>/g,
  284. /**
  285. * Used to detect code to be evaluated.
  286. *
  287. * @static
  288. * @memberOf _.templateSettings
  289. * @type RegExp
  290. */
  291. 'evaluate': /<%([\s\S]+?)%>/g,
  292. /**
  293. * Used to detect `data` property values to inject.
  294. *
  295. * @static
  296. * @memberOf _.templateSettings
  297. * @type RegExp
  298. */
  299. 'interpolate': /<%=([\s\S]+?)%>/g,
  300. /**
  301. * Used to reference the data object in the template text.
  302. *
  303. * @static
  304. * @memberOf _.templateSettings
  305. * @type String
  306. */
  307. 'variable': ''
  308. };
  309. /*--------------------------------------------------------------------------*/
  310. /**
  311. * The template used to create iterator functions.
  312. *
  313. * @private
  314. * @param {Obect} data The data object used to populate the text.
  315. * @returns {String} Returns the interpolated text.
  316. */
  317. var iteratorTemplate = template(
  318. // conditional strict mode
  319. '<% if (useStrict) { %>\'use strict\';\n<% } %>' +
  320. // the `iteratee` may be reassigned by the `top` snippet
  321. 'var index, value, iteratee = <%= firstArg %>, ' +
  322. // assign the `result` variable an initial value
  323. 'result<% if (init) { %> = <%= init %><% } %>;\n' +
  324. // add code to exit early or do so if the first argument is falsey
  325. '<%= exit %>;\n' +
  326. // add code after the exit snippet but before the iteration branches
  327. '<%= top %>;\n' +
  328. // the following branch is for iterating arrays and array-like objects
  329. '<% if (arrayBranch) { %>' +
  330. 'var length = iteratee.length; index = -1;' +
  331. ' <% if (objectBranch) { %>\nif (length > -1 && length === length >>> 0) {<% } %>' +
  332. // add support for accessing string characters by index if needed
  333. ' <% if (noCharByIndex) { %>\n' +
  334. ' if (toString.call(iteratee) == stringClass) {\n' +
  335. ' iteratee = iteratee.split(\'\')\n' +
  336. ' }' +
  337. ' <% } %>\n' +
  338. ' <%= arrayBranch.beforeLoop %>;\n' +
  339. ' while (++index < length) {\n' +
  340. ' value = iteratee[index];\n' +
  341. ' <%= arrayBranch.inLoop %>\n' +
  342. ' }' +
  343. ' <% if (objectBranch) { %>\n}<% } %>' +
  344. '<% } %>' +
  345. // the following branch is for iterating an object's own/inherited properties
  346. '<% if (objectBranch) { %>' +
  347. ' <% if (arrayBranch) { %>\nelse {' +
  348. // add support for iterating over `arguments` objects if needed
  349. ' <% } else if (noArgsEnum) { %>\n' +
  350. ' var length = iteratee.length; index = -1;\n' +
  351. ' if (length && isArguments(iteratee)) {\n' +
  352. ' while (++index < length) {\n' +
  353. ' value = iteratee[index += \'\'];\n' +
  354. ' <%= objectBranch.inLoop %>\n' +
  355. ' }\n' +
  356. ' } else {' +
  357. ' <% } %>' +
  358. // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
  359. // (if the prototype or a property on the prototype has been set)
  360. // incorrectly sets a function's `prototype` property [[Enumerable]]
  361. // value to `true`. Because of this Lo-Dash standardizes on skipping
  362. // the the `prototype` property of functions regardless of its
  363. // [[Enumerable]] value.
  364. ' <% if (!hasDontEnumBug) { %>\n' +
  365. ' var skipProto = typeof iteratee == \'function\' && \n' +
  366. ' propertyIsEnumerable.call(iteratee, \'prototype\');\n' +
  367. ' <% } %>' +
  368. // iterate own properties using `Object.keys` if it's fast
  369. ' <% if (isKeysFast && useHas) { %>\n' +
  370. ' var ownIndex = -1,\n' +
  371. ' ownProps = objectTypes[typeof iteratee] ? nativeKeys(iteratee) : [],\n' +
  372. ' length = ownProps.length;\n\n' +
  373. ' <%= objectBranch.beforeLoop %>;\n' +
  374. ' while (++ownIndex < length) {\n' +
  375. ' index = ownProps[ownIndex];\n' +
  376. ' <% if (!hasDontEnumBug) { %>if (!(skipProto && index == \'prototype\')) {\n <% } %>' +
  377. ' value = iteratee[index];\n' +
  378. ' <%= objectBranch.inLoop %>\n' +
  379. ' <% if (!hasDontEnumBug) { %>}\n<% } %>' +
  380. ' }' +
  381. // else using a for-in loop
  382. ' <% } else { %>\n' +
  383. ' <%= objectBranch.beforeLoop %>;\n' +
  384. ' for (index in iteratee) {' +
  385. ' <% if (!hasDontEnumBug || useHas) { %>\n if (<%' +
  386. ' if (!hasDontEnumBug) { %>!(skipProto && index == \'prototype\')<% }' +
  387. ' if (!hasDontEnumBug && useHas) { %> && <% }' +
  388. ' if (useHas) { %>hasOwnProperty.call(iteratee, index)<% }' +
  389. ' %>) {' +
  390. ' <% } %>\n' +
  391. ' value = iteratee[index];\n' +
  392. ' <%= objectBranch.inLoop %>;\n' +
  393. ' <% if (!hasDontEnumBug || useHas) { %>}\n<% } %>' +
  394. ' }' +
  395. ' <% } %>' +
  396. // Because IE < 9 can't set the `[[Enumerable]]` attribute of an
  397. // existing property and the `constructor` property of a prototype
  398. // defaults to non-enumerable, Lo-Dash skips the `constructor`
  399. // property when it infers it's iterating over a `prototype` object.
  400. ' <% if (hasDontEnumBug) { %>\n\n' +
  401. ' var ctor = iteratee.constructor;\n' +
  402. ' <% for (var k = 0; k < 7; k++) { %>\n' +
  403. ' index = \'<%= shadowed[k] %>\';\n' +
  404. ' if (<%' +
  405. ' if (shadowed[k] == \'constructor\') {' +
  406. ' %>!(ctor && ctor.prototype === iteratee) && <%' +
  407. ' } %>hasOwnProperty.call(iteratee, index)) {\n' +
  408. ' value = iteratee[index];\n' +
  409. ' <%= objectBranch.inLoop %>\n' +
  410. ' }' +
  411. ' <% } %>' +
  412. ' <% } %>' +
  413. ' <% if (arrayBranch || noArgsEnum) { %>\n}<% } %>' +
  414. '<% } %>\n' +
  415. // add code to the bottom of the iteration function
  416. '<%= bottom %>;\n' +
  417. // finally, return the `result`
  418. 'return result'
  419. );
  420. /**
  421. * Reusable iterator options shared by
  422. * `every`, `filter`, `find`, `forEach`, `forIn`, `forOwn`, `groupBy`, `map`,
  423. * `reject`, `some`, and `sortBy`.
  424. */
  425. var baseIteratorOptions = {
  426. 'args': 'collection, callback, thisArg',
  427. 'init': 'collection',
  428. 'top':
  429. 'if (!callback) {\n' +
  430. ' callback = identity\n' +
  431. '}\n' +
  432. 'else if (thisArg) {\n' +
  433. ' callback = iteratorBind(callback, thisArg)\n' +
  434. '}',
  435. 'inLoop': 'if (callback(value, index, collection) === false) return result'
  436. };
  437. /** Reusable iterator options for `countBy`, `groupBy`, and `sortBy` */
  438. var countByIteratorOptions = {
  439. 'init': '{}',
  440. 'top':
  441. 'var prop;\n' +
  442. 'if (typeof callback != \'function\') {\n' +
  443. ' var valueProp = callback;\n' +
  444. ' callback = function(value) { return value[valueProp] }\n' +
  445. '}\n' +
  446. 'else if (thisArg) {\n' +
  447. ' callback = iteratorBind(callback, thisArg)\n' +
  448. '}',
  449. 'inLoop':
  450. 'prop = callback(value, index, collection);\n' +
  451. '(hasOwnProperty.call(result, prop) ? result[prop]++ : result[prop] = 1)'
  452. };
  453. /** Reusable iterator options for `every` and `some` */
  454. var everyIteratorOptions = {
  455. 'init': 'true',
  456. 'inLoop': 'if (!callback(value, index, collection)) return !result'
  457. };
  458. /** Reusable iterator options for `defaults` and `extend` */
  459. var extendIteratorOptions = {
  460. 'useHas': false,
  461. 'useStrict': false,
  462. 'args': 'object',
  463. 'init': 'object',
  464. 'top':
  465. 'for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {\n' +
  466. ' if (iteratee = arguments[argsIndex]) {',
  467. 'inLoop': 'result[index] = value',
  468. 'bottom': ' }\n}'
  469. };
  470. /** Reusable iterator options for `filter`, `reject`, and `where` */
  471. var filterIteratorOptions = {
  472. 'init': '[]',
  473. 'inLoop': 'callback(value, index, collection) && result.push(value)'
  474. };
  475. /** Reusable iterator options for `find`, `forEach`, `forIn`, and `forOwn` */
  476. var forEachIteratorOptions = {
  477. 'top': 'if (thisArg) callback = iteratorBind(callback, thisArg)'
  478. };
  479. /** Reusable iterator options for `forIn` and `forOwn` */
  480. var forOwnIteratorOptions = {
  481. 'inLoop': {
  482. 'object': baseIteratorOptions.inLoop
  483. }
  484. };
  485. /** Reusable iterator options for `invoke`, `map`, `pluck`, and `sortBy` */
  486. var mapIteratorOptions = {
  487. 'init': '',
  488. 'exit': 'if (!collection) return []',
  489. 'beforeLoop': {
  490. 'array': 'result = Array(length)',
  491. 'object': 'result = ' + (isKeysFast ? 'Array(length)' : '[]')
  492. },
  493. 'inLoop': {
  494. 'array': 'result[index] = callback(value, index, collection)',
  495. 'object': 'result' + (isKeysFast ? '[ownIndex] = ' : '.push') + '(callback(value, index, collection))'
  496. }
  497. };
  498. /** Reusable iterator options for `omit` and `pick` */
  499. var omitIteratorOptions = {
  500. 'useHas': false,
  501. 'args': 'object, callback, thisArg',
  502. 'init': '{}',
  503. 'top':
  504. 'var isFunc = typeof callback == \'function\';\n' +
  505. 'if (!isFunc) {\n' +
  506. ' var props = concat.apply(ArrayProto, arguments)\n' +
  507. '} else if (thisArg) {\n' +
  508. ' callback = iteratorBind(callback, thisArg)\n' +
  509. '}',
  510. 'inLoop':
  511. 'if (isFunc\n' +
  512. ' ? !callback(value, index, object)\n' +
  513. ' : indexOf(props, index) < 0\n' +
  514. ') result[index] = value'
  515. };
  516. /*--------------------------------------------------------------------------*/
  517. /**
  518. * Creates a new function optimized for searching large arrays for a given `value`,
  519. * starting at `fromIndex`, using strict equality for comparisons, i.e. `===`.
  520. *
  521. * @private
  522. * @param {Array} array The array to search.
  523. * @param {Mixed} value The value to search for.
  524. * @param {Number} [fromIndex=0] The index to start searching from.
  525. * @param {Number} [largeSize=30] The length at which an array is considered large.
  526. * @returns {Boolean} Returns `true` if `value` is found, else `false`.
  527. */
  528. function cachedContains(array, fromIndex, largeSize) {
  529. fromIndex || (fromIndex = 0);
  530. var length = array.length,
  531. isLarge = (length - fromIndex) >= (largeSize || largeArraySize),
  532. cache = isLarge ? {} : array;
  533. if (isLarge) {
  534. // init value cache
  535. var key,
  536. index = fromIndex - 1;
  537. while (++index < length) {
  538. // manually coerce `value` to string because `hasOwnProperty`, in some
  539. // older versions of Firefox, coerces objects incorrectly
  540. key = array[index] + '';
  541. (hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = [])).push(array[index]);
  542. }
  543. }
  544. return function(value) {
  545. if (isLarge) {
  546. var key = value + '';
  547. return hasOwnProperty.call(cache, key) && indexOf(cache[key], value) > -1;
  548. }
  549. return indexOf(cache, value, fromIndex) > -1;
  550. }
  551. }
  552. /**
  553. * Creates compiled iteration functions. The iteration function will be created
  554. * to iterate over only objects if the first argument of `options.args` is
  555. * "object" or `options.inLoop.array` is falsey.
  556. *
  557. * @private
  558. * @param {Object} [options1, options2, ...] The compile options objects.
  559. *
  560. * useHas - A boolean to specify whether or not to use `hasOwnProperty` checks
  561. * in the object loop.
  562. *
  563. * useStrict - A boolean to specify whether or not to include the ES5
  564. * "use strict" directive.
  565. *
  566. * args - A string of comma separated arguments the iteration function will
  567. * accept.
  568. *
  569. * init - A string to specify the initial value of the `result` variable.
  570. *
  571. * exit - A string of code to use in place of the default exit-early check
  572. * of `if (!arguments[0]) return result`.
  573. *
  574. * top - A string of code to execute after the exit-early check but before
  575. * the iteration branches.
  576. *
  577. * beforeLoop - A string or object containing an "array" or "object" property
  578. * of code to execute before the array or object loops.
  579. *
  580. * inLoop - A string or object containing an "array" or "object" property
  581. * of code to execute in the array or object loops.
  582. *
  583. * bottom - A string of code to execute after the iteration branches but
  584. * before the `result` is returned.
  585. *
  586. * @returns {Function} Returns the compiled function.
  587. */
  588. function createIterator() {
  589. var object,
  590. prop,
  591. value,
  592. index = -1,
  593. length = arguments.length;
  594. // merge options into a template data object
  595. var data = {
  596. 'bottom': '',
  597. 'exit': '',
  598. 'init': '',
  599. 'top': '',
  600. 'arrayBranch': { 'beforeLoop': '' },
  601. 'objectBranch': { 'beforeLoop': '' }
  602. };
  603. while (++index < length) {
  604. object = arguments[index];
  605. for (prop in object) {
  606. value = (value = object[prop]) == null ? '' : value;
  607. // keep this regexp explicit for the build pre-process
  608. if (/beforeLoop|inLoop/.test(prop)) {
  609. if (typeof value == 'string') {
  610. value = { 'array': value, 'object': value };
  611. }
  612. data.arrayBranch[prop] = value.array || '';
  613. data.objectBranch[prop] = value.object || '';
  614. } else {
  615. data[prop] = value;
  616. }
  617. }
  618. }
  619. // set additional template `data` values
  620. var args = data.args,
  621. firstArg = /^[^,]+/.exec(args)[0],
  622. useStrict = data.useStrict;
  623. data.firstArg = firstArg;
  624. data.hasDontEnumBug = hasDontEnumBug;
  625. data.isKeysFast = isKeysFast;
  626. data.noArgsEnum = noArgsEnum;
  627. data.shadowed = shadowed;
  628. data.useHas = data.useHas !== false;
  629. data.useStrict = useStrict == null ? isStrictFast : useStrict;
  630. if (data.noCharByIndex == null) {
  631. data.noCharByIndex = noCharByIndex;
  632. }
  633. if (!data.exit) {
  634. data.exit = 'if (!' + firstArg + ') return result';
  635. }
  636. if (firstArg != 'collection' || !data.arrayBranch.inLoop) {
  637. data.arrayBranch = null;
  638. }
  639. // create the function factory
  640. var factory = Function(
  641. 'arrayLikeClasses, ArrayProto, bind, compareAscending, concat, forIn, ' +
  642. 'hasOwnProperty, identity, indexOf, isArguments, isArray, isFunction, ' +
  643. 'isPlainObject, iteratorBind, objectClass, objectTypes, nativeKeys, ' +
  644. 'propertyIsEnumerable, slice, stringClass, toString',
  645. 'var callee = function(' + args + ') {\n' + iteratorTemplate(data) + '\n};\n' +
  646. 'return callee'
  647. );
  648. // return the compiled function
  649. return factory(
  650. arrayLikeClasses, ArrayProto, bind, compareAscending, concat, forIn,
  651. hasOwnProperty, identity, indexOf, isArguments, isArray, isFunction,
  652. isPlainObject, iteratorBind, objectClass, objectTypes, nativeKeys,
  653. propertyIsEnumerable, slice, stringClass, toString
  654. );
  655. }
  656. /**
  657. * Used by `sortBy` to compare transformed `collection` values, stable sorting
  658. * them in ascending order.
  659. *
  660. * @private
  661. * @param {Object} a The object to compare to `b`.
  662. * @param {Object} b The object to compare to `a`.
  663. * @returns {Number} Returns the sort order indicator of `1` or `-1`.
  664. */
  665. function compareAscending(a, b) {
  666. var ai = a.index,
  667. bi = b.index;
  668. a = a.criteria;
  669. b = b.criteria;
  670. if (a === undefined) {
  671. return 1;
  672. }
  673. if (b === undefined) {
  674. return -1;
  675. }
  676. // ensure a stable sort in V8 and other engines
  677. // http://code.google.com/p/v8/issues/detail?id=90
  678. return a < b ? -1 : a > b ? 1 : ai < bi ? -1 : 1;
  679. }
  680. /**
  681. * Used by `template` to replace tokens with their corresponding code snippets.
  682. *
  683. * @private
  684. * @param {String} match The matched token.
  685. * @param {String} index The `tokenized` index of the code snippet.
  686. * @returns {String} Returns the code snippet.
  687. */
  688. function detokenize(match, index) {
  689. return tokenized[index];
  690. }
  691. /**
  692. * Used by `template` to escape characters for inclusion in compiled
  693. * string literals.
  694. *
  695. * @private
  696. * @param {String} match The matched character to escape.
  697. * @returns {String} Returns the escaped character.
  698. */
  699. function escapeStringChar(match) {
  700. return '\\' + stringEscapes[match];
  701. }
  702. /**
  703. * Used by `escape` to convert characters to HTML entities.
  704. *
  705. * @private
  706. * @param {String} match The matched character to escape.
  707. * @returns {String} Returns the escaped character.
  708. */
  709. function escapeHtmlChar(match) {
  710. return htmlEscapes[match];
  711. }
  712. /**
  713. * Creates a new function that, when called, invokes `func` with the `this`
  714. * binding of `thisArg` and the arguments (value, index, object).
  715. *
  716. * @private
  717. * @param {Function} func The function to bind.
  718. * @param {Mixed} [thisArg] The `this` binding of `func`.
  719. * @returns {Function} Returns the new bound function.
  720. */
  721. function iteratorBind(func, thisArg) {
  722. return function(value, index, object) {
  723. return func.call(thisArg, value, index, object);
  724. };
  725. }
  726. /**
  727. * A no-operation function.
  728. *
  729. * @private
  730. */
  731. function noop() {
  732. // no operation performed
  733. }
  734. /**
  735. * Used by `template` to replace "escape" template delimiters with tokens.
  736. *
  737. * @private
  738. * @param {String} match The matched template delimiter.
  739. * @param {String} value The delimiter value.
  740. * @returns {String} Returns a token.
  741. */
  742. function tokenizeEscape(match, value) {
  743. if (match && reComplexDelimiter.test(value)) {
  744. return '<e%-' + value + '%>';
  745. }
  746. var index = tokenized.length;
  747. tokenized[index] = "' +\n__e(" + value + ") +\n'";
  748. return tokenHead + index + tokenFoot;
  749. }
  750. /**
  751. * Used by `template` to replace "evaluate" template delimiters, or complex
  752. * "escape" and "interpolate" delimiters, with tokens.
  753. *
  754. * @private
  755. * @param {String} match The matched template delimiter.
  756. * @param {String} escapeValue The complex "escape" delimiter value.
  757. * @param {String} interpolateValue The complex "interpolate" delimiter value.
  758. * @param {String} [evaluateValue] The "evaluate" delimiter value.
  759. * @returns {String} Returns a token.
  760. */
  761. function tokenizeEvaluate(match, escapeValue, interpolateValue, evaluateValue) {
  762. if (evaluateValue) {
  763. var index = tokenized.length;
  764. tokenized[index] = "';\n" + evaluateValue + ";\n__p += '";
  765. return tokenHead + index + tokenFoot;
  766. }
  767. return escapeValue
  768. ? tokenizeEscape(null, escapeValue)
  769. : tokenizeInterpolate(null, interpolateValue);
  770. }
  771. /**
  772. * Used by `template` to replace "interpolate" template delimiters with tokens.
  773. *
  774. * @private
  775. * @param {String} match The matched template delimiter.
  776. * @param {String} value The delimiter value.
  777. * @returns {String} Returns a token.
  778. */
  779. function tokenizeInterpolate(match, value) {
  780. if (match && reComplexDelimiter.test(value)) {
  781. return '<e%=' + value + '%>';
  782. }
  783. var index = tokenized.length;
  784. tokenized[index] = "' +\n((__t = (" + value + ")) == null ? '' : __t) +\n'";
  785. return tokenHead + index + tokenFoot;
  786. }
  787. /**
  788. * Used by `unescape` to convert HTML entities to characters.
  789. *
  790. * @private
  791. * @param {String} match The matched character to unescape.
  792. * @returns {String} Returns the unescaped character.
  793. */
  794. function unescapeHtmlChar(match) {
  795. return htmlUnescapes[match];
  796. }
  797. /*--------------------------------------------------------------------------*/
  798. /**
  799. * Checks if `value` is an `arguments` object.
  800. *
  801. * @static
  802. * @memberOf _
  803. * @category Objects
  804. * @param {Mixed} value The value to check.
  805. * @returns {Boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
  806. * @example
  807. *
  808. * (function() { return _.isArguments(arguments); })(1, 2, 3);
  809. * // => true
  810. *
  811. * _.isArguments([1, 2, 3]);
  812. * // => false
  813. */
  814. function isArguments(value) {
  815. return toString.call(value) == argsClass;
  816. }
  817. // fallback for browsers that can't detect `arguments` objects by [[Class]]
  818. if (noArgsClass) {
  819. isArguments = function(value) {
  820. return !!(value && hasOwnProperty.call(value, 'callee'));
  821. };
  822. }
  823. /**
  824. * Checks if `value` is an array.
  825. *
  826. * @static
  827. * @memberOf _
  828. * @category Objects
  829. * @param {Mixed} value The value to check.
  830. * @returns {Boolean} Returns `true` if the `value` is an array, else `false`.
  831. * @example
  832. *
  833. * (function() { return _.isArray(arguments); })();
  834. * // => false
  835. *
  836. * _.isArray([1, 2, 3]);
  837. * // => true
  838. */
  839. var isArray = nativeIsArray || function(value) {
  840. return toString.call(value) == arrayClass;
  841. };
  842. /**
  843. * Checks if `value` is a function.
  844. *
  845. * @static
  846. * @memberOf _
  847. * @category Objects
  848. * @param {Mixed} value The value to check.
  849. * @returns {Boolean} Returns `true` if the `value` is a function, else `false`.
  850. * @example
  851. *
  852. * _.isFunction(''.concat);
  853. * // => true
  854. */
  855. function isFunction(value) {
  856. return typeof value == 'function';
  857. }
  858. // fallback for older versions of Chrome and Safari
  859. if (isFunction(/x/)) {
  860. isFunction = function(value) {
  861. return toString.call(value) == funcClass;
  862. };
  863. }
  864. /**
  865. * A fallback implementation of `isPlainObject`.
  866. *
  867. * @private
  868. * @param {Mixed} value The value to check.
  869. * @param {Boolean} [skipArgsCheck=false] Internally used to skip checks for
  870. * `arguments` objects.
  871. * @returns {Boolean} Returns `true` if the `value` is a plain `Object` object,
  872. * else `false`.
  873. */
  874. function isPlainFallback(value, skipArgsCheck) {
  875. // avoid non-objects and false positives for `arguments` objects
  876. var result = false;
  877. if (!(value && typeof value == 'object') || (!skipArgsCheck && isArguments(value))) {
  878. return result;
  879. }
  880. // IE < 9 presents DOM nodes as `Object` objects except they have `toString`
  881. // methods that are `typeof` "string" and still can coerce nodes to strings.
  882. // Also check that the constructor is `Object` (i.e. `Object instanceof Object`)
  883. var ctor = value.constructor;
  884. if ((!noNodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) &&
  885. (!isFunction(ctor) || ctor instanceof ctor)) {
  886. // IE < 9 iterates inherited properties before own properties. If the first
  887. // iterated property is an object's own property then there are no inherited
  888. // enumerable properties.
  889. if (iteratesOwnLast) {
  890. forIn(value, function(objValue, objKey) {
  891. result = !hasOwnProperty.call(value, objKey);
  892. return false;
  893. });
  894. return result === false;
  895. }
  896. // In most environments an object's own properties are iterated before
  897. // its inherited properties. If the last iterated property is an object's
  898. // own property then there are no inherited enumerable properties.
  899. forIn(value, function(objValue, objKey) {
  900. result = objKey;
  901. });
  902. return result === false || hasOwnProperty.call(value, result);
  903. }
  904. return result;
  905. }
  906. /**
  907. * Checks if a given `value` is an object created by the `Object` constructor
  908. * assuming objects created by the `Object` constructor have no inherited
  909. * enumerable properties and that there are no `Object.prototype` extensions.
  910. *
  911. * @private
  912. * @param {Mixed} value The value to check.
  913. * @param {Boolean} [skipArgsCheck=false] Internally used to skip checks for
  914. * `arguments` objects.
  915. * @returns {Boolean} Returns `true` if the `value` is a plain `Object` object,
  916. * else `false`.
  917. */
  918. var isPlainObject = objectTypes.__proto__ != ObjectProto ? isPlainFallback : function(value, skipArgsCheck) {
  919. if (!value) {
  920. return false;
  921. }
  922. var valueOf = value.valueOf,
  923. objProto = typeof valueOf == 'function' && valueOf.__proto__.__proto__;
  924. return objProto
  925. ? value == objProto || (value.__proto__ == objProto && (skipArgsCheck || !isArguments(value)))
  926. : isPlainFallback(value);
  927. };
  928. /**
  929. * A shim implementation of `Object.keys` that produces an array of the given
  930. * object's own enumerable property names.
  931. *
  932. * @private
  933. * @param {Object} object The object to inspect.
  934. * @returns {Array} Returns a new array of property names.
  935. */
  936. var shimKeys = createIterator({
  937. 'args': 'object',
  938. 'init': '[]',
  939. 'inLoop': 'result.push(index)'
  940. });
  941. /*--------------------------------------------------------------------------*/
  942. /**
  943. * Creates a clone of `value`. If `deep` is `true`, all nested objects will
  944. * also be cloned otherwise they will be assigned by reference. If a value has
  945. * a `clone` method it will be used to perform the clone. Functions, DOM nodes,
  946. * `arguments` objects, and objects created by constructors other than `Object`
  947. * are **not** cloned unless they have a custom `clone` method.
  948. *
  949. * @static
  950. * @memberOf _
  951. * @category Objects
  952. * @param {Mixed} value The value to clone.
  953. * @param {Boolean} deep A flag to indicate a deep clone.
  954. * @param {Object} [guard] Internally used to allow this method to work with
  955. * others like `_.map` without using their callback `index` argument for `deep`.
  956. * @param {Array} [stack=[]] Internally used to keep track of traversed objects
  957. * to avoid circular references.
  958. * @param {Object} thorough Internally used to indicate whether or not to perform
  959. * a more thorough clone of non-object values.
  960. * @returns {Mixed} Returns the cloned `value`.
  961. * @example
  962. *
  963. * var stooges = [
  964. * { 'name': 'moe', 'age': 40 },
  965. * { 'name': 'larry', 'age': 50 },
  966. * { 'name': 'curly', 'age': 60 }
  967. * ];
  968. *
  969. * _.clone({ 'name': 'moe' });
  970. * // => { 'name': 'moe' }
  971. *
  972. * var shallow = _.clone(stooges);
  973. * shallow[0] === stooges[0];
  974. * // => true
  975. *
  976. * var deep = _.clone(stooges, true);
  977. * shallow[0] === stooges[0];
  978. * // => false
  979. */
  980. function clone(value, deep, guard, stack, thorough) {
  981. if (value == null) {
  982. return value;
  983. }
  984. if (guard) {
  985. deep = false;
  986. }
  987. // avoid slower checks on primitives
  988. thorough || (thorough = { 'value': null });
  989. if (thorough.value == null) {
  990. // primitives passed from iframes use the primary document's native prototypes
  991. thorough.value = !!(BoolProto.clone || NumberProto.clone || StringProto.clone);
  992. }
  993. // use custom `clone` method if available
  994. var isObj = objectTypes[typeof value];
  995. if ((isObj || thorough.value) && value.clone && isFunction(value.clone)) {
  996. thorough.value = null;
  997. return value.clone(deep);
  998. }
  999. // inspect [[Class]]
  1000. if (isObj) {
  1001. // don't clone `arguments` objects, functions, or non-object Objects
  1002. var className = toString.call(value);
  1003. if (!cloneableClasses[className] || (noArgsClass && isArguments(value))) {
  1004. return value;
  1005. }
  1006. var isArr = className == arrayClass;
  1007. isObj = isArr || (className == objectClass ? isPlainObject(value, true) : isObj);
  1008. }
  1009. // shallow clone
  1010. if (!isObj || !deep) {
  1011. // don't clone functions
  1012. return isObj
  1013. ? (isArr ? slice.call(value) : extend({}, value))
  1014. : value;
  1015. }
  1016. var ctor = value.constructor;
  1017. switch (className) {
  1018. case boolClass:
  1019. return new ctor(value == true);
  1020. case dateClass:
  1021. return new ctor(+value);
  1022. case numberClass:
  1023. case stringClass:
  1024. return new ctor(value);
  1025. case regexpClass:
  1026. return ctor(value.source, reFlags.exec(value));
  1027. }
  1028. // check for circular references and return corresponding clone
  1029. stack || (stack = []);
  1030. var length = stack.length;
  1031. while (length--) {
  1032. if (stack[length].source == value) {
  1033. return stack[length].value;
  1034. }
  1035. }
  1036. // init cloned object
  1037. length = value.length;
  1038. var result = isArr ? ctor(length) : {};
  1039. // add current clone and original source value to the stack of traversed objects
  1040. stack.push({ 'value': result, 'source': value });
  1041. // recursively populate clone (susceptible to call stack limits)
  1042. if (isArr) {
  1043. var index = -1;
  1044. while (++index < length) {
  1045. result[index] = clone(value[index], deep, null, stack, thorough);
  1046. }
  1047. } else {
  1048. forOwn(value, function(objValue, key) {
  1049. result[key] = clone(objValue, deep, null, stack, thorough);
  1050. });
  1051. }
  1052. return result;
  1053. }
  1054. /**
  1055. * Assigns enumerable properties of the default object(s) to the `destination`
  1056. * object for all `destination` properties that resolve to `null`/`undefined`.
  1057. * Once a property is set, additional defaults of the same property will be
  1058. * ignored.
  1059. *
  1060. * @static
  1061. * @memberOf _
  1062. * @category Objects
  1063. * @param {Object} object The destination object.
  1064. * @param {Object} [default1, default2, ...] The default objects.
  1065. * @returns {Object} Returns the destination object.
  1066. * @example
  1067. *
  1068. * var iceCream = { 'flavor': 'chocolate' };
  1069. * _.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' });
  1070. * // => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' }
  1071. */
  1072. var defaults = createIterator(extendIteratorOptions, {
  1073. 'inLoop': 'if (result[index] == null) ' + extendIteratorOptions.inLoop
  1074. });
  1075. /**
  1076. * Assigns enumerable properties of the source object(s) to the `destination`
  1077. * object. Subsequent sources will overwrite propery assignments of previous
  1078. * sources.
  1079. *
  1080. * @static
  1081. * @memberOf _
  1082. * @category Objects
  1083. * @param {Object} object The destination object.
  1084. * @param {Object} [source1, source2, ...] The source objects.
  1085. * @returns {Object} Returns the destination object.
  1086. * @example
  1087. *
  1088. * _.extend({ 'name': 'moe' }, { 'age': 40 });
  1089. * // => { 'name': 'moe', 'age': 40 }
  1090. */
  1091. var extend = createIterator(extendIteratorOptions);
  1092. /**
  1093. * Iterates over `object`'s own and inherited enumerable properties, executing
  1094. * the `callback` for each property. The `callback` is bound to `thisArg` and
  1095. * invoked with 3 arguments; (value, key, object). Callbacks may exit iteration
  1096. * early by explicitly returning `false`.
  1097. *
  1098. * @static
  1099. * @memberOf _
  1100. * @category Objects
  1101. * @param {Object} object The object to iterate over.
  1102. * @param {Function} callback The function called per iteration.
  1103. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1104. * @returns {Object} Returns `object`.
  1105. * @example
  1106. *
  1107. * function Dog(name) {
  1108. * this.name = name;
  1109. * }
  1110. *
  1111. * Dog.prototype.bark = function() {
  1112. * alert('Woof, woof!');
  1113. * };
  1114. *
  1115. * _.forIn(new Dog('Dagny'), function(value, key) {
  1116. * alert(key);
  1117. * });
  1118. * // => alerts 'name' and 'bark' (order is not guaranteed)
  1119. */
  1120. var forIn = createIterator(baseIteratorOptions, forEachIteratorOptions, forOwnIteratorOptions, {
  1121. 'useHas': false
  1122. });
  1123. /**
  1124. * Iterates over `object`'s own enumerable properties, executing the `callback`
  1125. * for each property. The `callback` is bound to `thisArg` and invoked with 3
  1126. * arguments; (value, key, object). Callbacks may exit iteration early by
  1127. * explicitly returning `false`.
  1128. *
  1129. * @static
  1130. * @memberOf _
  1131. * @category Objects
  1132. * @param {Object} object The object to iterate over.
  1133. * @param {Function} callback The function called per iteration.
  1134. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1135. * @returns {Object} Returns `object`.
  1136. * @example
  1137. *
  1138. * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
  1139. * alert(key);
  1140. * });
  1141. * // => alerts '0', '1', and 'length' (order is not guaranteed)
  1142. */
  1143. var forOwn = createIterator(baseIteratorOptions, forEachIteratorOptions, forOwnIteratorOptions);
  1144. /**
  1145. * Creates a sorted array of all enumerable properties, own and inherited,
  1146. * of `object` that have function values.
  1147. *
  1148. * @static
  1149. * @memberOf _
  1150. * @alias methods
  1151. * @category Objects
  1152. * @param {Object} object The object to inspect.
  1153. * @returns {Array} Returns a new array of property names that have function values.
  1154. * @example
  1155. *
  1156. * _.functions(_);
  1157. * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
  1158. */
  1159. var functions = createIterator({
  1160. 'useHas': false,
  1161. 'args': 'object',
  1162. 'init': '[]',
  1163. 'inLoop': 'if (isFunction(value)) result.push(index)',
  1164. 'bottom': 'result.sort()'
  1165. });
  1166. /**
  1167. * Checks if the specified object `property` exists and is a direct property,
  1168. * instead of an inherited property.
  1169. *
  1170. * @static
  1171. * @memberOf _
  1172. * @category Objects
  1173. * @param {Object} object The object to check.
  1174. * @param {String} property The property to check for.
  1175. * @returns {Boolean} Returns `true` if key is a direct property, else `false`.
  1176. * @example
  1177. *
  1178. * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
  1179. * // => true
  1180. */
  1181. function has(object, property) {
  1182. return object ? hasOwnProperty.call(object, property) : false;
  1183. }
  1184. /**
  1185. * Invert the keys and values of an object. The values must be serializable.
  1186. *
  1187. * @static
  1188. * @memberOf _
  1189. * @alias methods
  1190. * @category Objects
  1191. * @param {Object} object The object to inspect.
  1192. * @returns {Array} Returns a new array of property names that have function values.
  1193. * @example
  1194. *
  1195. * var obj = {first: 'Moe', second: 'Larry', third: 'Curly'}
  1196. * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
  1197. */
  1198. var invert = createIterator({
  1199. 'args': 'object',
  1200. 'init': '{}',
  1201. 'inLoop': 'result[value] = index'
  1202. });
  1203. /**
  1204. * Checks if `value` is a boolean (`true` or `false`) value.
  1205. *
  1206. * @static
  1207. * @memberOf _
  1208. * @category Objects
  1209. * @param {Mixed} value The value to check.
  1210. * @returns {Boolean} Returns `true` if the `value` is a boolean value, else `false`.
  1211. * @example
  1212. *
  1213. * _.isBoolean(null);
  1214. * // => false
  1215. */
  1216. function isBoolean(value) {
  1217. return value === true || value === false || toString.call(value) == boolClass;
  1218. }
  1219. /**
  1220. * Checks if `value` is a date.
  1221. *
  1222. * @static
  1223. * @memberOf _
  1224. * @category Objects
  1225. * @param {Mixed} value The value to check.
  1226. * @returns {Boolean} Returns `true` if the `value` is a date, else `false`.
  1227. * @example
  1228. *
  1229. * _.isDate(new Date);
  1230. * // => true
  1231. */
  1232. function isDate(value) {
  1233. return toString.call(value) == dateClass;
  1234. }
  1235. /**
  1236. * Checks if `value` is a DOM element.
  1237. *
  1238. * @static
  1239. * @memberOf _
  1240. * @category Objects
  1241. * @param {Mixed} value The value to check.
  1242. * @returns {Boolean} Returns `true` if the `value` is a DOM element, else `false`.
  1243. * @example
  1244. *
  1245. * _.isElement(document.body);
  1246. * // => true
  1247. */
  1248. function isElement(value) {
  1249. return value ? value.nodeType === 1 : false;
  1250. }
  1251. /**
  1252. * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
  1253. * length of `0` and objects with no own enumerable properties are considered
  1254. * "empty".
  1255. *
  1256. * @static
  1257. * @memberOf _
  1258. * @category Objects
  1259. * @param {Array|Object|String} value The value to inspect.
  1260. * @returns {Boolean} Returns `true` if the `value` is empty, else `false`.
  1261. * @example
  1262. *
  1263. * _.isEmpty([1, 2, 3]);
  1264. * // => false
  1265. *
  1266. * _.isEmpty({});
  1267. * // => true
  1268. *
  1269. * _.isEmpty('');
  1270. * // => true
  1271. */
  1272. var isEmpty = createIterator({
  1273. 'args': 'value',
  1274. 'init': 'true',
  1275. 'top':
  1276. 'var className = toString.call(value),\n' +
  1277. ' length = value.length;\n' +
  1278. 'if (arrayLikeClasses[className]' +
  1279. (noArgsClass ? ' || isArguments(value)' : '') + ' ||\n' +
  1280. ' (className == objectClass && length > -1 && length === length >>> 0 &&\n' +
  1281. ' isFunction(value.splice))' +
  1282. ') return !length',
  1283. 'inLoop': {
  1284. 'object': 'return false'
  1285. }
  1286. });
  1287. /**
  1288. * Performs a deep comparison between two values to determine if they are
  1289. * equivalent to each other. If a value has an `isEqual` method it will be
  1290. * used to perform the comparison.
  1291. *
  1292. * @static
  1293. * @memberOf _
  1294. * @category Objects
  1295. * @param {Mixed} a The value to compare.
  1296. * @param {Mixed} b The other value to compare.
  1297. * @param {Array} [stack=[]] Internally used to keep track of traversed objects
  1298. * to avoid circular references.
  1299. * @param {Object} thorough Internally used to indicate whether or not to perform
  1300. * a more thorough comparison of non-object values.
  1301. * @returns {Boolean} Returns `true` if the values are equvalent, else `false`.
  1302. * @example
  1303. *
  1304. * var moe = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
  1305. * var clone = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
  1306. *
  1307. * moe == clone;
  1308. * // => false
  1309. *
  1310. * _.isEqual(moe, clone);
  1311. * // => true
  1312. */
  1313. function isEqual(a, b, stack, thorough) {
  1314. // a strict comparison is necessary because `null == undefined`
  1315. if (a == null || b == null) {
  1316. return a === b;
  1317. }
  1318. // avoid slower checks on non-objects
  1319. thorough || (thorough = { 'value': null });
  1320. if (thorough.value == null) {
  1321. // primitives passed from iframes use the primary document's native prototypes
  1322. thorough.value = !!(BoolProto.isEqual || NumberProto.isEqual || StringProto.isEqual);
  1323. }
  1324. if (objectTypes[typeof a] || objectTypes[typeof b] || thorough.value) {
  1325. // unwrap any LoDash wrapped values
  1326. a = a.__wrapped__ || a;
  1327. b = b.__wrapped__ || b;
  1328. // use custom `isEqual` method if available
  1329. if (a.isEqual && isFunction(a.isEqual)) {
  1330. thorough.value = null;
  1331. return a.isEqual(b);
  1332. }
  1333. if (b.isEqual && isFunction(b.isEqual)) {
  1334. thorough.value = null;
  1335. return b.isEqual(a);
  1336. }
  1337. }
  1338. // exit early for identical values
  1339. if (a === b) {
  1340. // treat `+0` vs. `-0` as not equal
  1341. return a !== 0 || (1 / a == 1 / b);
  1342. }
  1343. // compare [[Class]] names
  1344. var className = toString.call(a);
  1345. if (className != toString.call(b)) {
  1346. return false;
  1347. }
  1348. switch (className) {
  1349. case boolClass:
  1350. case dateClass:
  1351. // coerce dates and booleans to numbers, dates to milliseconds and booleans
  1352. // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
  1353. return +a == +b;
  1354. case numberClass:
  1355. // treat `NaN` vs. `NaN` as equal
  1356. return a != +a
  1357. ? b != +b
  1358. // but treat `+0` vs. `-0` as not equal
  1359. : (a == 0 ? (1 / a == 1 / b) : a == +b);
  1360. case regexpClass:
  1361. case stringClass:
  1362. // coerce regexes to strings (http://es5.github.com/#x15.10.6.4)
  1363. // treat string primitives and their corresponding object instances as equal
  1364. return a == b + '';
  1365. }
  1366. // exit early, in older browsers, if `a` is array-like but not `b`
  1367. var isArr = arrayLikeClasses[className];
  1368. if (noArgsClass && !isArr && (isArr = isArguments(a)) && !isArguments(b)) {
  1369. return false;
  1370. }
  1371. // exit for functions and DOM nodes
  1372. if (!isArr && (className != objectClass || (noNodeClass && (
  1373. (typeof a.toString != 'function' && typeof (a + '') == 'string') ||
  1374. (typeof b.toString != 'function' && typeof (b + '') == 'string'))))) {
  1375. return false;
  1376. }
  1377. // assume cyclic structures are equal
  1378. // the algorithm for detecting cyclic structures is adapted from ES 5.1
  1379. // section 15.12.3, abstract operation `JO` (http://es5.github.com/#x15.12.3)
  1380. stack || (stack = []);
  1381. var length = stack.length;
  1382. while (length--) {
  1383. if (stack[length] == a) {
  1384. return true;
  1385. }
  1386. }
  1387. var index = -1,
  1388. result = true,
  1389. size = 0;
  1390. // add `a` to the stack of traversed objects
  1391. stack.push(a);
  1392. // recursively compare objects and arrays (susceptible to call stack limits)
  1393. if (isArr) {
  1394. // compare lengths to determine if a deep comparison is necessary
  1395. size = a.length;
  1396. result = size == b.length;
  1397. if (result) {
  1398. // deep compare the contents, ignoring non-numeric properties
  1399. while (size--) {
  1400. if (!(result = isEqual(a[size], b[size], stack, thorough))) {
  1401. break;
  1402. }
  1403. }
  1404. }
  1405. return result;
  1406. }
  1407. var ctorA = a.constructor,
  1408. ctorB = b.constructor;
  1409. // non `Object` object instances with different constructors are not equal
  1410. if (ctorA != ctorB && !(
  1411. isFunction(ctorA) && ctorA instanceof ctorA &&
  1412. isFunction(ctorB) && ctorB instanceof ctorB
  1413. )) {
  1414. return false;
  1415. }
  1416. // deep compare objects
  1417. for (var prop in a) {
  1418. if (hasOwnProperty.call(a, prop)) {
  1419. // count the number of properties.
  1420. size++;
  1421. // deep compare each property value.
  1422. if (!(hasOwnProperty.call(b, prop) && isEqual(a[prop], b[prop], stack, thorough))) {
  1423. return false;
  1424. }
  1425. }
  1426. }
  1427. // ensure both objects have the same number of properties
  1428. for (prop in b) {
  1429. // The JS engine in Adobe products, like InDesign, has a bug that causes
  1430. // `!size--` to throw an error so it must be wrapped in parentheses.
  1431. // https://github.com/documentcloud/underscore/issues/355
  1432. if (hasOwnProperty.call(b, prop) && !(size--)) {
  1433. // `size` will be `-1` if `b` has more properties than `a`
  1434. return false;
  1435. }
  1436. }
  1437. // handle JScript [[DontEnum]] bug
  1438. if (hasDontEnumBug) {
  1439. while (++index < 7) {
  1440. prop = shadowed[index];
  1441. if (hasOwnProperty.call(a, prop) &&
  1442. !(hasOwnProperty.call(b, prop) && isEqual(a[prop], b[prop], stack, thorough))) {
  1443. return false;
  1444. }
  1445. }
  1446. }
  1447. return true;
  1448. }
  1449. /**
  1450. * Checks if `value` is a finite number.
  1451. *
  1452. * Note: This is not the same as native `isFinite`, which will return true for
  1453. * booleans and other values. See http://es5.github.com/#x15.1.2.5.
  1454. *
  1455. * @deprecated
  1456. * @static
  1457. * @memberOf _
  1458. * @category Objects
  1459. * @param {Mixed} value The value to check.
  1460. * @returns {Boolean} Returns `true` if the `value` is a finite number, else `false`.
  1461. * @example
  1462. *
  1463. * _.isFinite(-101);
  1464. * // => true
  1465. *
  1466. * _.isFinite('10');
  1467. * // => false
  1468. *
  1469. * _.isFinite(Infinity);
  1470. * // => false
  1471. */
  1472. function isFinite(value) {
  1473. return nativeIsFinite(value) && toString.call(value) == numberClass;
  1474. }
  1475. /**
  1476. * Checks if `value` is the language type of Object.
  1477. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  1478. *
  1479. * @static
  1480. * @memberOf _
  1481. * @category Objects
  1482. * @param {Mixed} value The value to check.
  1483. * @returns {Boolean} Returns `true` if the `value` is an object, else `false`.
  1484. * @example
  1485. *
  1486. * _.isObject({});
  1487. * // => true
  1488. *
  1489. * _.isObject(1);
  1490. * // => false
  1491. */
  1492. function isObject(value) {
  1493. // check if the value is the ECMAScript language type of Object
  1494. // http://es5.github.com/#x8
  1495. // and avoid a V8 bug
  1496. // http://code.google.com/p/v8/issues/detail?id=2291
  1497. return value ? objectTypes[typeof value] : false;
  1498. }
  1499. /**
  1500. * Checks if `value` is `NaN`.
  1501. *
  1502. * Note: This is not the same as native `isNaN`, which will return true for
  1503. * `undefined` and other values. See http://es5.github.com/#x15.1.2.4.
  1504. *
  1505. * @deprecated
  1506. * @static
  1507. * @memberOf _
  1508. * @category Objects
  1509. * @param {Mixed} value The value to check.
  1510. * @returns {Boolean} Returns `true` if the `value` is `NaN`, else `false`.
  1511. * @example
  1512. *
  1513. * _.isNaN(NaN);
  1514. * // => true
  1515. *
  1516. * _.isNaN(new Number(NaN));
  1517. * // => true
  1518. *
  1519. * isNaN(undefined);
  1520. * // => true
  1521. *
  1522. * _.isNaN(undefined);
  1523. * // => false
  1524. */
  1525. function isNaN(value) {
  1526. // `NaN` as a primitive is the only value that is not equal to itself
  1527. // (perform the [[Class]] check first to avoid errors with some host objects in IE)
  1528. return toString.call(value) == numberClass && value != +value
  1529. }
  1530. /**
  1531. * Checks if `value` is `null`.
  1532. *
  1533. * @deprecated
  1534. * @static
  1535. * @memberOf _
  1536. * @category Objects
  1537. * @param {Mixed} value The value to check.
  1538. * @returns {Boolean} Returns `true` if the `value` is `null`, else `false`.
  1539. * @example
  1540. *
  1541. * _.isNull(null);
  1542. * // => true
  1543. *
  1544. * _.isNull(undefined);
  1545. * // => false
  1546. */
  1547. function isNull(value) {
  1548. return value === null;
  1549. }
  1550. /**
  1551. * Checks if `value` is a number.
  1552. *
  1553. * @static
  1554. * @memberOf _
  1555. * @category Objects
  1556. * @param {Mixed} value The value to check.
  1557. * @returns {Boolean} Returns `true` if the `value` is a number, else `false`.
  1558. * @example
  1559. *
  1560. * _.isNumber(8.4 * 5;
  1561. * // => true
  1562. */
  1563. function isNumber(value) {
  1564. return toString.call(value) == numberClass;
  1565. }
  1566. /**
  1567. * Checks if `value` is a regular expression.
  1568. *
  1569. * @static
  1570. * @memberOf _
  1571. * @category Objects
  1572. * @param {Mixed} value The value to check.
  1573. * @returns {Boolean} Returns `true` if the `value` is a regular expression, else `false`.
  1574. * @example
  1575. *
  1576. * _.isRegExp(/moe/);
  1577. * // => true
  1578. */
  1579. function isRegExp(value) {
  1580. return toString.call(value) == regexpClass;
  1581. }
  1582. /**
  1583. * Checks if `value` is a string.
  1584. *
  1585. * @static
  1586. * @memberOf _
  1587. * @category Objects
  1588. * @param {Mixed} value The value to check.
  1589. * @returns {Boolean} Returns `true` if the `value` is a string, else `false`.
  1590. * @example
  1591. *
  1592. * _.isString('moe');
  1593. * // => true
  1594. */
  1595. function isString(value) {
  1596. return toString.call(value) == stringClass;
  1597. }
  1598. /**
  1599. * Checks if `value` is `undefined`.
  1600. *
  1601. * @deprecated
  1602. * @static
  1603. * @memberOf _
  1604. * @category Objects
  1605. * @param {Mixed} value The value to check.
  1606. * @returns {Boolean} Returns `true` if the `value` is `undefined`, else `false`.
  1607. * @example
  1608. *
  1609. * _.isUndefined(void 0);
  1610. * // => true
  1611. */
  1612. function isUndefined(value) {
  1613. return value === undefined;
  1614. }
  1615. /**
  1616. * Creates an array composed of the own enumerable property names of `object`.
  1617. *
  1618. * @static
  1619. * @memberOf _
  1620. * @category Objects
  1621. * @param {Object} object The object to inspect.
  1622. * @returns {Array} Returns a new array of property names.
  1623. * @example
  1624. *
  1625. * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
  1626. * // => ['one', 'two', 'three'] (order is not guaranteed)
  1627. */
  1628. var keys = !nativeKeys ? shimKeys : function(object) {
  1629. var type = typeof object;
  1630. // avoid iterating over the `prototype` property
  1631. if (type == 'function' && propertyIsEnumerable.call(object, 'prototype')) {
  1632. return shimKeys(object);
  1633. }
  1634. return object && objectTypes[type]
  1635. ? nativeKeys(object)
  1636. : [];
  1637. };
  1638. /**
  1639. * Merges enumerable properties of the source object(s) into the `destination`
  1640. * object. Subsequent sources will overwrite propery assignments of previous
  1641. * sources.
  1642. *
  1643. * @static
  1644. * @memberOf _
  1645. * @category Objects
  1646. * @param {Object} object The destination object.
  1647. * @param {Object} [source1, source2, ...] The source objects.
  1648. * @param {Object} [indicator] Internally used to indicate that the `stack`
  1649. * argument is an array of traversed objects instead of another source object.
  1650. * @param {Array} [stack=[]] Internally used to keep track of traversed objects
  1651. * to avoid circular references.
  1652. * @returns {Object} Returns the destination object.
  1653. * @example
  1654. *
  1655. * var stooges = [
  1656. * { 'name': 'moe' },
  1657. * { 'name': 'larry' }
  1658. * ];
  1659. *
  1660. * var ages = [
  1661. * { 'age': 40 },
  1662. * { 'age': 50 }
  1663. * ];
  1664. *
  1665. * _.merge(stooges, ages);
  1666. * // => [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }]
  1667. */
  1668. var merge = createIterator(extendIteratorOptions, {
  1669. 'args': 'object, source, indicator, stack',
  1670. 'top':
  1671. 'var destValue, found, isArr, stackLength, recursive = indicator == isPlainObject;\n' +
  1672. 'if (!recursive) stack = [];\n' +
  1673. 'for (var argsIndex = 1, argsLength = recursive ? 2 : arguments.length; argsIndex < argsLength; argsIndex++) {\n' +
  1674. ' if (iteratee = arguments[argsIndex]) {',
  1675. 'inLoop':
  1676. 'if (value && ((isArr = isArray(value)) || isPlainObject(value))) {\n' +
  1677. ' found = false; stackLength = stack.length;\n' +
  1678. ' while (stackLength--) {\n' +
  1679. ' if (found = stack[stackLength].source == value) break\n' +
  1680. ' }\n' +
  1681. ' if (found) {\n' +
  1682. ' result[index] = stack[stackLength].value\n' +
  1683. ' } else {\n' +
  1684. ' destValue = (destValue = result[index]) && isArr\n' +
  1685. ' ? (isArray(destValue) ? destValue : [])\n' +
  1686. ' : (isPlainObject(destValue) ? destValue : {});\n' +
  1687. ' stack.push({ value: destValue, source: value });\n' +
  1688. ' result[index] = callee(destValue, value, isPlainObject, stack)\n' +
  1689. ' }\n' +
  1690. '} else if (value != null) {\n' +
  1691. ' result[index] = value\n' +
  1692. '}'
  1693. });
  1694. /**
  1695. * Creates a shallow clone of `object` excluding the specified properties.
  1696. * Property names may be specified as individual arguments or as arrays of
  1697. * property names. If `callback` is passed, it will be executed for each property
  1698. * in the `object`, omitting the properties `callback` returns truthy for. The
  1699. * `callback` is bound to `thisArg` and invoked with 3 arguments; (value, key, object).
  1700. *
  1701. * @static
  1702. * @memberOf _
  1703. * @category Objects
  1704. * @param {Object} object The source object.
  1705. * @param {Function|String} callback|[prop1, prop2, ...] The properties to omit
  1706. * or the function called per iteration.
  1707. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1708. * @returns {Object} Returns an object without the omitted properties.
  1709. * @example
  1710. *
  1711. * _.omit({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'userid');
  1712. * // => { 'name': 'moe', 'age': 40 }
  1713. *
  1714. * _.omit({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) {
  1715. * return key.charAt(0) == '_';
  1716. * });
  1717. * // => { 'name': 'moe' }
  1718. */
  1719. var omit = createIterator(omitIteratorOptions);
  1720. /**
  1721. * Creates a two dimensional array of the given object's key-value pairs,
  1722. * i.e. `[[key1, value1], [key2, value2]]`.
  1723. *
  1724. * @static
  1725. * @memberOf _
  1726. * @category Objects
  1727. * @param {Object} object The object to inspect.
  1728. * @returns {Array} Returns new array of key-value pairs.
  1729. * @example
  1730. *
  1731. * _.pairs({ 'moe': 30, 'larry': 40, 'curly': 50 });
  1732. * // => [['moe', 30], ['larry', 40], ['curly', 50]] (order is not guaranteed)
  1733. */
  1734. var pairs = createIterator({
  1735. 'args': 'object',
  1736. 'init':'[]',
  1737. 'inLoop': 'result' + (isKeysFast ? '[ownIndex] = ' : '.push') + '([index, value])'
  1738. });
  1739. /**
  1740. * Creates a shallow clone of `object` composed of the specified properties.
  1741. * Property names may be specified as individual arguments or as arrays of
  1742. * property names. If `callback` is passed, it will be executed for each property
  1743. * in the `object`, picking the properties `callback` returns truthy for. The
  1744. * `callback` is bound to `thisArg` and invoked with 3 arguments; (value, key, object).
  1745. *
  1746. * @static
  1747. * @memberOf _
  1748. * @category Objects
  1749. * @param {Object} object The source object.
  1750. * @param {Function|String} callback|[prop1, prop2, ...] The properties to pick
  1751. * or the function called per iteration.
  1752. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1753. * @returns {Object} Returns an object composed of the picked properties.
  1754. * @example
  1755. *
  1756. * _.pick({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'name', 'age');
  1757. * // => { 'name': 'moe', 'age': 40 }
  1758. *
  1759. * _.pick({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) {
  1760. * return key.charAt(0) != '_';
  1761. * });
  1762. * // => { 'name': 'moe' }
  1763. */
  1764. var pick = createIterator(omitIteratorOptions, {
  1765. 'top':
  1766. 'if (typeof callback != \'function\') {\n' +
  1767. ' var prop,\n' +
  1768. ' props = concat.apply(ArrayProto, arguments),\n' +
  1769. ' length = props.length;\n' +
  1770. ' for (index = 1; index < length; index++) {\n' +
  1771. ' prop = props[index];\n' +
  1772. ' if (prop in object) result[prop] = object[prop]\n' +
  1773. ' }\n' +
  1774. '} else {\n' +
  1775. ' if (thisArg) callback = iteratorBind(callback, thisArg)',
  1776. 'inLoop':
  1777. 'if (callback(value, index, object)) result[index] = value',
  1778. 'bottom': '}'
  1779. });
  1780. /**
  1781. * Creates an array composed of the own enumerable property values of `object`.
  1782. *
  1783. * @static
  1784. * @memberOf _
  1785. * @category Objects
  1786. * @param {Object} object The object to inspect.
  1787. * @returns {Array} Returns a new array of property values.
  1788. * @example
  1789. *
  1790. * _.values({ 'one': 1, 'two': 2, 'three': 3 });
  1791. * // => [1, 2, 3]
  1792. */
  1793. var values = createIterator({
  1794. 'args': 'object',
  1795. 'init': '[]',
  1796. 'inLoop': 'result.push(value)'
  1797. });
  1798. /*--------------------------------------------------------------------------*/
  1799. /**
  1800. * Checks if a given `target` element is present in a `collection` using strict
  1801. * equality for comparisons, i.e. `===`.
  1802. *
  1803. * @static
  1804. * @memberOf _
  1805. * @alias include
  1806. * @category Collections
  1807. * @param {Array|Object|String} collection The collection to iterate over.
  1808. * @param {Mixed} target The value to check for.
  1809. * @returns {Boolean} Returns `true` if the `target` element is found, else `false`.
  1810. * @example
  1811. *
  1812. * _.contains([1, 2, 3], 3);
  1813. * // => true
  1814. *
  1815. * _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
  1816. * // => true
  1817. *
  1818. * _.contains('curly', 'ur');
  1819. * // => true
  1820. */
  1821. var contains = createIterator({
  1822. 'args': 'collection, target',
  1823. 'init': 'false',
  1824. 'noCharByIndex': false,
  1825. 'beforeLoop': {
  1826. 'array': 'if (toString.call(collection) == stringClass) return collection.indexOf(target) > -1'
  1827. },
  1828. 'inLoop': 'if (value === target) return true'
  1829. });
  1830. /**
  1831. * Creates an object composed of keys returned from running each element of
  1832. * `collection` through a `callback`. The corresponding value of each key is
  1833. * the number of times the key was returned by `callback`. The `callback` is
  1834. * bound to `thisArg` and invoked with 3 arguments; (value, index|key, collection).
  1835. * The `callback` argument may also be the name of a property to count by (e.g. 'length').
  1836. *
  1837. * @static
  1838. * @memberOf _
  1839. * @category Collections
  1840. * @param {Array|Object|String} collection The collection to iterate over.
  1841. * @param {Function|String} callback|property The function called per iteration
  1842. * or property name to count by.
  1843. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1844. * @returns {Object} Returns the composed aggregate object.
  1845. * @example
  1846. *
  1847. * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
  1848. * // => { '4': 1, '6': 2 }
  1849. *
  1850. * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  1851. * // => { '4': 1, '6': 2 }
  1852. *
  1853. * _.countBy(['one', 'two', 'three'], 'length');
  1854. * // => { '3': 2, '5': 1 }
  1855. */
  1856. var countBy = createIterator(baseIteratorOptions, countByIteratorOptions);
  1857. /**
  1858. * Checks if the `callback` returns a truthy value for **all** elements of a
  1859. * `collection`. The `callback` is bound to `thisArg` and invoked with 3
  1860. * arguments; (value, index|key, collection).
  1861. *
  1862. * @static
  1863. * @memberOf _
  1864. * @alias all
  1865. * @category Collections
  1866. * @param {Array|Object|String} collection The collection to iterate over.
  1867. * @param {Function} [callback=identity] The function called per iteration.
  1868. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1869. * @returns {Boolean} Returns `true` if all elements pass the callback check, else `false`.
  1870. * @example
  1871. *
  1872. * _.every([true, 1, null, 'yes'], Boolean);
  1873. * // => false
  1874. */
  1875. var every = createIterator(baseIteratorOptions, everyIteratorOptions);
  1876. /**
  1877. * Examines each element in a `collection`, returning an array of all elements
  1878. * the `callback` returns truthy for. The `callback` is bound to `thisArg` and
  1879. * invoked with 3 arguments; (value, index|key, collection).
  1880. *
  1881. * @static
  1882. * @memberOf _
  1883. * @alias select
  1884. * @category Collections
  1885. * @param {Array|Object|String} collection The collection to iterate over.
  1886. * @param {Function} [callback=identity] The function called per iteration.
  1887. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1888. * @returns {Array} Returns a new array of elements that passed callback check.
  1889. * @example
  1890. *
  1891. * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  1892. * // => [2, 4, 6]
  1893. */
  1894. var filter = createIterator(baseIteratorOptions, filterIteratorOptions);
  1895. /**
  1896. * Examines each element in a `collection`, returning the first one the `callback`
  1897. * returns truthy for. The function returns as soon as it finds an acceptable
  1898. * element, and does not iterate over the entire `collection`. The `callback` is
  1899. * bound to `thisArg` and invoked with 3 arguments; (value, index|key, collection).
  1900. *
  1901. * @static
  1902. * @memberOf _
  1903. * @alias detect
  1904. * @category Collections
  1905. * @param {Array|Object|String} collection The collection to iterate over.
  1906. * @param {Function} callback The function called per iteration.
  1907. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1908. * @returns {Mixed} Returns the element that passed the callback check, else `undefined`.
  1909. * @example
  1910. *
  1911. * var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  1912. * // => 2
  1913. */
  1914. var find = createIterator(baseIteratorOptions, forEachIteratorOptions, {
  1915. 'init': '',
  1916. 'inLoop': 'if (callback(value, index, collection)) return value'
  1917. });
  1918. /**
  1919. * Iterates over a `collection`, executing the `callback` for each element in
  1920. * the `collection`. The `callback` is bound to `thisArg` and invoked with 3
  1921. * arguments; (value, index|key, collection). Callbacks may exit iteration
  1922. * early by explicitly returning `false`.
  1923. *
  1924. * @static
  1925. * @memberOf _
  1926. * @alias each
  1927. * @category Collections
  1928. * @param {Array|Object|String} collection The collection to iterate over.
  1929. * @param {Function} callback The function called per iteration.
  1930. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1931. * @returns {Array|Object} Returns `collection`.
  1932. * @example
  1933. *
  1934. * _([1, 2, 3]).forEach(alert).join(',');
  1935. * // => alerts each number and returns '1,2,3'
  1936. *
  1937. * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
  1938. * // => alerts each number (order is not guaranteed)
  1939. */
  1940. var forEach = createIterator(baseIteratorOptions, forEachIteratorOptions);
  1941. /**
  1942. * Creates an object composed of keys returned from running each element of
  1943. * `collection` through a `callback`. The corresponding value of each key is an
  1944. * array of elements passed to `callback` that returned the key. The `callback`
  1945. * is bound to `thisArg` and invoked with 3 arguments; (value, index|key, collection).
  1946. * The `callback` argument may also be the name of a property to count by (e.g. 'length').
  1947. *
  1948. * @static
  1949. * @memberOf _
  1950. * @category Collections
  1951. * @param {Array|Object|String} collection The collection to iterate over.
  1952. * @param {Function|String} callback|property The function called per iteration
  1953. * or property name to group by.
  1954. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1955. * @returns {Object} Returns the composed aggregate object.
  1956. * @example
  1957. *
  1958. * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
  1959. * // => { '4': [4.2], '6': [6.1, 6.4] }
  1960. *
  1961. * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  1962. * // => { '4': [4.2], '6': [6.1, 6.4] }
  1963. *
  1964. * _.groupBy(['one', 'two', 'three'], 'length');
  1965. * // => { '3': ['one', 'two'], '5': ['three'] }
  1966. */
  1967. var groupBy = createIterator(baseIteratorOptions, countByIteratorOptions, {
  1968. 'inLoop':
  1969. 'prop = callback(value, index, collection);\n' +
  1970. '(hasOwnProperty.call(result, prop) ? result[prop] : result[prop] = []).push(value)'
  1971. });
  1972. /**
  1973. * Invokes the method named by `methodName` on each element in the `collection`.
  1974. * Additional arguments will be passed to each invoked method. If `methodName`
  1975. * is a function it will be invoked for, and `this` bound to, each element
  1976. * in the `collection`.
  1977. *
  1978. * @static
  1979. * @memberOf _
  1980. * @category Collections
  1981. * @param {Array|Object|String} collection The collection to iterate over.
  1982. * @param {Function|String} methodName The name of the method to invoke or
  1983. * the function invoked per iteration.
  1984. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
  1985. * @returns {Array} Returns a new array of values returned from each invoked method.
  1986. * @example
  1987. *
  1988. * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  1989. * // => [[1, 5, 7], [1, 2, 3]]
  1990. *
  1991. * _.invoke([123, 456], String.prototype.split, '');
  1992. * // => [['1', '2', '3'], ['4', '5', '6']]
  1993. */
  1994. var invoke = createIterator(mapIteratorOptions, {
  1995. 'args': 'collection, methodName',
  1996. 'top':
  1997. 'var args = slice.call(arguments, 2),\n' +
  1998. ' isFunc = typeof methodName == \'function\'',
  1999. 'inLoop': {
  2000. 'array':
  2001. 'result[index] = (isFunc ? methodName : value[methodName]).apply(value, args)',
  2002. 'object':
  2003. 'result' + (isKeysFast ? '[ownIndex] = ' : '.push') +
  2004. '((isFunc ? methodName : value[methodName]).apply(value, args))'
  2005. }
  2006. });
  2007. /**
  2008. * Creates a new array of values by running each element in the `collection`
  2009. * through a `callback`. The `callback` is bound to `thisArg` and invoked with
  2010. * 3 arguments; (value, index|key, collection).
  2011. *
  2012. * @static
  2013. * @memberOf _
  2014. * @alias collect
  2015. * @category Collections
  2016. * @param {Array|Object|String} collection The collection to iterate over.
  2017. * @param {Function} [callback=identity] The function called per iteration.
  2018. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2019. * @returns {Array} Returns a new array of elements returned by the callback.
  2020. * @example
  2021. *
  2022. * _.map([1, 2, 3], function(num) { return num * 3; });
  2023. * // => [3, 6, 9]
  2024. *
  2025. * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
  2026. * // => [3, 6, 9] (order is not guaranteed)
  2027. */
  2028. var map = createIterator(baseIteratorOptions, mapIteratorOptions);
  2029. /**
  2030. * Retrieves the value of a specified property from all elements in
  2031. * the `collection`.
  2032. *
  2033. * @static
  2034. * @memberOf _
  2035. * @category Collections
  2036. * @param {Array|Object|String} collection The collection to iterate over.
  2037. * @param {String} property The property to pluck.
  2038. * @returns {Array} Returns a new array of property values.
  2039. * @example
  2040. *
  2041. * var stooges = [
  2042. * { 'name': 'moe', 'age': 40 },
  2043. * { 'name': 'larry', 'age': 50 },
  2044. * { 'name': 'curly', 'age': 60 }
  2045. * ];
  2046. *
  2047. * _.pluck(stooges, 'name');
  2048. * // => ['moe', 'larry', 'curly']
  2049. */
  2050. var pluck = createIterator(mapIteratorOptions, {
  2051. 'args': 'collection, property',
  2052. 'inLoop': {
  2053. 'array': 'result[index] = value[property]',
  2054. 'object': 'result' + (isKeysFast ? '[ownIndex] = ' : '.push') + '(value[property])'
  2055. }
  2056. });
  2057. /**
  2058. * Boils down a `collection` to a single value. The initial state of the
  2059. * reduction is `accumulator` and each successive step of it should be returned
  2060. * by the `callback`. The `callback` is bound to `thisArg` and invoked with 4
  2061. * arguments; for arrays they are (accumulator, value, index|key, collection).
  2062. *
  2063. * @static
  2064. * @memberOf _
  2065. * @alias foldl, inject
  2066. * @category Collections
  2067. * @param {Array|Object|String} collection The collection to iterate over.
  2068. * @param {Function} callback The function called per iteration.
  2069. * @param {Mixed} [accumulator] Initial value of the accumulator.
  2070. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2071. * @returns {Mixed} Returns the accumulated value.
  2072. * @example
  2073. *
  2074. * var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; });
  2075. * // => 6
  2076. */
  2077. var reduce = createIterator({
  2078. 'args': 'collection, callback, accumulator, thisArg',
  2079. 'init': 'accumulator',
  2080. 'top':
  2081. 'var noaccum = arguments.length < 3;\n' +
  2082. 'if (thisArg) callback = iteratorBind(callback, thisArg)',
  2083. 'beforeLoop': {
  2084. 'array': 'if (noaccum) result = iteratee[++index]'
  2085. },
  2086. 'inLoop': {
  2087. 'array':
  2088. 'result = callback(result, value, index, collection)',
  2089. 'object':
  2090. 'result = noaccum\n' +
  2091. ' ? (noaccum = false, value)\n' +
  2092. ' : callback(result, value, index, collection)'
  2093. }
  2094. });
  2095. /**
  2096. * The right-associative version of `_.reduce`.
  2097. *
  2098. * @static
  2099. * @memberOf _
  2100. * @alias foldr
  2101. * @category Collections
  2102. * @param {Array|Object|String} collection The collection to iterate over.
  2103. * @param {Function} callback The function called per iteration.
  2104. * @param {Mixed} [accumulator] Initial value of the accumulator.
  2105. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2106. * @returns {Mixed} Returns the accumulated value.
  2107. * @example
  2108. *
  2109. * var list = [[0, 1], [2, 3], [4, 5]];
  2110. * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  2111. * // => [4, 5, 2, 3, 0, 1]
  2112. */
  2113. function reduceRight(collection, callback, accumulator, thisArg) {
  2114. if (!collection) {
  2115. return accumulator;
  2116. }
  2117. var length = collection.length,
  2118. noaccum = arguments.length < 3;
  2119. if(thisArg) {
  2120. callback = iteratorBind(callback, thisArg);
  2121. }
  2122. // Opera 10.53-10.60 JITted `length >>> 0` returns the wrong value for negative numbers
  2123. if (length > -1 && length === length >>> 0) {
  2124. var iteratee = noCharByIndex && toString.call(collection) == stringClass
  2125. ? collection.split('')
  2126. : collection;
  2127. if (length && noaccum) {
  2128. accumulator = iteratee[--length];
  2129. }
  2130. while (length--) {
  2131. accumulator = callback(accumulator, iteratee[length], length, collection);
  2132. }
  2133. return accumulator;
  2134. }
  2135. var prop,
  2136. props = keys(collection);
  2137. length = props.length;
  2138. if (length && noaccum) {
  2139. accumulator = collection[props[--length]];
  2140. }
  2141. while (length--) {
  2142. prop = props[length];
  2143. accumulator = callback(accumulator, collection[prop], prop, collection);
  2144. }
  2145. return accumulator;
  2146. }
  2147. /**
  2148. * The opposite of `_.filter`, this method returns the values of a
  2149. * `collection` that `callback` does **not** return truthy for.
  2150. *
  2151. * @static
  2152. * @memberOf _
  2153. * @category Collections
  2154. * @param {Array|Object|String} collection The collection to iterate over.
  2155. * @param {Function} [callback=identity] The function called per iteration.
  2156. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2157. * @returns {Array} Returns a new array of elements that did **not** pass the callback check.
  2158. * @example
  2159. *
  2160. * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  2161. * // => [1, 3, 5]
  2162. */
  2163. var reject = createIterator(baseIteratorOptions, filterIteratorOptions, {
  2164. 'inLoop': '!' + filterIteratorOptions.inLoop
  2165. });
  2166. /**
  2167. * Gets the size of the `collection` by returning `collection.length` for arrays
  2168. * and array-like objects or the number of own enumerable properties for objects.
  2169. *
  2170. * @static
  2171. * @memberOf _
  2172. * @category Collections
  2173. * @param {Array|Object|String} collection The collection to inspect.
  2174. * @returns {Number} Returns `collection.length` or number of own enumerable properties.
  2175. * @example
  2176. *
  2177. * _.size([1, 2]);
  2178. * // => 2
  2179. *
  2180. * _.size({ 'one': 1, 'two': 2, 'three': 3 });
  2181. * // => 3
  2182. *
  2183. * _.size('curly');
  2184. * // => 5
  2185. */
  2186. function size(collection) {
  2187. if (!collection) {
  2188. return 0;
  2189. }
  2190. var length = collection.length;
  2191. return length > -1 && length === length >>> 0 ? length : keys(collection).length;
  2192. }
  2193. /**
  2194. * Checks if the `callback` returns a truthy value for **any** element of a
  2195. * `collection`. The function returns as soon as it finds passing value, and
  2196. * does not iterate over the entire `collection`. The `callback` is bound to
  2197. * `thisArg` and invoked with 3 arguments; (value, index|key, collection).
  2198. *
  2199. * @static
  2200. * @memberOf _
  2201. * @alias any
  2202. * @category Collections
  2203. * @param {Array|Object|String} collection The collection to iterate over.
  2204. * @param {Function} [callback=identity] The function called per iteration.
  2205. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2206. * @returns {Boolean} Returns `true` if any element passes the callback check, else `false`.
  2207. * @example
  2208. *
  2209. * _.some([null, 0, 'yes', false]);
  2210. * // => true
  2211. */
  2212. var some = createIterator(baseIteratorOptions, everyIteratorOptions, {
  2213. 'init': 'false',
  2214. 'inLoop': everyIteratorOptions.inLoop.replace('!', '')
  2215. });
  2216. /**
  2217. * Creates a new array, stable sorted in ascending order by the results of
  2218. * running each element of `collection` through a `callback`. The `callback`
  2219. * is bound to `thisArg` and invoked with 3 arguments; (value, index|key, collection).
  2220. * The `callback` argument may also be the name of a property to sort by (e.g. 'length').
  2221. *
  2222. * @static
  2223. * @memberOf _
  2224. * @category Collections
  2225. * @param {Array|Object|String} collection The collection to iterate over.
  2226. * @param {Function|String} callback|property The function called per iteration
  2227. * or property name to sort by.
  2228. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2229. * @returns {Array} Returns a new array of sorted elements.
  2230. * @example
  2231. *
  2232. * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
  2233. * // => [3, 1, 2]
  2234. *
  2235. * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
  2236. * // => [3, 1, 2]
  2237. *
  2238. * _.sortBy(['larry', 'brendan', 'moe'], 'length');
  2239. * // => ['moe', 'larry', 'brendan']
  2240. */
  2241. var sortBy = createIterator(baseIteratorOptions, countByIteratorOptions, mapIteratorOptions, {
  2242. 'inLoop': {
  2243. 'array':
  2244. 'result[index] = {\n' +
  2245. ' criteria: callback(value, index, collection),\n' +
  2246. ' index: index,\n' +
  2247. ' value: value\n' +
  2248. '}',
  2249. 'object':
  2250. 'result' + (isKeysFast ? '[ownIndex] = ' : '.push') + '({\n' +
  2251. ' criteria: callback(value, index, collection),\n' +
  2252. ' index: index,\n' +
  2253. ' value: value\n' +
  2254. '})'
  2255. },
  2256. 'bottom':
  2257. 'result.sort(compareAscending);\n' +
  2258. 'length = result.length;\n' +
  2259. 'while (length--) {\n' +
  2260. ' result[length] = result[length].value\n' +
  2261. '}'
  2262. });
  2263. /**
  2264. * Converts the `collection`, to an array. Useful for converting the
  2265. * `arguments` object.
  2266. *
  2267. * @static
  2268. * @memberOf _
  2269. * @category Collections
  2270. * @param {Array|Object|String} collection The collection to convert.
  2271. * @returns {Array} Returns the new converted array.
  2272. * @example
  2273. *
  2274. * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
  2275. * // => [2, 3, 4]
  2276. */
  2277. function toArray(collection) {
  2278. if (!collection) {
  2279. return [];
  2280. }
  2281. if (collection.toArray && isFunction(collection.toArray)) {
  2282. return collection.toArray();
  2283. }
  2284. var length = collection.length;
  2285. if (length > -1 && length === length >>> 0) {
  2286. return (noArraySliceOnStrings ? toString.call(collection) == stringClass : typeof collection == 'string')
  2287. ? collection.split('')
  2288. : slice.call(collection);
  2289. }
  2290. return values(collection);
  2291. }
  2292. /**
  2293. * Examines each element in a `collection`, returning an array of all elements
  2294. * that contain the given `properties`.
  2295. *
  2296. * @static
  2297. * @memberOf _
  2298. * @category Collections
  2299. * @param {Array|Object|String} collection The collection to iterate over.
  2300. * @param {Object} properties The object of properties/values to filter by.
  2301. * @returns {Array} Returns a new array of elements that contain the given `properties`.
  2302. * @example
  2303. *
  2304. * var stooges = [
  2305. * { 'name': 'moe', 'age': 40 },
  2306. * { 'name': 'larry', 'age': 50 },
  2307. * { 'name': 'curly', 'age': 60 }
  2308. * ];
  2309. *
  2310. * _.where(stooges, { 'age': 40 });
  2311. * // => [{ 'name': 'moe', 'age': 40 }]
  2312. */
  2313. var where = createIterator(filterIteratorOptions, {
  2314. 'args': 'collection, properties',
  2315. 'top':
  2316. 'var props = [];\n' +
  2317. 'forIn(properties, function(value, prop) { props.push(prop) });\n' +
  2318. 'var propsLength = props.length',
  2319. 'inLoop':
  2320. 'for (var prop, pass = true, propIndex = 0; propIndex < propsLength; propIndex++) {\n' +
  2321. ' prop = props[propIndex];\n' +
  2322. ' if (!(pass = value[prop] === properties[prop])) break\n' +
  2323. '}\n' +
  2324. 'pass && result.push(value)'
  2325. });
  2326. /*--------------------------------------------------------------------------*/
  2327. /**
  2328. * Creates a new array with all falsey values of `array` removed. The values
  2329. * `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey.
  2330. *
  2331. * @static
  2332. * @memberOf _
  2333. * @category Arrays
  2334. * @param {Array} array The array to compact.
  2335. * @returns {Array} Returns a new filtered array.
  2336. * @example
  2337. *
  2338. * _.compact([0, 1, false, 2, '', 3]);
  2339. * // => [1, 2, 3]
  2340. */
  2341. function compact(array) {
  2342. var result = [];
  2343. if (!array) {
  2344. return result;
  2345. }
  2346. var index = -1,
  2347. length = array.length;
  2348. while (++index < length) {
  2349. if (array[index]) {
  2350. result.push(array[index]);
  2351. }
  2352. }
  2353. return result;
  2354. }
  2355. /**
  2356. * Creates a new array of `array` elements not present in the other arrays
  2357. * using strict equality for comparisons, i.e. `===`.
  2358. *
  2359. * @static
  2360. * @memberOf _
  2361. * @category Arrays
  2362. * @param {Array} array The array to process.
  2363. * @param {Array} [array1, array2, ...] Arrays to check.
  2364. * @returns {Array} Returns a new array of `array` elements not present in the
  2365. * other arrays.
  2366. * @example
  2367. *
  2368. * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
  2369. * // => [1, 3, 4]
  2370. */
  2371. function difference(array) {
  2372. var result = [];
  2373. if (!array) {
  2374. return result;
  2375. }
  2376. var index = -1,
  2377. length = array.length,
  2378. flattened = concat.apply(result, arguments),
  2379. contains = cachedContains(flattened, length);
  2380. while (++index < length) {
  2381. if (!contains(array[index])) {
  2382. result.push(array[index]);
  2383. }
  2384. }
  2385. return result;
  2386. }
  2387. /**
  2388. * Gets the first element of the `array`. Pass `n` to return the first `n`
  2389. * elements of the `array`.
  2390. *
  2391. * @static
  2392. * @memberOf _
  2393. * @alias head, take
  2394. * @category Arrays
  2395. * @param {Array} array The array to query.
  2396. * @param {Number} [n] The number of elements to return.
  2397. * @param {Object} [guard] Internally used to allow this method to work with
  2398. * others like `_.map` without using their callback `index` argument for `n`.
  2399. * @returns {Mixed} Returns the first element or an array of the first `n`
  2400. * elements of `array`.
  2401. * @example
  2402. *
  2403. * _.first([5, 4, 3, 2, 1]);
  2404. * // => 5
  2405. */
  2406. function first(array, n, guard) {
  2407. if (array) {
  2408. return (n == null || guard) ? array[0] : slice.call(array, 0, n);
  2409. }
  2410. }
  2411. /**
  2412. * Flattens a nested array (the nesting can be to any depth). If `shallow` is
  2413. * truthy, `array` will only be flattened a single level.
  2414. *
  2415. * @static
  2416. * @memberOf _
  2417. * @category Arrays
  2418. * @param {Array} array The array to compact.
  2419. * @param {Boolean} shallow A flag to indicate only flattening a single level.
  2420. * @returns {Array} Returns a new flattened array.
  2421. * @example
  2422. *
  2423. * _.flatten([1, [2], [3, [[4]]]]);
  2424. * // => [1, 2, 3, 4];
  2425. *
  2426. * _.flatten([1, [2], [3, [[4]]]], true);
  2427. * // => [1, 2, 3, [[4]]];
  2428. */
  2429. function flatten(array, shallow) {
  2430. var result = [];
  2431. if (!array) {
  2432. return result;
  2433. }
  2434. var value,
  2435. index = -1,
  2436. length = array.length;
  2437. while (++index < length) {
  2438. value = array[index];
  2439. if (isArray(value)) {
  2440. push.apply(result, shallow ? value : flatten(value));
  2441. } else {
  2442. result.push(value);
  2443. }
  2444. }
  2445. return result;
  2446. }
  2447. /**
  2448. * Gets the index at which the first occurrence of `value` is found using
  2449. * strict equality for comparisons, i.e. `===`. If the `array` is already
  2450. * sorted, passing `true` for `isSorted` will run a faster binary search.
  2451. *
  2452. * @static
  2453. * @memberOf _
  2454. * @category Arrays
  2455. * @param {Array} array The array to search.
  2456. * @param {Mixed} value The value to search for.
  2457. * @param {Boolean|Number} [fromIndex=0] The index to start searching from or
  2458. * `true` to perform a binary search on a sorted `array`.
  2459. * @returns {Number} Returns the index of the matched value or `-1`.
  2460. * @example
  2461. *
  2462. * _.indexOf([1, 2, 3, 1, 2, 3], 2);
  2463. * // => 1
  2464. *
  2465. * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
  2466. * // => 4
  2467. *
  2468. * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
  2469. * // => 2
  2470. */
  2471. function indexOf(array, value, fromIndex) {
  2472. if (!array) {
  2473. return -1;
  2474. }
  2475. var index = -1,
  2476. length = array.length;
  2477. if (fromIndex) {
  2478. if (typeof fromIndex == 'number') {
  2479. index = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) - 1;
  2480. } else {
  2481. index = sortedIndex(array, value);
  2482. return array[index] === value ? index : -1;
  2483. }
  2484. }
  2485. while (++index < length) {
  2486. if (array[index] === value) {
  2487. return index;
  2488. }
  2489. }
  2490. return -1;
  2491. }
  2492. /**
  2493. * Gets all but the last element of `array`. Pass `n` to exclude the last `n`
  2494. * elements from the result.
  2495. *
  2496. * @static
  2497. * @memberOf _
  2498. * @category Arrays
  2499. * @param {Array} array The array to query.
  2500. * @param {Number} [n] The number of elements to return.
  2501. * @param {Object} [guard] Internally used to allow this method to work with
  2502. * others like `_.map` without using their callback `index` argument for `n`.
  2503. * @returns {Array} Returns all but the last element or `n` elements of `array`.
  2504. * @example
  2505. *
  2506. * _.initial([3, 2, 1]);
  2507. * // => [3, 2]
  2508. */
  2509. function initial(array, n, guard) {
  2510. if (!array) {
  2511. return [];
  2512. }
  2513. return slice.call(array, 0, -((n == null || guard) ? 1 : n));
  2514. }
  2515. /**
  2516. * Computes the intersection of all the passed-in arrays using strict equality
  2517. * for comparisons, i.e. `===`.
  2518. *
  2519. * @static
  2520. * @memberOf _
  2521. * @category Arrays
  2522. * @param {Array} [array1, array2, ...] Arrays to process.
  2523. * @returns {Array} Returns a new array of unique elements, in order, that are
  2524. * present in **all** of the arrays.
  2525. * @example
  2526. *
  2527. * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  2528. * // => [1, 2]
  2529. */
  2530. function intersection(array) {
  2531. var result = [];
  2532. if (!array) {
  2533. return result;
  2534. }
  2535. var value,
  2536. argsLength = arguments.length,
  2537. cache = [],
  2538. index = -1,
  2539. length = array.length;
  2540. array: while (++index < length) {
  2541. value = array[index];
  2542. if (indexOf(result, value) < 0) {
  2543. for (var argsIndex = 1; argsIndex < argsLength; argsIndex++) {
  2544. if (!(cache[argsIndex] || (cache[argsIndex] = cachedContains(arguments[argsIndex])))(value)) {
  2545. continue array;
  2546. }
  2547. }
  2548. result.push(value);
  2549. }
  2550. }
  2551. return result;
  2552. }
  2553. /**
  2554. * Gets the last element of the `array`. Pass `n` to return the lasy `n`
  2555. * elementsvof the `array`.
  2556. *
  2557. * @static
  2558. * @memberOf _
  2559. * @category Arrays
  2560. * @param {Array} array The array to query.
  2561. * @param {Number} [n] The number of elements to return.
  2562. * @param {Object} [guard] Internally used to allow this method to work with
  2563. * others like `_.map` without using their callback `index` argument for `n`.
  2564. * @returns {Mixed} Returns the last element or an array of the last `n`
  2565. * elements of `array`.
  2566. * @example
  2567. *
  2568. * _.last([3, 2, 1]);
  2569. * // => 1
  2570. */
  2571. function last(array, n, guard) {
  2572. if (array) {
  2573. var length = array.length;
  2574. return (n == null || guard) ? array[length - 1] : slice.call(array, -n || length);
  2575. }
  2576. }
  2577. /**
  2578. * Gets the index at which the last occurrence of `value` is found using
  2579. * strict equality for comparisons, i.e. `===`.
  2580. *
  2581. * @static
  2582. * @memberOf _
  2583. * @category Arrays
  2584. * @param {Array} array The array to search.
  2585. * @param {Mixed} value The value to search for.
  2586. * @param {Number} [fromIndex=array.length-1] The index to start searching from.
  2587. * @returns {Number} Returns the index of the matched value or `-1`.
  2588. * @example
  2589. *
  2590. * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
  2591. * // => 4
  2592. *
  2593. * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
  2594. * // => 1
  2595. */
  2596. function lastIndexOf(array, value, fromIndex) {
  2597. if (!array) {
  2598. return -1;
  2599. }
  2600. var index = array.length;
  2601. if (fromIndex && typeof fromIndex == 'number') {
  2602. index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
  2603. }
  2604. while (index--) {
  2605. if (array[index] === value) {
  2606. return index;
  2607. }
  2608. }
  2609. return -1;
  2610. }
  2611. /**
  2612. * Retrieves the maximum value of an `array`. If `callback` is passed,
  2613. * it will be executed for each value in the `array` to generate the
  2614. * criterion by which the value is ranked. The `callback` is bound to
  2615. * `thisArg` and invoked with 3 arguments; (value, index, array).
  2616. *
  2617. * @static
  2618. * @memberOf _
  2619. * @category Arrays
  2620. * @param {Array} array The array to iterate over.
  2621. * @param {Function} [callback] The function called per iteration.
  2622. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2623. * @returns {Mixed} Returns the maximum value.
  2624. * @example
  2625. *
  2626. * var stooges = [
  2627. * { 'name': 'moe', 'age': 40 },
  2628. * { 'name': 'larry', 'age': 50 },
  2629. * { 'name': 'curly', 'age': 60 }
  2630. * ];
  2631. *
  2632. * _.max(stooges, function(stooge) { return stooge.age; });
  2633. * // => { 'name': 'curly', 'age': 60 };
  2634. */
  2635. function max(array, callback, thisArg) {
  2636. var computed = -Infinity,
  2637. result = computed;
  2638. if (!array) {
  2639. return result;
  2640. }
  2641. var current,
  2642. index = -1,
  2643. length = array.length;
  2644. if (!callback) {
  2645. while (++index < length) {
  2646. if (array[index] > result) {
  2647. result = array[index];
  2648. }
  2649. }
  2650. return result;
  2651. }
  2652. if (thisArg) {
  2653. callback = iteratorBind(callback, thisArg);
  2654. }
  2655. while (++index < length) {
  2656. current = callback(array[index], index, array);
  2657. if (current > computed) {
  2658. computed = current;
  2659. result = array[index];
  2660. }
  2661. }
  2662. return result;
  2663. }
  2664. /**
  2665. * Retrieves the minimum value of an `array`. If `callback` is passed,
  2666. * it will be executed for each value in the `array` to generate the
  2667. * criterion by which the value is ranked. The `callback` is bound to `thisArg`
  2668. * and invoked with 3 arguments; (value, index, array).
  2669. *
  2670. * @static
  2671. * @memberOf _
  2672. * @category Arrays
  2673. * @param {Array} array The array to iterate over.
  2674. * @param {Function} [callback] The function called per iteration.
  2675. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2676. * @returns {Mixed} Returns the minimum value.
  2677. * @example
  2678. *
  2679. * _.min([10, 5, 100, 2, 1000]);
  2680. * // => 2
  2681. */
  2682. function min(array, callback, thisArg) {
  2683. var computed = Infinity,
  2684. result = computed;
  2685. if (!array) {
  2686. return result;
  2687. }
  2688. var current,
  2689. index = -1,
  2690. length = array.length;
  2691. if (!callback) {
  2692. while (++index < length) {
  2693. if (array[index] < result) {
  2694. result = array[index];
  2695. }
  2696. }
  2697. return result;
  2698. }
  2699. if (thisArg) {
  2700. callback = iteratorBind(callback, thisArg);
  2701. }
  2702. while (++index < length) {
  2703. current = callback(array[index], index, array);
  2704. if (current < computed) {
  2705. computed = current;
  2706. result = array[index];
  2707. }
  2708. }
  2709. return result;
  2710. }
  2711. /**
  2712. * Creates an object composed from arrays of `keys` and `values`. Pass either
  2713. * a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or
  2714. * two arrays, one of `keys` and one of corresponding `values`.
  2715. *
  2716. * @static
  2717. * @memberOf _
  2718. * @category Arrays
  2719. * @param {Array} keys The array of keys.
  2720. * @param {Array} [values=[]] The array of values.
  2721. * @returns {Object} Returns an object composed of the given keys and
  2722. * corresponding values.
  2723. * @example
  2724. *
  2725. * _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
  2726. * // => { 'moe': 30, 'larry': 40, 'curly': 50 }
  2727. */
  2728. function object(keys, values) {
  2729. if (!keys) {
  2730. return {};
  2731. }
  2732. var index = -1,
  2733. length = keys.length,
  2734. result = {};
  2735. while (++index < length) {
  2736. if (values) {
  2737. result[keys[index]] = values[index];
  2738. } else {
  2739. result[keys[index][0]] = keys[index][1];
  2740. }
  2741. }
  2742. return result;
  2743. }
  2744. /**
  2745. * Creates an array of numbers (positive and/or negative) progressing from
  2746. * `start` up to but not including `stop`. This method is a port of Python's
  2747. * `range()` function. See http://docs.python.org/library/functions.html#range.
  2748. *
  2749. * @static
  2750. * @memberOf _
  2751. * @category Arrays
  2752. * @param {Number} [start=0] The start of the range.
  2753. * @param {Number} end The end of the range.
  2754. * @param {Number} [step=1] The value to increment or descrement by.
  2755. * @returns {Array} Returns a new range array.
  2756. * @example
  2757. *
  2758. * _.range(10);
  2759. * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  2760. *
  2761. * _.range(1, 11);
  2762. * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2763. *
  2764. * _.range(0, 30, 5);
  2765. * // => [0, 5, 10, 15, 20, 25]
  2766. *
  2767. * _.range(0, -10, -1);
  2768. * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  2769. *
  2770. * _.range(0);
  2771. * // => []
  2772. */
  2773. function range(start, end, step) {
  2774. start = +start || 0;
  2775. step = +step || 1;
  2776. if (end == null) {
  2777. end = start;
  2778. start = 0;
  2779. }
  2780. // use `Array(length)` so V8 will avoid the slower "dictionary" mode
  2781. // http://www.youtube.com/watch?v=XAqIpGU8ZZk#t=16m27s
  2782. var index = -1,
  2783. length = nativeMax(0, Math.ceil((end - start) / step)),
  2784. result = Array(length);
  2785. while (++index < length) {
  2786. result[index] = start;
  2787. start += step;
  2788. }
  2789. return result;
  2790. }
  2791. /**
  2792. * The opposite of `_.initial`, this method gets all but the first value of
  2793. * `array`. Pass `n` to exclude the first `n` values from the result.
  2794. *
  2795. * @static
  2796. * @memberOf _
  2797. * @alias drop, tail
  2798. * @category Arrays
  2799. * @param {Array} array The array to query.
  2800. * @param {Number} [n] The number of elements to return.
  2801. * @param {Object} [guard] Internally used to allow this method to work with
  2802. * others like `_.map` without using their callback `index` argument for `n`.
  2803. * @returns {Array} Returns all but the first value or `n` values of `array`.
  2804. * @example
  2805. *
  2806. * _.rest([3, 2, 1]);
  2807. * // => [2, 1]
  2808. */
  2809. function rest(array, n, guard) {
  2810. if (!array) {
  2811. return [];
  2812. }
  2813. return slice.call(array, (n == null || guard) ? 1 : n);
  2814. }
  2815. /**
  2816. * Creates a new array of shuffled `array` values, using a version of the
  2817. * Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
  2818. *
  2819. * @static
  2820. * @memberOf _
  2821. * @category Arrays
  2822. * @param {Array} array The array to shuffle.
  2823. * @returns {Array} Returns a new shuffled array.
  2824. * @example
  2825. *
  2826. * _.shuffle([1, 2, 3, 4, 5, 6]);
  2827. * // => [4, 1, 6, 3, 5, 2]
  2828. */
  2829. function shuffle(array) {
  2830. if (!array) {
  2831. return [];
  2832. }
  2833. var rand,
  2834. index = -1,
  2835. length = array.length,
  2836. result = Array(length);
  2837. while (++index < length) {
  2838. rand = nativeFloor(nativeRandom() * (index + 1));
  2839. result[index] = result[rand];
  2840. result[rand] = array[index];
  2841. }
  2842. return result;
  2843. }
  2844. /**
  2845. * Uses a binary search to determine the smallest index at which the `value`
  2846. * should be inserted into `array` in order to maintain the sort order of the
  2847. * sorted `array`. If `callback` is passed, it will be executed for `value` and
  2848. * each element in `array` to compute their sort ranking. The `callback` is
  2849. * bound to `thisArg` and invoked with 1 argument; (value).
  2850. *
  2851. * @static
  2852. * @memberOf _
  2853. * @category Arrays
  2854. * @param {Array} array The array to iterate over.
  2855. * @param {Mixed} value The value to evaluate.
  2856. * @param {Function} [callback=identity] The function called per iteration.
  2857. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2858. * @returns {Number} Returns the index at which the value should be inserted
  2859. * into `array`.
  2860. * @example
  2861. *
  2862. * _.sortedIndex([20, 30, 40], 35);
  2863. * // => 2
  2864. *
  2865. * var dict = {
  2866. * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'thirty-five': 35, 'fourty': 40 }
  2867. * };
  2868. *
  2869. * _.sortedIndex(['twenty', 'thirty', 'fourty'], 'thirty-five', function(word) {
  2870. * return dict.wordToNumber[word];
  2871. * });
  2872. * // => 2
  2873. *
  2874. * _.sortedIndex(['twenty', 'thirty', 'fourty'], 'thirty-five', function(word) {
  2875. * return this.wordToNumber[word];
  2876. * }, dict);
  2877. * // => 2
  2878. */
  2879. function sortedIndex(array, value, callback, thisArg) {
  2880. if (!array) {
  2881. return 0;
  2882. }
  2883. var mid,
  2884. low = 0,
  2885. high = array.length;
  2886. if (callback) {
  2887. if (thisArg) {
  2888. callback = bind(callback, thisArg);
  2889. }
  2890. value = callback(value);
  2891. while (low < high) {
  2892. mid = (low + high) >>> 1;
  2893. callback(array[mid]) < value ? low = mid + 1 : high = mid;
  2894. }
  2895. } else {
  2896. while (low < high) {
  2897. mid = (low + high) >>> 1;
  2898. array[mid] < value ? low = mid + 1 : high = mid;
  2899. }
  2900. }
  2901. return low;
  2902. }
  2903. /**
  2904. * Computes the union of the passed-in arrays using strict equality for
  2905. * comparisons, i.e. `===`.
  2906. *
  2907. * @static
  2908. * @memberOf _
  2909. * @category Arrays
  2910. * @param {Array} [array1, array2, ...] Arrays to process.
  2911. * @returns {Array} Returns a new array of unique values, in order, that are
  2912. * present in one or more of the arrays.
  2913. * @example
  2914. *
  2915. * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  2916. * // => [1, 2, 3, 101, 10]
  2917. */
  2918. function union() {
  2919. var index = -1,
  2920. result = [],
  2921. flattened = concat.apply(result, arguments),
  2922. length = flattened.length;
  2923. while (++index < length) {
  2924. if (indexOf(result, flattened[index]) < 0) {
  2925. result.push(flattened[index]);
  2926. }
  2927. }
  2928. return result;
  2929. }
  2930. /**
  2931. * Creates a duplicate-value-free version of the `array` using strict equality
  2932. * for comparisons, i.e. `===`. If the `array` is already sorted, passing `true`
  2933. * for `isSorted` will run a faster algorithm. If `callback` is passed, each
  2934. * element of `array` is passed through a callback` before uniqueness is computed.
  2935. * The `callback` is bound to `thisArg` and invoked with 3 arguments; (value, index, array).
  2936. *
  2937. * @static
  2938. * @memberOf _
  2939. * @alias unique
  2940. * @category Arrays
  2941. * @param {Array} array The array to process.
  2942. * @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted.
  2943. * @param {Function} [callback=identity] The function called per iteration.
  2944. * @param {Mixed} [thisArg] The `this` binding for the callback.
  2945. * @returns {Array} Returns a duplicate-value-free array.
  2946. * @example
  2947. *
  2948. * _.uniq([1, 2, 1, 3, 1]);
  2949. * // => [1, 2, 3]
  2950. *
  2951. * _.uniq([1, 1, 2, 2, 3], true);
  2952. * // => [1, 2, 3]
  2953. *
  2954. * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); });
  2955. * // => [1, 2, 3]
  2956. *
  2957. * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math);
  2958. * // => [1, 2, 3]
  2959. */
  2960. function uniq(array, isSorted, callback, thisArg) {
  2961. var result = [];
  2962. if (!array) {
  2963. return result;
  2964. }
  2965. var computed,
  2966. index = -1,
  2967. length = array.length,
  2968. seen = [];
  2969. // juggle arguments
  2970. if (typeof isSorted == 'function') {
  2971. thisArg = callback;
  2972. callback = isSorted;
  2973. isSorted = false;
  2974. }
  2975. if (!callback) {
  2976. callback = identity;
  2977. } else if (thisArg) {
  2978. callback = iteratorBind(callback, thisArg);
  2979. }
  2980. while (++index < length) {
  2981. computed = callback(array[index], index, array);
  2982. if (isSorted
  2983. ? !index || seen[seen.length - 1] !== computed
  2984. : indexOf(seen, computed) < 0
  2985. ) {
  2986. seen.push(computed);
  2987. result.push(array[index]);
  2988. }
  2989. }
  2990. return result;
  2991. }
  2992. /**
  2993. * Creates a new array with all occurrences of the passed values removed using
  2994. * strict equality for comparisons, i.e. `===`.
  2995. *
  2996. * @static
  2997. * @memberOf _
  2998. * @category Arrays
  2999. * @param {Array} array The array to filter.
  3000. * @param {Mixed} [value1, value2, ...] Values to remove.
  3001. * @returns {Array} Returns a new filtered array.
  3002. * @example
  3003. *
  3004. * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
  3005. * // => [2, 3, 4]
  3006. */
  3007. function without(array) {
  3008. var result = [];
  3009. if (!array) {
  3010. return result;
  3011. }
  3012. var index = -1,
  3013. length = array.length,
  3014. contains = cachedContains(arguments, 1, 20);
  3015. while (++index < length) {
  3016. if (!contains(array[index])) {
  3017. result.push(array[index]);
  3018. }
  3019. }
  3020. return result;
  3021. }
  3022. /**
  3023. * Groups the elements of each array at their corresponding indexes. Useful for
  3024. * separate data sources that are coordinated through matching array indexes.
  3025. * For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix
  3026. * in a similar fashion.
  3027. *
  3028. * @static
  3029. * @memberOf _
  3030. * @category Arrays
  3031. * @param {Array} [array1, array2, ...] Arrays to process.
  3032. * @returns {Array} Returns a new array of grouped elements.
  3033. * @example
  3034. *
  3035. * _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
  3036. * // => [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]]
  3037. */
  3038. function zip(array) {
  3039. if (!array) {
  3040. return [];
  3041. }
  3042. var index = -1,
  3043. length = max(pluck(arguments, 'length')),
  3044. result = Array(length);
  3045. while (++index < length) {
  3046. result[index] = pluck(arguments, index);
  3047. }
  3048. return result;
  3049. }
  3050. /*--------------------------------------------------------------------------*/
  3051. /**
  3052. * Creates a new function that is restricted to executing only after it is
  3053. * called `n` times.
  3054. *
  3055. * @static
  3056. * @memberOf _
  3057. * @category Functions
  3058. * @param {Number} n The number of times the function must be called before
  3059. * it is executed.
  3060. * @param {Function} func The function to restrict.
  3061. * @returns {Function} Returns the new restricted function.
  3062. * @example
  3063. *
  3064. * var renderNotes = _.after(notes.length, render);
  3065. * _.forEach(notes, function(note) {
  3066. * note.asyncSave({ 'success': renderNotes });
  3067. * });
  3068. * // `renderNotes` is run once, after all notes have saved
  3069. */
  3070. function after(n, func) {
  3071. if (n < 1) {
  3072. return func();
  3073. }
  3074. return function() {
  3075. if (--n < 1) {
  3076. return func.apply(this, arguments);
  3077. }
  3078. };
  3079. }
  3080. /**
  3081. * Creates a new function that, when called, invokes `func` with the `this`
  3082. * binding of `thisArg` and prepends any additional `bind` arguments to those
  3083. * passed to the bound function. Lazy defined methods may be bound by passing
  3084. * the object they are bound to as `func` and the method name as `thisArg`.
  3085. *
  3086. * @static
  3087. * @memberOf _
  3088. * @category Functions
  3089. * @param {Function|Object} func The function to bind or the object the method belongs to.
  3090. * @param {Mixed} [thisArg] The `this` binding of `func` or the method name.
  3091. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
  3092. * @returns {Function} Returns the new bound function.
  3093. * @example
  3094. *
  3095. * // basic bind
  3096. * var func = function(greeting) {
  3097. * return greeting + ' ' + this.name;
  3098. * };
  3099. *
  3100. * func = _.bind(func, { 'name': 'moe' }, 'hi');
  3101. * func();
  3102. * // => 'hi moe'
  3103. *
  3104. * // lazy bind
  3105. * var object = {
  3106. * 'name': 'moe',
  3107. * 'greet': function(greeting) {
  3108. * return greeting + ' ' + this.name;
  3109. * }
  3110. * };
  3111. *
  3112. * var func = _.bind(object, 'greet', 'hi');
  3113. * func();
  3114. * // => 'hi moe'
  3115. *
  3116. * object.greet = function(greeting) {
  3117. * return greeting + ', ' + this.name + '!';
  3118. * };
  3119. *
  3120. * func();
  3121. * // => 'hi, moe!'
  3122. */
  3123. function bind(func, thisArg) {
  3124. var methodName,
  3125. isFunc = isFunction(func);
  3126. // juggle arguments
  3127. if (!isFunc) {
  3128. methodName = thisArg;
  3129. thisArg = func;
  3130. }
  3131. // use `Function#bind` if it exists and is fast
  3132. // (in V8 `Function#bind` is slower except when partially applied)
  3133. else if (isBindFast || (nativeBind && arguments.length > 2)) {
  3134. return nativeBind.call.apply(nativeBind, arguments);
  3135. }
  3136. var partialArgs = slice.call(arguments, 2);
  3137. function bound() {
  3138. // `Function#bind` spec
  3139. // http://es5.github.com/#x15.3.4.5
  3140. var args = arguments,
  3141. thisBinding = thisArg;
  3142. if (!isFunc) {
  3143. func = thisArg[methodName];
  3144. }
  3145. if (partialArgs.length) {
  3146. args = args.length
  3147. ? partialArgs.concat(slice.call(args))
  3148. : partialArgs;
  3149. }
  3150. if (this instanceof bound) {
  3151. // get `func` instance if `bound` is invoked in a `new` expression
  3152. noop.prototype = func.prototype;
  3153. thisBinding = new noop;
  3154. // mimic the constructor's `return` behavior
  3155. // http://es5.github.com/#x13.2.2
  3156. var result = func.apply(thisBinding, args);
  3157. return result && objectTypes[typeof result]
  3158. ? result
  3159. : thisBinding
  3160. }
  3161. return func.apply(thisBinding, args);
  3162. }
  3163. return bound;
  3164. }
  3165. /**
  3166. * Binds methods on `object` to `object`, overwriting the existing method.
  3167. * If no method names are provided, all the function properties of `object`
  3168. * will be bound.
  3169. *
  3170. * @static
  3171. * @memberOf _
  3172. * @category Functions
  3173. * @param {Object} object The object to bind and assign the bound methods to.
  3174. * @param {String} [methodName1, methodName2, ...] Method names on the object to bind.
  3175. * @returns {Object} Returns `object`.
  3176. * @example
  3177. *
  3178. * var buttonView = {
  3179. * 'label': 'lodash',
  3180. * 'onClick': function() { alert('clicked: ' + this.label); }
  3181. * };
  3182. *
  3183. * _.bindAll(buttonView);
  3184. * jQuery('#lodash_button').on('click', buttonView.onClick);
  3185. * // => When the button is clicked, `this.label` will have the correct value
  3186. */
  3187. var bindAll = createIterator({
  3188. 'useHas': false,
  3189. 'useStrict': false,
  3190. 'args': 'object',
  3191. 'init': 'object',
  3192. 'top':
  3193. 'var funcs = arguments,\n' +
  3194. ' length = funcs.length;\n' +
  3195. 'if (length > 1) {\n' +
  3196. ' for (var index = 1; index < length; index++) {\n' +
  3197. ' result[funcs[index]] = bind(result[funcs[index]], result)\n' +
  3198. ' }\n' +
  3199. ' return result\n' +
  3200. '}',
  3201. 'inLoop':
  3202. 'if (isFunction(result[index])) {\n' +
  3203. ' result[index] = bind(result[index], result)\n' +
  3204. '}'
  3205. });
  3206. /**
  3207. * Creates a new function that is the composition of the passed functions,
  3208. * where each function consumes the return value of the function that follows.
  3209. * In math terms, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
  3210. *
  3211. * @static
  3212. * @memberOf _
  3213. * @category Functions
  3214. * @param {Function} [func1, func2, ...] Functions to compose.
  3215. * @returns {Function} Returns the new composed function.
  3216. * @example
  3217. *
  3218. * var greet = function(name) { return 'hi: ' + name; };
  3219. * var exclaim = function(statement) { return statement + '!'; };
  3220. * var welcome = _.compose(exclaim, greet);
  3221. * welcome('moe');
  3222. * // => 'hi: moe!'
  3223. */
  3224. function compose() {
  3225. var funcs = arguments;
  3226. return function() {
  3227. var args = arguments,
  3228. length = funcs.length;
  3229. while (length--) {
  3230. args = [funcs[length].apply(this, args)];
  3231. }
  3232. return args[0];
  3233. };
  3234. }
  3235. /**
  3236. * Creates a new function that will delay the execution of `func` until after
  3237. * `wait` milliseconds have elapsed since the last time it was invoked. Pass
  3238. * `true` for `immediate` to cause debounce to invoke `func` on the leading,
  3239. * instead of the trailing, edge of the `wait` timeout. Subsequent calls to
  3240. * the debounced function will return the result of the last `func` call.
  3241. *
  3242. * @static
  3243. * @memberOf _
  3244. * @category Functions
  3245. * @param {Function} func The function to debounce.
  3246. * @param {Number} wait The number of milliseconds to delay.
  3247. * @param {Boolean} immediate A flag to indicate execution is on the leading
  3248. * edge of the timeout.
  3249. * @returns {Function} Returns the new debounced function.
  3250. * @example
  3251. *
  3252. * var lazyLayout = _.debounce(calculateLayout, 300);
  3253. * jQuery(window).on('resize', lazyLayout);
  3254. */
  3255. function debounce(func, wait, immediate) {
  3256. var args,
  3257. result,
  3258. thisArg,
  3259. timeoutId;
  3260. function delayed() {
  3261. timeoutId = null;
  3262. if (!immediate) {
  3263. func.apply(thisArg, args);
  3264. }
  3265. }
  3266. return function() {
  3267. var isImmediate = immediate && !timeoutId;
  3268. args = arguments;
  3269. thisArg = this;
  3270. clearTimeout(timeoutId);
  3271. timeoutId = setTimeout(delayed, wait);
  3272. if (isImmediate) {
  3273. result = func.apply(thisArg, args);
  3274. }
  3275. return result;
  3276. };
  3277. }
  3278. /**
  3279. * Executes the `func` function after `wait` milliseconds. Additional arguments
  3280. * will be passed to `func` when it is invoked.
  3281. *
  3282. * @static
  3283. * @memberOf _
  3284. * @category Functions
  3285. * @param {Function} func The function to delay.
  3286. * @param {Number} wait The number of milliseconds to delay execution.
  3287. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
  3288. * @returns {Number} Returns the `setTimeout` timeout id.
  3289. * @example
  3290. *
  3291. * var log = _.bind(console.log, console);
  3292. * _.delay(log, 1000, 'logged later');
  3293. * // => 'logged later' (Appears after one second.)
  3294. */
  3295. function delay(func, wait) {
  3296. var args = slice.call(arguments, 2);
  3297. return setTimeout(function() { return func.apply(undefined, args); }, wait);
  3298. }
  3299. /**
  3300. * Defers executing the `func` function until the current call stack has cleared.
  3301. * Additional arguments will be passed to `func` when it is invoked.
  3302. *
  3303. * @static
  3304. * @memberOf _
  3305. * @category Functions
  3306. * @param {Function} func The function to defer.
  3307. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
  3308. * @returns {Number} Returns the `setTimeout` timeout id.
  3309. * @example
  3310. *
  3311. * _.defer(function() { alert('deferred'); });
  3312. * // returns from the function before `alert` is called
  3313. */
  3314. function defer(func) {
  3315. var args = slice.call(arguments, 1);
  3316. return setTimeout(function() { return func.apply(undefined, args); }, 1);
  3317. }
  3318. /**
  3319. * Creates a new function that memoizes the result of `func`. If `resolver` is
  3320. * passed, it will be used to determine the cache key for storing the result
  3321. * based on the arguments passed to the memoized function. By default, the first
  3322. * argument passed to the memoized function is used as the cache key.
  3323. *
  3324. * @static
  3325. * @memberOf _
  3326. * @category Functions
  3327. * @param {Function} func The function to have its output memoized.
  3328. * @param {Function} [resolver] A function used to resolve the cache key.
  3329. * @returns {Function} Returns the new memoizing function.
  3330. * @example
  3331. *
  3332. * var fibonacci = _.memoize(function(n) {
  3333. * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
  3334. * });
  3335. */
  3336. function memoize(func, resolver) {
  3337. var cache = {};
  3338. return function() {
  3339. var prop = resolver ? resolver.apply(this, arguments) : arguments[0];
  3340. return hasOwnProperty.call(cache, prop)
  3341. ? cache[prop]
  3342. : (cache[prop] = func.apply(this, arguments));
  3343. };
  3344. }
  3345. /**
  3346. * Creates a new function that is restricted to one execution. Repeat calls to
  3347. * the function will return the value of the first call.
  3348. *
  3349. * @static
  3350. * @memberOf _
  3351. * @category Functions
  3352. * @param {Function} func The function to restrict.
  3353. * @returns {Function} Returns the new restricted function.
  3354. * @example
  3355. *
  3356. * var initialize = _.once(createApplication);
  3357. * initialize();
  3358. * initialize();
  3359. * // Application is only created once.
  3360. */
  3361. function once(func) {
  3362. var result,
  3363. ran = false;
  3364. return function() {
  3365. if (ran) {
  3366. return result;
  3367. }
  3368. ran = true;
  3369. result = func.apply(this, arguments);
  3370. // clear the `func` variable so the function may be garbage collected
  3371. func = null;
  3372. return result;
  3373. };
  3374. }
  3375. /**
  3376. * Creates a new function that, when called, invokes `func` with any additional
  3377. * `partial` arguments prepended to those passed to the new function. This method
  3378. * is similar `bind`, except it does **not** alter the `this` binding.
  3379. *
  3380. * @static
  3381. * @memberOf _
  3382. * @category Functions
  3383. * @param {Function} func The function to partially apply arguments to.
  3384. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
  3385. * @returns {Function} Returns the new partially applied function.
  3386. * @example
  3387. *
  3388. * var greet = function(greeting, name) { return greeting + ': ' + name; };
  3389. * var hi = _.partial(greet, 'hi');
  3390. * hi('moe');
  3391. * // => 'hi: moe'
  3392. */
  3393. function partial(func) {
  3394. var args = slice.call(arguments, 1),
  3395. argsLength = args.length;
  3396. return function() {
  3397. var result,
  3398. others = arguments;
  3399. if (others.length) {
  3400. args.length = argsLength;
  3401. push.apply(args, others);
  3402. }
  3403. result = args.length == 1 ? func.call(this, args[0]) : func.apply(this, args);
  3404. args.length = argsLength;
  3405. return result;
  3406. };
  3407. }
  3408. /**
  3409. * Creates a new function that, when executed, will only call the `func`
  3410. * function at most once per every `wait` milliseconds. If the throttled
  3411. * function is invoked more than once during the `wait` timeout, `func` will
  3412. * also be called on the trailing edge of the timeout. Subsequent calls to the
  3413. * throttled function will return the result of the last `func` call.
  3414. *
  3415. * @static
  3416. * @memberOf _
  3417. * @category Functions
  3418. * @param {Function} func The function to throttle.
  3419. * @param {Number} wait The number of milliseconds to throttle executions to.
  3420. * @returns {Function} Returns the new throttled function.
  3421. * @example
  3422. *
  3423. * var throttled = _.throttle(updatePosition, 100);
  3424. * jQuery(window).on('scroll', throttled);
  3425. */
  3426. function throttle(func, wait) {
  3427. var args,
  3428. result,
  3429. thisArg,
  3430. timeoutId,
  3431. lastCalled = 0;
  3432. function trailingCall() {
  3433. lastCalled = new Date;
  3434. timeoutId = null;
  3435. func.apply(thisArg, args);
  3436. }
  3437. return function() {
  3438. var now = new Date,
  3439. remain = wait - (now - lastCalled);
  3440. args = arguments;
  3441. thisArg = this;
  3442. if (remain <= 0) {
  3443. lastCalled = now;
  3444. result = func.apply(thisArg, args);
  3445. }
  3446. else if (!timeoutId) {
  3447. timeoutId = setTimeout(trailingCall, remain);
  3448. }
  3449. return result;
  3450. };
  3451. }
  3452. /**
  3453. * Creates a new function that passes `value` to the `wrapper` function as its
  3454. * first argument. Additional arguments passed to the new function are appended
  3455. * to those passed to the `wrapper` function.
  3456. *
  3457. * @static
  3458. * @memberOf _
  3459. * @category Functions
  3460. * @param {Mixed} value The value to wrap.
  3461. * @param {Function} wrapper The wrapper function.
  3462. * @returns {Function} Returns the new function.
  3463. * @example
  3464. *
  3465. * var hello = function(name) { return 'hello: ' + name; };
  3466. * hello = _.wrap(hello, function(func) {
  3467. * return 'before, ' + func('moe') + ', after';
  3468. * });
  3469. * hello();
  3470. * // => 'before, hello: moe, after'
  3471. */
  3472. function wrap(value, wrapper) {
  3473. return function() {
  3474. var args = [value];
  3475. if (arguments.length) {
  3476. push.apply(args, arguments);
  3477. }
  3478. return wrapper.apply(this, args);
  3479. };
  3480. }
  3481. /*--------------------------------------------------------------------------*/
  3482. /**
  3483. * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
  3484. * corresponding HTML entities.
  3485. *
  3486. * @static
  3487. * @memberOf _
  3488. * @category Utilities
  3489. * @param {String} string The string to escape.
  3490. * @returns {String} Returns the escaped string.
  3491. * @example
  3492. *
  3493. * _.escape('Moe, Larry & Curly');
  3494. * // => "Moe, Larry &amp; Curly"
  3495. */
  3496. function escape(string) {
  3497. return string == null ? '' : (string + '').replace(reUnescapedHtml, escapeHtmlChar);
  3498. }
  3499. /**
  3500. * This function returns the first argument passed to it.
  3501. *
  3502. * Note: It is used throughout Lo-Dash as a default callback.
  3503. *
  3504. * @static
  3505. * @memberOf _
  3506. * @category Utilities
  3507. * @param {Mixed} value Any value.
  3508. * @returns {Mixed} Returns `value`.
  3509. * @example
  3510. *
  3511. * var moe = { 'name': 'moe' };
  3512. * moe === _.identity(moe);
  3513. * // => true
  3514. */
  3515. function identity(value) {
  3516. return value;
  3517. }
  3518. /**
  3519. * Adds functions properties of `object` to the `lodash` function and chainable
  3520. * wrapper.
  3521. *
  3522. * @static
  3523. * @memberOf _
  3524. * @category Utilities
  3525. * @param {Object} object The object of function properties to add to `lodash`.
  3526. * @example
  3527. *
  3528. * _.mixin({
  3529. * 'capitalize': function(string) {
  3530. * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
  3531. * }
  3532. * });
  3533. *
  3534. * _.capitalize('larry');
  3535. * // => 'Larry'
  3536. *
  3537. * _('curly').capitalize();
  3538. * // => 'Curly'
  3539. */
  3540. function mixin(object) {
  3541. forEach(functions(object), function(methodName) {
  3542. var func = lodash[methodName] = object[methodName];
  3543. LoDash.prototype[methodName] = function() {
  3544. var args = [this.__wrapped__];
  3545. if (arguments.length) {
  3546. push.apply(args, arguments);
  3547. }
  3548. var result = func.apply(lodash, args);
  3549. if (this.__chain__) {
  3550. result = new LoDash(result);
  3551. result.__chain__ = true;
  3552. }
  3553. return result;
  3554. };
  3555. });
  3556. }
  3557. /**
  3558. * Reverts the '_' variable to its previous value and returns a reference to
  3559. * the `lodash` function.
  3560. *
  3561. * @static
  3562. * @memberOf _
  3563. * @category Utilities
  3564. * @returns {Function} Returns the `lodash` function.
  3565. * @example
  3566. *
  3567. * var lodash = _.noConflict();
  3568. */
  3569. function noConflict() {
  3570. window._ = oldDash;
  3571. return this;
  3572. }
  3573. /**
  3574. * Produces a random number between `min` and `max` (inclusive). If only one
  3575. * argument is passed, a number between `0` and the given number will be returned.
  3576. * If no arguments are passed `_.random` will act as `Math.random`.
  3577. *
  3578. * @static
  3579. * @memberOf _
  3580. * @category Utilities
  3581. * @param {Number} min The minimum possible value.
  3582. * @param {Number} max The maximum possible value.
  3583. * @returns {Number} Returns the random number.
  3584. * @example
  3585. *
  3586. * _.random(0, 5);
  3587. * // => a number between 1 and 5
  3588. *
  3589. * _.random(5);
  3590. * // => also a number between 1 and 5
  3591. *
  3592. * _.random();
  3593. * // => an integer between 0 and less than 1
  3594. */
  3595. function random(min, max) {
  3596. if (min == null && max == null) {
  3597. return nativeRandom();
  3598. }
  3599. min = +min || 0;
  3600. if (max == null) {
  3601. max = min;
  3602. min = 0;
  3603. }
  3604. return min + nativeFloor(nativeRandom() * ((+max || 0) - min + 1));
  3605. }
  3606. /**
  3607. * Resolves the value of `property` on `object`. If `property` is a function
  3608. * it will be invoked and its result returned, else the property value is
  3609. * returned. If `object` is falsey, then `null` is returned.
  3610. *
  3611. * @deprecated
  3612. * @static
  3613. * @memberOf _
  3614. * @category Utilities
  3615. * @param {Object} object The object to inspect.
  3616. * @param {String} property The property to get the result of.
  3617. * @returns {Mixed} Returns the resolved value.
  3618. * @example
  3619. *
  3620. * var object = {
  3621. * 'cheese': 'crumpets',
  3622. * 'stuff': function() {
  3623. * return 'nonsense';
  3624. * }
  3625. * };
  3626. *
  3627. * _.result(object, 'cheese');
  3628. * // => 'crumpets'
  3629. *
  3630. * _.result(object, 'stuff');
  3631. * // => 'nonsense'
  3632. */
  3633. function result(object, property) {
  3634. // based on Backbone's private `getValue` function
  3635. // https://github.com/documentcloud/backbone/blob/0.9.2/backbone.js#L1419-1424
  3636. if (!object) {
  3637. return null;
  3638. }
  3639. var value = object[property];
  3640. return isFunction(value) ? object[property]() : value;
  3641. }
  3642. /**
  3643. * A micro-templating method that handles arbitrary delimiters, preserves
  3644. * whitespace, and correctly escapes quotes within interpolated code.
  3645. *
  3646. * Note: In the development build `_.template` utilizes sourceURLs for easier
  3647. * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
  3648. *
  3649. * Note: Lo-Dash may be used in Chrome extensions by either creating a `lodash csp`
  3650. * build and avoiding `_.template` use, or loading Lo-Dash in a sandboxed page.
  3651. * See http://developer.chrome.com/trunk/extensions/sandboxingEval.html
  3652. *
  3653. * @static
  3654. * @memberOf _
  3655. * @category Utilities
  3656. * @param {String} text The template text.
  3657. * @param {Obect} data The data object used to populate the text.
  3658. * @param {Object} options The options object.
  3659. * @returns {Function|String} Returns a compiled function when no `data` object
  3660. * is given, else it returns the interpolated text.
  3661. * @example
  3662. *
  3663. * // using a compiled template
  3664. * var compiled = _.template('hello: <%= name %>');
  3665. * compiled({ 'name': 'moe' });
  3666. * // => 'hello: moe'
  3667. *
  3668. * var list = '<% _.forEach(people, function(name) { %> <li><%= name %></li> <% }); %>';
  3669. * _.template(list, { 'people': ['moe', 'larry', 'curly'] });
  3670. * // => '<li>moe</li><li>larry</li><li>curly</li>'
  3671. *
  3672. * // using the "escape" delimiter to escape HTML in data property values
  3673. * _.template('<b><%- value %></b>', { 'value': '<script>' });
  3674. * // => '<b>&lt;script></b>'
  3675. *
  3676. * // using the internal `print` function in "evaluate" delimiters
  3677. * _.template('<% print("Hello " + epithet); %>', { 'epithet': 'stooge' });
  3678. * // => 'Hello stooge.'
  3679. *
  3680. * // using custom template delimiter settings
  3681. * _.templateSettings = {
  3682. * 'interpolate': /\{\{(.+?)\}\}/g
  3683. * };
  3684. *
  3685. * _.template('Hello {{ name }}!', { 'name': 'Mustache' });
  3686. * // => 'Hello Mustache!'
  3687. *
  3688. * // using the `variable` option to ensure a with-statement isn't used in the compiled template
  3689. * var compiled = _.template('hello: <%= data.name %>', null, { 'variable': 'data' });
  3690. * compiled.source;
  3691. * // => function(data) {
  3692. * var __t, __p = '', __e = _.escape;
  3693. * __p += 'hello: ' + ((__t = ( data.name )) == null ? '' : __t);
  3694. * return __p;
  3695. * }
  3696. *
  3697. * // using the `source` property to inline compiled templates for meaningful
  3698. * // line numbers in error messages and a stack trace
  3699. * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
  3700. * var JST = {\
  3701. * "main": ' + _.template(mainText).source + '\
  3702. * };\
  3703. * ');
  3704. */
  3705. function template(text, data, options) {
  3706. // based on John Resig's `tmpl` implementation
  3707. // http://ejohn.org/blog/javascript-micro-templating/
  3708. // and Laura Doktorova's doT.js
  3709. // https://github.com/olado/doT
  3710. options || (options = {});
  3711. text += '';
  3712. var isEvaluating,
  3713. result,
  3714. escapeDelimiter = options.escape,
  3715. evaluateDelimiter = options.evaluate,
  3716. interpolateDelimiter = options.interpolate,
  3717. settings = lodash.templateSettings,
  3718. variable = options.variable || settings.variable,
  3719. hasVariable = variable;
  3720. // use default settings if no options object is provided
  3721. if (escapeDelimiter == null) {
  3722. escapeDelimiter = settings.escape;
  3723. }
  3724. if (evaluateDelimiter == null) {
  3725. // use `false` as the fallback value, instead of leaving it `undefined`,
  3726. // so the initial assignment of `reEvaluateDelimiter` will still occur
  3727. evaluateDelimiter = settings.evaluate || false;
  3728. }
  3729. if (interpolateDelimiter == null) {
  3730. interpolateDelimiter = settings.interpolate;
  3731. }
  3732. // tokenize delimiters to avoid escaping them
  3733. if (escapeDelimiter) {
  3734. text = text.replace(escapeDelimiter, tokenizeEscape);
  3735. }
  3736. if (interpolateDelimiter) {
  3737. text = text.replace(interpolateDelimiter, tokenizeInterpolate);
  3738. }
  3739. if (evaluateDelimiter != lastEvaluateDelimiter) {
  3740. // generate `reEvaluateDelimiter` to match `_.templateSettings.evaluate`
  3741. // and internal `<e%- %>`, `<e%= %>` delimiters
  3742. lastEvaluateDelimiter = evaluateDelimiter;
  3743. reEvaluateDelimiter = RegExp(
  3744. '<e%-([\\s\\S]+?)%>|<e%=([\\s\\S]+?)%>' +
  3745. (evaluateDelimiter ? '|' + evaluateDelimiter.source : '')
  3746. , 'g');
  3747. }
  3748. isEvaluating = tokenized.length;
  3749. text = text.replace(reEvaluateDelimiter, tokenizeEvaluate);
  3750. isEvaluating = isEvaluating != tokenized.length;
  3751. // escape characters that cannot be included in string literals and
  3752. // detokenize delimiter code snippets
  3753. text = "__p += '" + text
  3754. .replace(reUnescapedString, escapeStringChar)
  3755. .replace(reToken, detokenize) + "';\n";
  3756. // clear stored code snippets
  3757. tokenized.length = 0;
  3758. // if `variable` is not specified and the template contains "evaluate"
  3759. // delimiters, wrap a with-statement around the generated code to add the
  3760. // data object to the top of the scope chain
  3761. if (!hasVariable) {
  3762. variable = lastVariable || 'obj';
  3763. if (isEvaluating) {
  3764. text = 'with (' + variable + ') {\n' + text + '\n}\n';
  3765. }
  3766. else {
  3767. if (variable != lastVariable) {
  3768. // generate `reDoubleVariable` to match references like `obj.obj` inside
  3769. // transformed "escape" and "interpolate" delimiters
  3770. lastVariable = variable;
  3771. reDoubleVariable = RegExp('(\\(\\s*)' + variable + '\\.' + variable + '\\b', 'g');
  3772. }
  3773. // avoid a with-statement by prepending data object references to property names
  3774. text = text
  3775. .replace(reInsertVariable, '$&' + variable + '.')
  3776. .replace(reDoubleVariable, '$1__d');
  3777. }
  3778. }
  3779. // cleanup code by stripping empty strings
  3780. text = ( isEvaluating ? text.replace(reEmptyStringLeading, '') : text)
  3781. .replace(reEmptyStringMiddle, '$1')
  3782. .replace(reEmptyStringTrailing, '$1;');
  3783. // frame code as the function body
  3784. text = 'function(' + variable + ') {\n' +
  3785. (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
  3786. 'var __t, __p = \'\', __e = _.escape' +
  3787. (isEvaluating
  3788. ? ', __j = Array.prototype.join;\n' +
  3789. 'function print() { __p += __j.call(arguments, \'\') }\n'
  3790. : (hasVariable ? '' : ', __d = ' + variable + '.' + variable + ' || ' + variable) + ';\n'
  3791. ) +
  3792. text +
  3793. 'return __p\n}';
  3794. // add a sourceURL for easier debugging
  3795. // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
  3796. if (useSourceURL) {
  3797. text += '\n//@ sourceURL=/lodash/template/source[' + (templateCounter++) + ']';
  3798. }
  3799. try {
  3800. result = Function('_', 'return ' + text)(lodash);
  3801. } catch(e) {
  3802. // defer syntax errors until the compiled template is executed to allow
  3803. // examining the `source` property beforehand and for consistency,
  3804. // because other template related errors occur at execution
  3805. result = function() { throw e; };
  3806. }
  3807. if (data) {
  3808. return result(data);
  3809. }
  3810. // provide the compiled function's source via its `toString` method, in
  3811. // supported environments, or the `source` property as a convenience for
  3812. // inlining compiled templates during the build process
  3813. result.source = text;
  3814. return result;
  3815. }
  3816. /**
  3817. * Executes the `callback` function `n` times. The `callback` is bound to
  3818. * `thisArg` and invoked with 1 argument; (index).
  3819. *
  3820. * @static
  3821. * @memberOf _
  3822. * @category Utilities
  3823. * @param {Number} n The number of times to execute the callback.
  3824. * @param {Function} callback The function called per iteration.
  3825. * @param {Mixed} [thisArg] The `this` binding for the callback.
  3826. * @example
  3827. *
  3828. * _.times(3, function(n) { genie.grantWish(n); });
  3829. * // => calls `genie.grantWish(n)` three times, passing `n` of `0`, `1`, and `2` respectively
  3830. *
  3831. * _.times(3, function(n) { this.grantWish(n); }, genie);
  3832. * // => also calls `genie.grantWish(n)` three times
  3833. */
  3834. function times(n, callback, thisArg) {
  3835. var index = -1;
  3836. if (thisArg) {
  3837. while (++index < n) {
  3838. callback.call(thisArg, index);
  3839. }
  3840. } else {
  3841. while (++index < n) {
  3842. callback(index);
  3843. }
  3844. }
  3845. }
  3846. /**
  3847. * Converts the HTML entities `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#x27;`
  3848. * in `string` to their corresponding characters.
  3849. *
  3850. * @static
  3851. * @memberOf _
  3852. * @category Utilities
  3853. * @param {String} string The string to unescape.
  3854. * @returns {String} Returns the unescaped string.
  3855. * @example
  3856. *
  3857. * _.unescape('Moe, Larry &amp; Curly');
  3858. * // => "Moe, Larry & Curly"
  3859. */
  3860. function unescape(string) {
  3861. return string == null ? '' : (string + '').replace(reEscapedHtml, unescapeHtmlChar);
  3862. }
  3863. /**
  3864. * Generates a unique id. If `prefix` is passed, the id will be appended to it.
  3865. *
  3866. * @static
  3867. * @memberOf _
  3868. * @category Utilities
  3869. * @param {String} [prefix] The value to prefix the id with.
  3870. * @returns {Number|String} Returns a numeric id if no prefix is passed, else
  3871. * a string id may be returned.
  3872. * @example
  3873. *
  3874. * _.uniqueId('contact_');
  3875. * // => 'contact_104'
  3876. */
  3877. function uniqueId(prefix) {
  3878. var id = idCounter++;
  3879. return prefix ? prefix + id : id;
  3880. }
  3881. /*--------------------------------------------------------------------------*/
  3882. /**
  3883. * Wraps the value in a `lodash` wrapper object.
  3884. *
  3885. * @static
  3886. * @memberOf _
  3887. * @category Chaining
  3888. * @param {Mixed} value The value to wrap.
  3889. * @returns {Object} Returns the wrapper object.
  3890. * @example
  3891. *
  3892. * var stooges = [
  3893. * { 'name': 'moe', 'age': 40 },
  3894. * { 'name': 'larry', 'age': 50 },
  3895. * { 'name': 'curly', 'age': 60 }
  3896. * ];
  3897. *
  3898. * var youngest = _.chain(stooges)
  3899. * .sortBy(function(stooge) { return stooge.age; })
  3900. * .map(function(stooge) { return stooge.name + ' is ' + stooge.age; })
  3901. * .first()
  3902. * .value();
  3903. * // => 'moe is 40'
  3904. */
  3905. function chain(value) {
  3906. value = new LoDash(value);
  3907. value.__chain__ = true;
  3908. return value;
  3909. }
  3910. /**
  3911. * Invokes `interceptor` with the `value` as the first argument, and then
  3912. * returns `value`. The purpose of this method is to "tap into" a method chain,
  3913. * in order to perform operations on intermediate results within the chain.
  3914. *
  3915. * @static
  3916. * @memberOf _
  3917. * @category Chaining
  3918. * @param {Mixed} value The value to pass to `interceptor`.
  3919. * @param {Function} interceptor The function to invoke.
  3920. * @returns {Mixed} Returns `value`.
  3921. * @example
  3922. *
  3923. * _.chain([1,2,3,200])
  3924. * .filter(function(num) { return num % 2 == 0; })
  3925. * .tap(alert)
  3926. * .map(function(num) { return num * num })
  3927. * .value();
  3928. * // => // [2, 200] (alerted)
  3929. * // => [4, 40000]
  3930. */
  3931. function tap(value, interceptor) {
  3932. interceptor(value);
  3933. return value;
  3934. }
  3935. /**
  3936. * Enables method chaining on the wrapper object.
  3937. *
  3938. * @name chain
  3939. * @deprecated
  3940. * @memberOf _
  3941. * @category Chaining
  3942. * @returns {Mixed} Returns the wrapper object.
  3943. * @example
  3944. *
  3945. * _([1, 2, 3]).value();
  3946. * // => [1, 2, 3]
  3947. */
  3948. function wrapperChain() {
  3949. this.__chain__ = true;
  3950. return this;
  3951. }
  3952. /**
  3953. * Extracts the wrapped value.
  3954. *
  3955. * @name value
  3956. * @memberOf _
  3957. * @category Chaining
  3958. * @returns {Mixed} Returns the wrapped value.
  3959. * @example
  3960. *
  3961. * _([1, 2, 3]).value();
  3962. * // => [1, 2, 3]
  3963. */
  3964. function wrapperValue() {
  3965. return this.__wrapped__;
  3966. }
  3967. /*--------------------------------------------------------------------------*/
  3968. /**
  3969. * The semantic version number.
  3970. *
  3971. * @static
  3972. * @memberOf _
  3973. * @type String
  3974. */
  3975. lodash.VERSION = '0.6.1';
  3976. // assign static methods
  3977. lodash.after = after;
  3978. lodash.bind = bind;
  3979. lodash.bindAll = bindAll;
  3980. lodash.chain = chain;
  3981. lodash.clone = clone;
  3982. lodash.compact = compact;
  3983. lodash.compose = compose;
  3984. lodash.contains = contains;
  3985. lodash.countBy = countBy;
  3986. lodash.debounce = debounce;
  3987. lodash.defaults = defaults;
  3988. lodash.defer = defer;
  3989. lodash.delay = delay;
  3990. lodash.difference = difference;
  3991. lodash.escape = escape;
  3992. lodash.every = every;
  3993. lodash.extend = extend;
  3994. lodash.filter = filter;
  3995. lodash.find = find;
  3996. lodash.first = first;
  3997. lodash.flatten = flatten;
  3998. lodash.forEach = forEach;
  3999. lodash.forIn = forIn;
  4000. lodash.forOwn = forOwn;
  4001. lodash.functions = functions;
  4002. lodash.groupBy = groupBy;
  4003. lodash.has = has;
  4004. lodash.identity = identity;
  4005. lodash.indexOf = indexOf;
  4006. lodash.initial = initial;
  4007. lodash.intersection = intersection;
  4008. lodash.invert = invert;
  4009. lodash.invoke = invoke;
  4010. lodash.isArguments = isArguments;
  4011. lodash.isArray = isArray;
  4012. lodash.isBoolean = isBoolean;
  4013. lodash.isDate = isDate;
  4014. lodash.isElement = isElement;
  4015. lodash.isEmpty = isEmpty;
  4016. lodash.isEqual = isEqual;
  4017. lodash.isFinite = isFinite;
  4018. lodash.isFunction = isFunction;
  4019. lodash.isNaN = isNaN;
  4020. lodash.isNull = isNull;
  4021. lodash.isNumber = isNumber;
  4022. lodash.isObject = isObject;
  4023. lodash.isRegExp = isRegExp;
  4024. lodash.isString = isString;
  4025. lodash.isUndefined = isUndefined;
  4026. lodash.keys = keys;
  4027. lodash.last = last;
  4028. lodash.lastIndexOf = lastIndexOf;
  4029. lodash.map = map;
  4030. lodash.max = max;
  4031. lodash.memoize = memoize;
  4032. lodash.merge = merge;
  4033. lodash.min = min;
  4034. lodash.mixin = mixin;
  4035. lodash.noConflict = noConflict;
  4036. lodash.object = object;
  4037. lodash.omit = omit;
  4038. lodash.once = once;
  4039. lodash.pairs = pairs;
  4040. lodash.partial = partial;
  4041. lodash.pick = pick;
  4042. lodash.pluck = pluck;
  4043. lodash.random = random;
  4044. lodash.range = range;
  4045. lodash.reduce = reduce;
  4046. lodash.reduceRight = reduceRight;
  4047. lodash.reject = reject;
  4048. lodash.rest = rest;
  4049. lodash.result = result;
  4050. lodash.shuffle = shuffle;
  4051. lodash.size = size;
  4052. lodash.some = some;
  4053. lodash.sortBy = sortBy;
  4054. lodash.sortedIndex = sortedIndex;
  4055. lodash.tap = tap;
  4056. lodash.template = template;
  4057. lodash.throttle = throttle;
  4058. lodash.times = times;
  4059. lodash.toArray = toArray;
  4060. lodash.unescape = unescape;
  4061. lodash.union = union;
  4062. lodash.uniq = uniq;
  4063. lodash.uniqueId = uniqueId;
  4064. lodash.values = values;
  4065. lodash.where = where;
  4066. lodash.without = without;
  4067. lodash.wrap = wrap;
  4068. lodash.zip = zip;
  4069. // assign aliases
  4070. lodash.all = every;
  4071. lodash.any = some;
  4072. lodash.collect = map;
  4073. lodash.detect = find;
  4074. lodash.drop = rest;
  4075. lodash.each = forEach;
  4076. lodash.foldl = reduce;
  4077. lodash.foldr = reduceRight;
  4078. lodash.head = first;
  4079. lodash.include = contains;
  4080. lodash.inject = reduce;
  4081. lodash.methods = functions;
  4082. lodash.select = filter;
  4083. lodash.tail = rest;
  4084. lodash.take = first;
  4085. lodash.unique = uniq;
  4086. // add pseudo private properties used and removed during the build process
  4087. lodash._iteratorTemplate = iteratorTemplate;
  4088. lodash._shimKeys = shimKeys;
  4089. /*--------------------------------------------------------------------------*/
  4090. // assign private `LoDash` constructor's prototype
  4091. LoDash.prototype = lodash.prototype;
  4092. // add all static functions to `LoDash.prototype`
  4093. mixin(lodash);
  4094. // add `LoDash.prototype.chain` after calling `mixin()` to avoid overwriting
  4095. // it with the wrapped `lodash.chain`
  4096. LoDash.prototype.chain = wrapperChain;
  4097. LoDash.prototype.value = wrapperValue;
  4098. // add all mutator Array functions to the wrapper.
  4099. forEach(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
  4100. var func = ArrayProto[methodName];
  4101. LoDash.prototype[methodName] = function() {
  4102. var value = this.__wrapped__;
  4103. func.apply(value, arguments);
  4104. // avoid array-like object bugs with `Array#shift` and `Array#splice` in
  4105. // Firefox < 10 and IE < 9
  4106. if (hasObjectSpliceBug && value.length === 0) {
  4107. delete value[0];
  4108. }
  4109. if (this.__chain__) {
  4110. value = new LoDash(value);
  4111. value.__chain__ = true;
  4112. }
  4113. return value;
  4114. };
  4115. });
  4116. // add all accessor Array functions to the wrapper.
  4117. forEach(['concat', 'join', 'slice'], function(methodName) {
  4118. var func = ArrayProto[methodName];
  4119. LoDash.prototype[methodName] = function() {
  4120. var value = this.__wrapped__,
  4121. result = func.apply(value, arguments);
  4122. if (this.__chain__) {
  4123. result = new LoDash(result);
  4124. result.__chain__ = true;
  4125. }
  4126. return result;
  4127. };
  4128. });
  4129. /*--------------------------------------------------------------------------*/
  4130. // expose Lo-Dash
  4131. // some AMD build optimizers, like r.js, check for specific condition patterns like the following:
  4132. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  4133. // Expose Lo-Dash to the global object even when an AMD loader is present in
  4134. // case Lo-Dash was injected by a third-party script and not intended to be
  4135. // loaded as a module. The global assignment can be reverted in the Lo-Dash
  4136. // module via its `noConflict()` method.
  4137. window._ = lodash;
  4138. // define as an anonymous module so, through path mapping, it can be
  4139. // referenced as the "underscore" module
  4140. define(function() {
  4141. return lodash;
  4142. });
  4143. }
  4144. // check for `exports` after `define` in case a build optimizer adds an `exports` object
  4145. else if (freeExports) {
  4146. // in Node.js or RingoJS v0.8.0+
  4147. if (typeof module == 'object' && module && module.exports == freeExports) {
  4148. (module.exports = lodash)._ = lodash;
  4149. }
  4150. // in Narwhal or RingoJS v0.7.0-
  4151. else {
  4152. freeExports._ = lodash;
  4153. }
  4154. }
  4155. else {
  4156. // in a browser or Rhino
  4157. window._ = lodash;
  4158. }
  4159. }(this));