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

/ajax/libs//0.6.1/lodash.js

https://gitlab.com/Mirros/cdnjs
JavaScript | 1504 lines | 666 code | 126 blank | 712 comment | 221 complexity | 1f10ab2149d3be372539f5e775013893 MD5 | raw file
  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 token = '__token__';
  79. /** Used to store tokenized template text snippets */
  80. var tokenized = [];
  81. /** Native method shortcuts */
  82. var concat = ArrayProto.concat,
  83. hasOwnProperty = ObjectProto.hasOwnProperty,
  84. push = ArrayProto.push,
  85. propertyIsEnumerable = ObjectProto.propertyIsEnumerable,
  86. slice = ArrayProto.slice,
  87. toString = ObjectProto.toString;
  88. /* Native method shortcuts for methods with the same name as other `lodash` methods */
  89. var nativeBind = reNative.test(nativeBind = slice.bind) && nativeBind,
  90. nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
  91. nativeIsFinite = window.isFinite,
  92. nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys;
  93. /** `Object#toString` result shortcuts */
  94. var argsClass = '[object Arguments]',
  95. arrayClass = '[object Array]',
  96. boolClass = '[object Boolean]',
  97. dateClass = '[object Date]',
  98. funcClass = '[object Function]',
  99. numberClass = '[object Number]',
  100. objectClass = '[object Object]',
  101. regexpClass = '[object RegExp]',
  102. stringClass = '[object String]';
  103. /** Timer shortcuts */
  104. var clearTimeout = window.clearTimeout,
  105. setTimeout = window.setTimeout;
  106. /**
  107. * Detect the JScript [[DontEnum]] bug:
  108. *
  109. * In IE < 9 an objects own properties, shadowing non-enumerable ones, are
  110. * made non-enumerable as well.
  111. */
  112. var hasDontEnumBug;
  113. /**
  114. * Detect if `Array#shift` and `Array#splice` augment array-like objects
  115. * incorrectly:
  116. *
  117. * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()`
  118. * and `splice()` functions that fail to remove the last element, `value[0]`,
  119. * of array-like objects even though the `length` property is set to `0`.
  120. * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
  121. * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
  122. */
  123. var hasObjectSpliceBug;
  124. /** Detect if own properties are iterated after inherited properties (IE < 9) */
  125. var iteratesOwnLast;
  126. /** Detect if an `arguments` object's indexes are non-enumerable (IE < 9) */
  127. var noArgsEnum = true;
  128. (function() {
  129. var object = { '0': 1, 'length': 1 },
  130. props = [];
  131. function ctor() { this.x = 1; }
  132. ctor.prototype = { 'valueOf': 1, 'y': 1 };
  133. for (var prop in new ctor) { props.push(prop); }
  134. for (prop in arguments) { noArgsEnum = !prop; }
  135. hasDontEnumBug = (props + '').length < 4;
  136. iteratesOwnLast = props[0] != 'x';
  137. hasObjectSpliceBug = (props.splice.call(object, 0, 1), object[0]);
  138. }(1));
  139. /** Detect if an `arguments` object's [[Class]] is unresolvable (Firefox < 4, IE < 9) */
  140. var noArgsClass = !isArguments(arguments);
  141. /** Detect if `Array#slice` cannot be used to convert strings to arrays (Opera < 10.52) */
  142. var noArraySliceOnStrings = slice.call('x')[0] != 'x';
  143. /**
  144. * Detect lack of support for accessing string characters by index:
  145. *
  146. * IE < 8 can't access characters by index and IE 8 can only access
  147. * characters by index on string literals.
  148. */
  149. var noCharByIndex = ('x'[0] + Object('x')[0]) != 'xx';
  150. /**
  151. * Detect if a node's [[Class]] is unresolvable (IE < 9)
  152. * and that the JS engine won't error when attempting to coerce an object to
  153. * a string without a `toString` property value of `typeof` "function".
  154. */
  155. try {
  156. var noNodeClass = ({ 'toString': 0 } + '', toString.call(window.document || 0) == objectClass);
  157. } catch(e) { }
  158. /* Detect if `Function#bind` exists and is inferred to be fast (all but V8) */
  159. var isBindFast = nativeBind && /\n|Opera/.test(nativeBind + toString.call(window.opera));
  160. /* Detect if `Object.keys` exists and is inferred to be fast (IE, Opera, V8) */
  161. var isKeysFast = nativeKeys && /^.+$|true/.test(nativeKeys + !!window.attachEvent);
  162. /* Detect if strict mode, "use strict", is inferred to be fast (V8) */
  163. var isStrictFast = !isBindFast;
  164. /**
  165. * Detect if sourceURL syntax is usable without erroring:
  166. *
  167. * The JS engine in Adobe products, like InDesign, will throw a syntax error
  168. * when it encounters a single line comment beginning with the `@` symbol.
  169. *
  170. * The JS engine in Narwhal will generate the function `function anonymous(){//}`
  171. * and throw a syntax error.
  172. *
  173. * Avoid comments beginning `@` symbols in IE because they are part of its
  174. * non-standard conditional compilation support.
  175. * http://msdn.microsoft.com/en-us/library/121hztk3(v=vs.94).aspx
  176. */
  177. try {
  178. var useSourceURL = (Function('//@')(), !window.attachEvent);
  179. } catch(e){ }
  180. /** Used to identify object classifications that are array-like */
  181. var arrayLikeClasses = {};
  182. arrayLikeClasses[boolClass] = arrayLikeClasses[dateClass] = arrayLikeClasses[funcClass] =
  183. arrayLikeClasses[numberClass] = arrayLikeClasses[objectClass] = arrayLikeClasses[regexpClass] = false;
  184. arrayLikeClasses[argsClass] = arrayLikeClasses[arrayClass] = arrayLikeClasses[stringClass] = true;
  185. /** Used to identify object classifications that `_.clone` supports */
  186. var cloneableClasses = {};
  187. cloneableClasses[argsClass] = cloneableClasses[funcClass] = false;
  188. cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] =
  189. cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] =
  190. cloneableClasses[stringClass] = true;
  191. /**
  192. * Used to convert characters to HTML entities:
  193. *
  194. * Though the `>` character is escaped for symmetry, characters like `>` and `/`
  195. * don't require escaping in HTML and have no special meaning unless they're part
  196. * of a tag or an unquoted attribute value.
  197. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
  198. */
  199. var htmlEscapes = {
  200. '&': '&amp;',
  201. '<': '&lt;',
  202. '>': '&gt;',
  203. '"': '&quot;',
  204. "'": '&#x27;'
  205. };
  206. /** Used to convert HTML entities to characters */
  207. var htmlUnescapes = {
  208. '&amp;': '&',
  209. '&lt;': '<',
  210. '&gt;': '>',
  211. '&quot;': '"',
  212. '&#x27;': "'"
  213. };
  214. /** Used to determine if values are of the language type Object */
  215. var objectTypes = {
  216. 'boolean': false,
  217. 'function': true,
  218. 'object': true,
  219. 'number': false,
  220. 'string': false,
  221. 'undefined': false,
  222. 'unknown': true
  223. };
  224. /** Used to escape characters for inclusion in compiled string literals */
  225. var stringEscapes = {
  226. '\\': '\\',
  227. "'": "'",
  228. '\n': 'n',
  229. '\r': 'r',
  230. '\t': 't',
  231. '\u2028': 'u2028',
  232. '\u2029': 'u2029'
  233. };
  234. /*--------------------------------------------------------------------------*/
  235. /**
  236. * The `lodash` function.
  237. *
  238. * @name _
  239. * @constructor
  240. * @param {Mixed} value The value to wrap in a `LoDash` instance.
  241. * @returns {Object} Returns a `LoDash` instance.
  242. */
  243. function lodash(value) {
  244. // allow invoking `lodash` without the `new` operator
  245. return new LoDash(value);
  246. }
  247. /**
  248. * Creates a `LoDash` instance that wraps a value to allow chaining.
  249. *
  250. * @private
  251. * @constructor
  252. * @param {Mixed} value The value to wrap.
  253. */
  254. function LoDash(value) {
  255. // exit early if already wrapped
  256. if (value && value._wrapped) {
  257. return value;
  258. }
  259. this._wrapped = value;
  260. }
  261. /**
  262. * By default, the template delimiters used by Lo-Dash are similar to those in
  263. * embedded Ruby (ERB). Change the following template settings to use alternative
  264. * delimiters.
  265. *
  266. * @static
  267. * @memberOf _
  268. * @type Object
  269. */
  270. lodash.templateSettings = {
  271. /**
  272. * Used to detect `data` property values to be HTML-escaped.
  273. *
  274. * @static
  275. * @memberOf _.templateSettings
  276. * @type RegExp
  277. */
  278. 'escape': /<%-([\s\S]+?)%>/g,
  279. /**
  280. * Used to detect code to be evaluated.
  281. *
  282. * @static
  283. * @memberOf _.templateSettings
  284. * @type RegExp
  285. */
  286. 'evaluate': /<%([\s\S]+?)%>/g,
  287. /**
  288. * Used to detect `data` property values to inject.
  289. *
  290. * @static
  291. * @memberOf _.templateSettings
  292. * @type RegExp
  293. */
  294. 'interpolate': /<%=([\s\S]+?)%>/g,
  295. /**
  296. * Used to reference the data object in the template text.
  297. *
  298. * @static
  299. * @memberOf _.templateSettings
  300. * @type String
  301. */
  302. 'variable': ''
  303. };
  304. /*--------------------------------------------------------------------------*/
  305. /**
  306. * The template used to create iterator functions.
  307. *
  308. * @private
  309. * @param {Obect} data The data object used to populate the text.
  310. * @returns {String} Returns the interpolated text.
  311. */
  312. var iteratorTemplate = template(
  313. // conditional strict mode
  314. '<% if (useStrict) { %>\'use strict\';\n<% } %>' +
  315. // the `iteratee` may be reassigned by the `top` snippet
  316. 'var index, value, iteratee = <%= firstArg %>, ' +
  317. // assign the `result` variable an initial value
  318. 'result<% if (init) { %> = <%= init %><% } %>;\n' +
  319. // add code to exit early or do so if the first argument is falsey
  320. '<%= exit %>;\n' +
  321. // add code after the exit snippet but before the iteration branches
  322. '<%= top %>;\n' +
  323. // the following branch is for iterating arrays and array-like objects
  324. '<% if (arrayBranch) { %>' +
  325. 'var length = iteratee.length; index = -1;' +
  326. ' <% if (objectBranch) { %>\nif (length > -1 && length === length >>> 0) {<% } %>' +
  327. // add support for accessing string characters by index if needed
  328. ' <% if (noCharByIndex) { %>\n' +
  329. ' if (toString.call(iteratee) == stringClass) {\n' +
  330. ' iteratee = iteratee.split(\'\')\n' +
  331. ' }' +
  332. ' <% } %>\n' +
  333. ' <%= arrayBranch.beforeLoop %>;\n' +
  334. ' while (++index < length) {\n' +
  335. ' value = iteratee[index];\n' +
  336. ' <%= arrayBranch.inLoop %>\n' +
  337. ' }' +
  338. ' <% if (objectBranch) { %>\n}<% } %>' +
  339. '<% } %>' +
  340. // the following branch is for iterating an object's own/inherited properties
  341. '<% if (objectBranch) { %>' +
  342. ' <% if (arrayBranch) { %>\nelse {' +
  343. // add support for iterating over `arguments` objects if needed
  344. ' <% } else if (noArgsEnum) { %>\n' +
  345. ' var length = iteratee.length; index = -1;\n' +
  346. ' if (length && isArguments(iteratee)) {\n' +
  347. ' while (++index < length) {\n' +
  348. ' value = iteratee[index += \'\'];\n' +
  349. ' <%= objectBranch.inLoop %>\n' +
  350. ' }\n' +
  351. ' } else {' +
  352. ' <% } %>' +
  353. // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
  354. // (if the prototype or a property on the prototype has been set)
  355. // incorrectly sets a function's `prototype` property [[Enumerable]]
  356. // value to `true`. Because of this Lo-Dash standardizes on skipping
  357. // the the `prototype` property of functions regardless of its
  358. // [[Enumerable]] value.
  359. ' <% if (!hasDontEnumBug) { %>\n' +
  360. ' var skipProto = typeof iteratee == \'function\' && \n' +
  361. ' propertyIsEnumerable.call(iteratee, \'prototype\');\n' +
  362. ' <% } %>' +
  363. // iterate own properties using `Object.keys` if it's fast
  364. ' <% if (isKeysFast && useHas) { %>\n' +
  365. ' var ownIndex = -1,\n' +
  366. ' ownProps = objectTypes[typeof iteratee] ? nativeKeys(iteratee) : [],\n' +
  367. ' length = ownProps.length;\n\n' +
  368. ' <%= objectBranch.beforeLoop %>;\n' +
  369. ' while (++ownIndex < length) {\n' +
  370. ' index = ownProps[ownIndex];\n' +
  371. ' <% if (!hasDontEnumBug) { %>if (!(skipProto && index == \'prototype\')) {\n <% } %>' +
  372. ' value = iteratee[index];\n' +
  373. ' <%= objectBranch.inLoop %>\n' +
  374. ' <% if (!hasDontEnumBug) { %>}\n<% } %>' +
  375. ' }' +
  376. // else using a for-in loop
  377. ' <% } else { %>\n' +
  378. ' <%= objectBranch.beforeLoop %>;\n' +
  379. ' for (index in iteratee) {' +
  380. ' <% if (!hasDontEnumBug || useHas) { %>\n if (<%' +
  381. ' if (!hasDontEnumBug) { %>!(skipProto && index == \'prototype\')<% }' +
  382. ' if (!hasDontEnumBug && useHas) { %> && <% }' +
  383. ' if (useHas) { %>hasOwnProperty.call(iteratee, index)<% }' +
  384. ' %>) {' +
  385. ' <% } %>\n' +
  386. ' value = iteratee[index];\n' +
  387. ' <%= objectBranch.inLoop %>;\n' +
  388. ' <% if (!hasDontEnumBug || useHas) { %>}\n<% } %>' +
  389. ' }' +
  390. ' <% } %>' +
  391. // Because IE < 9 can't set the `[[Enumerable]]` attribute of an
  392. // existing property and the `constructor` property of a prototype
  393. // defaults to non-enumerable, Lo-Dash skips the `constructor`
  394. // property when it infers it's iterating over a `prototype` object.
  395. ' <% if (hasDontEnumBug) { %>\n\n' +
  396. ' var ctor = iteratee.constructor;\n' +
  397. ' <% for (var k = 0; k < 7; k++) { %>\n' +
  398. ' index = \'<%= shadowed[k] %>\';\n' +
  399. ' if (<%' +
  400. ' if (shadowed[k] == \'constructor\') {' +
  401. ' %>!(ctor && ctor.prototype === iteratee) && <%' +
  402. ' } %>hasOwnProperty.call(iteratee, index)) {\n' +
  403. ' value = iteratee[index];\n' +
  404. ' <%= objectBranch.inLoop %>\n' +
  405. ' }' +
  406. ' <% } %>' +
  407. ' <% } %>' +
  408. ' <% if (arrayBranch || noArgsEnum) { %>\n}<% } %>' +
  409. '<% } %>\n' +
  410. // add code to the bottom of the iteration function
  411. '<%= bottom %>;\n' +
  412. // finally, return the `result`
  413. 'return result'
  414. );
  415. /**
  416. * Reusable iterator options shared by
  417. * `every`, `filter`, `find`, `forEach`, `forIn`, `forOwn`, `groupBy`, `map`,
  418. * `reject`, `some`, and `sortBy`.
  419. */
  420. var baseIteratorOptions = {
  421. 'args': 'collection, callback, thisArg',
  422. 'init': 'collection',
  423. 'top':
  424. 'if (!callback) {\n' +
  425. ' callback = identity\n' +
  426. '}\n' +
  427. 'else if (thisArg) {\n' +
  428. ' callback = iteratorBind(callback, thisArg)\n' +
  429. '}',
  430. 'inLoop': 'if (callback(value, index, collection) === false) return result'
  431. };
  432. /** Reusable iterator options for `countBy`, `groupBy`, and `sortBy` */
  433. var countByIteratorOptions = {
  434. 'init': '{}',
  435. 'top':
  436. 'var prop;\n' +
  437. 'if (typeof callback != \'function\') {\n' +
  438. ' var valueProp = callback;\n' +
  439. ' callback = function(value) { return value[valueProp] }\n' +
  440. '}\n' +
  441. 'else if (thisArg) {\n' +
  442. ' callback = iteratorBind(callback, thisArg)\n' +
  443. '}',
  444. 'inLoop':
  445. 'prop = callback(value, index, collection);\n' +
  446. '(hasOwnProperty.call(result, prop) ? result[prop]++ : result[prop] = 1)'
  447. };
  448. /** Reusable iterator options for `drop` and `pick` */
  449. var dropIteratorOptions = {
  450. 'useHas': false,
  451. 'args': 'object, callback, thisArg',
  452. 'init': '{}',
  453. 'top':
  454. 'var isFunc = typeof callback == \'function\';\n' +
  455. 'if (!isFunc) {\n' +
  456. ' var props = concat.apply(ArrayProto, arguments)\n' +
  457. '} else if (thisArg) {\n' +
  458. ' callback = iteratorBind(callback, thisArg)\n' +
  459. '}',
  460. 'inLoop':
  461. 'if (isFunc\n' +
  462. ' ? !callback(value, index, object)\n' +
  463. ' : indexOf(props, index) < 0\n' +
  464. ') result[index] = value'
  465. };
  466. /** Reusable iterator options for `every` and `some` */
  467. var everyIteratorOptions = {
  468. 'init': 'true',
  469. 'inLoop': 'if (!callback(value, index, collection)) return !result'
  470. };
  471. /** Reusable iterator options for `defaults` and `extend` */
  472. var extendIteratorOptions = {
  473. 'useHas': false,
  474. 'useStrict': false,
  475. 'args': 'object',
  476. 'init': 'object',
  477. 'top':
  478. 'for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {\n' +
  479. ' if (iteratee = arguments[argsIndex]) {',
  480. 'inLoop': 'result[index] = value',
  481. 'bottom': ' }\n}'
  482. };
  483. /** Reusable iterator options for `filter`, `reject`, and `where` */
  484. var filterIteratorOptions = {
  485. 'init': '[]',
  486. 'inLoop': 'callback(value, index, collection) && result.push(value)'
  487. };
  488. /** Reusable iterator options for `find`, `forEach`, `forIn`, and `forOwn` */
  489. var forEachIteratorOptions = {
  490. 'top': 'if (thisArg) callback = iteratorBind(callback, thisArg)'
  491. };
  492. /** Reusable iterator options for `forIn` and `forOwn` */
  493. var forOwnIteratorOptions = {
  494. 'inLoop': {
  495. 'object': baseIteratorOptions.inLoop
  496. }
  497. };
  498. /** Reusable iterator options for `invoke`, `map`, `pluck`, and `sortBy` */
  499. var mapIteratorOptions = {
  500. 'init': '',
  501. 'exit': 'if (!collection) return []',
  502. 'beforeLoop': {
  503. 'array': 'result = Array(length)',
  504. 'object': 'result = ' + (isKeysFast ? 'Array(length)' : '[]')
  505. },
  506. 'inLoop': {
  507. 'array': 'result[index] = callback(value, index, collection)',
  508. 'object': 'result' + (isKeysFast ? '[ownIndex] = ' : '.push') + '(callback(value, index, collection))'
  509. }
  510. };
  511. /*--------------------------------------------------------------------------*/
  512. /**
  513. * Creates a new function optimized for searching large arrays for a given `value`,
  514. * starting at `fromIndex`, using strict equality for comparisons, i.e. `===`.
  515. *
  516. * @private
  517. * @param {Array} array The array to search.
  518. * @param {Mixed} value The value to search for.
  519. * @param {Number} [fromIndex=0] The index to start searching from.
  520. * @param {Number} [largeSize=30] The length at which an array is considered large.
  521. * @returns {Boolean} Returns `true` if `value` is found, else `false`.
  522. */
  523. function cachedContains(array, fromIndex, largeSize) {
  524. fromIndex || (fromIndex = 0);
  525. var length = array.length,
  526. isLarge = (length - fromIndex) >= (largeSize || largeArraySize),
  527. cache = isLarge ? {} : array;
  528. if (isLarge) {
  529. // init value cache
  530. var key,
  531. index = fromIndex - 1;
  532. while (++index < length) {
  533. // manually coerce `value` to string because `hasOwnProperty`, in some
  534. // older versions of Firefox, coerces objects incorrectly
  535. key = array[index] + '';
  536. (hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = [])).push(array[index]);
  537. }
  538. }
  539. return function(value) {
  540. if (isLarge) {
  541. var key = value + '';
  542. return hasOwnProperty.call(cache, key) && indexOf(cache[key], value) > -1;
  543. }
  544. return indexOf(cache, value, fromIndex) > -1;
  545. }
  546. }
  547. /**
  548. * Creates compiled iteration functions. The iteration function will be created
  549. * to iterate over only objects if the first argument of `options.args` is
  550. * "object" or `options.inLoop.array` is falsey.
  551. *
  552. * @private
  553. * @param {Object} [options1, options2, ...] The compile options objects.
  554. *
  555. * useHas - A boolean to specify whether or not to use `hasOwnProperty` checks
  556. * in the object loop.
  557. *
  558. * useStrict - A boolean to specify whether or not to include the ES5
  559. * "use strict" directive.
  560. *
  561. * args - A string of comma separated arguments the iteration function will
  562. * accept.
  563. *
  564. * init - A string to specify the initial value of the `result` variable.
  565. *
  566. * exit - A string of code to use in place of the default exit-early check
  567. * of `if (!arguments[0]) return result`.
  568. *
  569. * top - A string of code to execute after the exit-early check but before
  570. * the iteration branches.
  571. *
  572. * beforeLoop - A string or object containing an "array" or "object" property
  573. * of code to execute before the array or object loops.
  574. *
  575. * inLoop - A string or object containing an "array" or "object" property
  576. * of code to execute in the array or object loops.
  577. *
  578. * bottom - A string of code to execute after the iteration branches but
  579. * before the `result` is returned.
  580. *
  581. * @returns {Function} Returns the compiled function.
  582. */
  583. function createIterator() {
  584. var object,
  585. prop,
  586. value,
  587. index = -1,
  588. length = arguments.length;
  589. // merge options into a template data object
  590. var data = {
  591. 'bottom': '',
  592. 'exit': '',
  593. 'init': '',
  594. 'top': '',
  595. 'arrayBranch': { 'beforeLoop': '' },
  596. 'objectBranch': { 'beforeLoop': '' }
  597. };
  598. while (++index < length) {
  599. object = arguments[index];
  600. for (prop in object) {
  601. value = (value = object[prop]) == null ? '' : value;
  602. // keep this regexp explicit for the build pre-process
  603. if (/beforeLoop|inLoop/.test(prop)) {
  604. if (typeof value == 'string') {
  605. value = { 'array': value, 'object': value };
  606. }
  607. data.arrayBranch[prop] = value.array || '';
  608. data.objectBranch[prop] = value.object || '';
  609. } else {
  610. data[prop] = value;
  611. }
  612. }
  613. }
  614. // set additional template `data` values
  615. var args = data.args,
  616. firstArg = /^[^,]+/.exec(args)[0],
  617. useStrict = data.useStrict;
  618. data.firstArg = firstArg;
  619. data.hasDontEnumBug = hasDontEnumBug;
  620. data.isKeysFast = isKeysFast;
  621. data.noArgsEnum = noArgsEnum;
  622. data.shadowed = shadowed;
  623. data.useHas = data.useHas !== false;
  624. data.useStrict = useStrict == null ? isStrictFast : useStrict;
  625. if (data.noCharByIndex == null) {
  626. data.noCharByIndex = noCharByIndex;
  627. }
  628. if (!data.exit) {
  629. data.exit = 'if (!' + firstArg + ') return result';
  630. }
  631. if (firstArg != 'collection' || !data.arrayBranch.inLoop) {
  632. data.arrayBranch = null;
  633. }
  634. // create the function factory
  635. var factory = Function(
  636. 'arrayLikeClasses, ArrayProto, bind, compareAscending, concat, forIn, ' +
  637. 'hasOwnProperty, identity, indexOf, isArguments, isArray, isFunction, ' +
  638. 'isPlainObject, iteratorBind, objectClass, objectTypes, nativeKeys, ' +
  639. 'propertyIsEnumerable, slice, stringClass, toString',
  640. 'var callee = function(' + args + ') {\n' + iteratorTemplate(data) + '\n};\n' +
  641. 'return callee'
  642. );
  643. // return the compiled function
  644. return factory(
  645. arrayLikeClasses, ArrayProto, bind, compareAscending, concat, forIn,
  646. hasOwnProperty, identity, indexOf, isArguments, isArray, isFunction,
  647. isPlainObject, iteratorBind, objectClass, objectTypes, nativeKeys,
  648. propertyIsEnumerable, slice, stringClass, toString
  649. );
  650. }
  651. /**
  652. * Used by `sortBy` to compare transformed `collection` values, stable sorting
  653. * them in ascending order.
  654. *
  655. * @private
  656. * @param {Object} a The object to compare to `b`.
  657. * @param {Object} b The object to compare to `a`.
  658. * @returns {Number} Returns the sort order indicator of `1` or `-1`.
  659. */
  660. function compareAscending(a, b) {
  661. var ai = a.index,
  662. bi = b.index;
  663. a = a.criteria;
  664. b = b.criteria;
  665. if (a === undefined) {
  666. return 1;
  667. }
  668. if (b === undefined) {
  669. return -1;
  670. }
  671. // ensure a stable sort in V8 and other engines
  672. // http://code.google.com/p/v8/issues/detail?id=90
  673. return a < b ? -1 : a > b ? 1 : ai < bi ? -1 : 1;
  674. }
  675. /**
  676. * Used by `template` to replace tokens with their corresponding code snippets.
  677. *
  678. * @private
  679. * @param {String} match The matched token.
  680. * @param {String} index The `tokenized` index of the code snippet.
  681. * @returns {String} Returns the code snippet.
  682. */
  683. function detokenize(match, index) {
  684. return tokenized[index];
  685. }
  686. /**
  687. * Used by `template` to escape characters for inclusion in compiled
  688. * string literals.
  689. *
  690. * @private
  691. * @param {String} match The matched character to escape.
  692. * @returns {String} Returns the escaped character.
  693. */
  694. function escapeStringChar(match) {
  695. return '\\' + stringEscapes[match];
  696. }
  697. /**
  698. * Used by `escape` to convert characters to HTML entities.
  699. *
  700. * @private
  701. * @param {String} match The matched character to escape.
  702. * @returns {String} Returns the escaped character.
  703. */
  704. function escapeHtmlChar(match) {
  705. return htmlEscapes[match];
  706. }
  707. /**
  708. * Creates a new function that, when called, invokes `func` with the `this`
  709. * binding of `thisArg` and the arguments (value, index, object).
  710. *
  711. * @private
  712. * @param {Function} func The function to bind.
  713. * @param {Mixed} [thisArg] The `this` binding of `func`.
  714. * @returns {Function} Returns the new bound function.
  715. */
  716. function iteratorBind(func, thisArg) {
  717. return function(value, index, object) {
  718. return func.call(thisArg, value, index, object);
  719. };
  720. }
  721. /**
  722. * A no-operation function.
  723. *
  724. * @private
  725. */
  726. function noop() {
  727. // no operation performed
  728. }
  729. /**
  730. * Used by `template` to replace "escape" template delimiters with tokens.
  731. *
  732. * @private
  733. * @param {String} match The matched template delimiter.
  734. * @param {String} value The delimiter value.
  735. * @returns {String} Returns a token.
  736. */
  737. function tokenizeEscape(match, value) {
  738. if (match && reComplexDelimiter.test(value)) {
  739. return '<e%-' + value + '%>';
  740. }
  741. var index = tokenized.length;
  742. tokenized[index] = "' +\n__e(" + value + ") +\n'";
  743. return token + index;
  744. }
  745. /**
  746. * Used by `template` to replace "evaluate" template delimiters, or complex
  747. * "escape" and "interpolate" delimiters, with tokens.
  748. *
  749. * @private
  750. * @param {String} match The matched template delimiter.
  751. * @param {String} escapeValue The complex "escape" delimiter value.
  752. * @param {String} interpolateValue The complex "interpolate" delimiter value.
  753. * @param {String} [evaluateValue] The "evaluate" delimiter value.
  754. * @returns {String} Returns a token.
  755. */
  756. function tokenizeEvaluate(match, escapeValue, interpolateValue, evaluateValue) {
  757. if (evaluateValue) {
  758. var index = tokenized.length;
  759. tokenized[index] = "';\n" + evaluateValue + ";\n__p += '";
  760. return token + index;
  761. }
  762. return escapeValue
  763. ? tokenizeEscape(null, escapeValue)
  764. : tokenizeInterpolate(null, interpolateValue);
  765. }
  766. /**
  767. * Used by `template` to replace "interpolate" template delimiters with tokens.
  768. *
  769. * @private
  770. * @param {String} match The matched template delimiter.
  771. * @param {String} value The delimiter value.
  772. * @returns {String} Returns a token.
  773. */
  774. function tokenizeInterpolate(match, value) {
  775. if (match && reComplexDelimiter.test(value)) {
  776. return '<e%=' + value + '%>';
  777. }
  778. var index = tokenized.length;
  779. tokenized[index] = "' +\n((__t = (" + value + ")) == null ? '' : __t) +\n'";
  780. return token + index;
  781. }
  782. /**
  783. * Used by `unescape` to convert HTML entities to characters.
  784. *
  785. * @private
  786. * @param {String} match The matched character to unescape.
  787. * @returns {String} Returns the unescaped character.
  788. */
  789. function unescapeHtmlChar(match) {
  790. return htmlUnescapes[match];
  791. }
  792. /*--------------------------------------------------------------------------*/
  793. /**
  794. * Checks if `value` is an `arguments` object.
  795. *
  796. * @static
  797. * @memberOf _
  798. * @category Objects
  799. * @param {Mixed} value The value to check.
  800. * @returns {Boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
  801. * @example
  802. *
  803. * (function() { return _.isArguments(arguments); })(1, 2, 3);
  804. * // => true
  805. *
  806. * _.isArguments([1, 2, 3]);
  807. * // => false
  808. */
  809. function isArguments(value) {
  810. return toString.call(value) == argsClass;
  811. }
  812. // fallback for browsers that can't detect `arguments` objects by [[Class]]
  813. if (noArgsClass) {
  814. isArguments = function(value) {
  815. return !!(value && hasOwnProperty.call(value, 'callee'));
  816. };
  817. }
  818. /**
  819. * Checks if `value` is an array.
  820. *
  821. * @static
  822. * @memberOf _
  823. * @category Objects
  824. * @param {Mixed} value The value to check.
  825. * @returns {Boolean} Returns `true` if the `value` is an array, else `false`.
  826. * @example
  827. *
  828. * (function() { return _.isArray(arguments); })();
  829. * // => false
  830. *
  831. * _.isArray([1, 2, 3]);
  832. * // => true
  833. */
  834. var isArray = nativeIsArray || function(value) {
  835. return toString.call(value) == arrayClass;
  836. };
  837. /**
  838. * Checks if `value` is a function.
  839. *
  840. * @static
  841. * @memberOf _
  842. * @category Objects
  843. * @param {Mixed} value The value to check.
  844. * @returns {Boolean} Returns `true` if the `value` is a function, else `false`.
  845. * @example
  846. *
  847. * _.isFunction(''.concat);
  848. * // => true
  849. */
  850. function isFunction(value) {
  851. return typeof value == 'function';
  852. }
  853. // fallback for older versions of Chrome and Safari
  854. if (isFunction(/x/)) {
  855. isFunction = function(value) {
  856. return toString.call(value) == funcClass;
  857. };
  858. }
  859. /**
  860. * Checks if a given `value` is an object created by the `Object` constructor
  861. * assuming objects created by the `Object` constructor have no inherited
  862. * enumerable properties and that there are no `Object.prototype` extensions.
  863. *
  864. * @private
  865. * @param {Mixed} value The value to check.
  866. * @param {Boolean} [skipArgsCheck=false] Internally used to skip checks for
  867. * `arguments` objects.
  868. * @returns {Boolean} Returns `true` if the `value` is a plain `Object` object,
  869. * else `false`.
  870. */
  871. function isPlainObject(value, skipArgsCheck) {
  872. return value
  873. ? value == ObjectProto || (value.__proto__ == ObjectProto && (skipArgsCheck || !isArguments(value)))
  874. : false;
  875. }
  876. // fallback for IE
  877. if (!isPlainObject(objectTypes)) {
  878. isPlainObject = function(value, skipArgsCheck) {
  879. // avoid non-objects and false positives for `arguments` objects
  880. var result = false;
  881. if (!(value && typeof value == 'object') || (!skipArgsCheck && isArguments(value))) {
  882. return result;
  883. }
  884. // IE < 9 presents DOM nodes as `Object` objects except they have `toString`
  885. // methods that are `typeof` "string" and still can coerce nodes to strings.
  886. // Also check that the constructor is `Object` (i.e. `Object instanceof Object`)
  887. var ctor = value.constructor;
  888. if ((!noNodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) &&
  889. (!isFunction(ctor) || ctor instanceof ctor)) {
  890. // IE < 9 iterates inherited properties before own properties. If the first
  891. // iterated property is an object's own property then there are no inherited
  892. // enumerable properties.
  893. if (iteratesOwnLast) {
  894. forIn(value, function(objValue, objKey) {
  895. result = !hasOwnProperty.call(value, objKey);
  896. return false;
  897. });
  898. return result === false;
  899. }
  900. // In most environments an object's own properties are iterated before
  901. // its inherited properties. If the last iterated property is an object's
  902. // own property then there are no inherited enumerable properties.
  903. forIn(value, function(objValue, objKey) {
  904. result = objKey;
  905. });
  906. return result === false || hasOwnProperty.call(value, result);
  907. }
  908. return result;
  909. };
  910. }
  911. /**
  912. * A shim implementation of `Object.keys` that produces an array of the given
  913. * object's own enumerable property names.
  914. *
  915. * @private
  916. * @param {Object} object The object to inspect.
  917. * @returns {Array} Returns a new array of property names.
  918. */
  919. var shimKeys = createIterator({
  920. 'args': 'object',
  921. 'init': '[]',
  922. 'inLoop': 'result.push(index)'
  923. });
  924. /*--------------------------------------------------------------------------*/
  925. /**
  926. * Creates a clone of `value`. If `deep` is `true`, all nested objects will
  927. * also be cloned otherwise they will be assigned by reference. If a value has
  928. * a `clone` method it will be used to perform the clone. Functions, DOM nodes,
  929. * `arguments` objects, and objects created by constructors other than `Object`
  930. * are **not** cloned unless they have a custom `clone` method.
  931. *
  932. * @static
  933. * @memberOf _
  934. * @category Objects
  935. * @param {Mixed} value The value to clone.
  936. * @param {Boolean} deep A flag to indicate a deep clone.
  937. * @param {Object} [guard] Internally used to allow this method to work with
  938. * others like `_.map` without using their callback `index` argument for `deep`.
  939. * @param {Array} [stack=[]] Internally used to keep track of traversed objects
  940. * to avoid circular references.
  941. * @param {Object} thorough Internally used to indicate whether or not to perform
  942. * a more thorough clone of non-object values.
  943. * @returns {Mixed} Returns the cloned `value`.
  944. * @example
  945. *
  946. * var stooges = [
  947. * { 'name': 'moe', 'age': 40 },
  948. * { 'name': 'larry', 'age': 50 },
  949. * { 'name': 'curly', 'age': 60 }
  950. * ];
  951. *
  952. * _.clone({ 'name': 'moe' });
  953. * // => { 'name': 'moe' }
  954. *
  955. * var shallow = _.clone(stooges);
  956. * shallow[0] === stooges[0];
  957. * // => true
  958. *
  959. * var deep = _.clone(stooges, true);
  960. * shallow[0] === stooges[0];
  961. * // => false
  962. */
  963. function clone(value, deep, guard, stack, thorough) {
  964. if (value == null) {
  965. return value;
  966. }
  967. if (guard) {
  968. deep = false;
  969. }
  970. // avoid slower checks on primitives
  971. thorough || (thorough = { 'value': null });
  972. if (thorough.value == null) {
  973. // primitives passed from iframes use the primary document's native prototypes
  974. thorough.value = !!(BoolProto.clone || NumberProto.clone || StringProto.clone);
  975. }
  976. // use custom `clone` method if available
  977. var isObj = objectTypes[typeof value];
  978. if ((isObj || thorough.value) && value.clone && isFunction(value.clone)) {
  979. thorough.value = null;
  980. return value.clone(deep);
  981. }
  982. // inspect [[Class]]
  983. if (isObj) {
  984. // don't clone `arguments` objects, functions, or non-object Objects
  985. var className = toString.call(value);
  986. if (!cloneableClasses[className] || (noArgsClass && isArguments(value))) {
  987. return value;
  988. }
  989. var isArr = className == arrayClass;
  990. isObj = isArr || (className == objectClass ? isPlainObject(value, true) : isObj);
  991. }
  992. // shallow clone
  993. if (!isObj || !deep) {
  994. // don't clone functions
  995. return isObj
  996. ? (isArr ? slice.call(value) : extend({}, value))
  997. : value;
  998. }
  999. var ctor = value.constructor;
  1000. switch (className) {
  1001. case boolClass:
  1002. return new ctor(value == true);
  1003. case dateClass:
  1004. return new ctor(+value);
  1005. case numberClass:
  1006. case stringClass:
  1007. return new ctor(value);
  1008. case regexpClass:
  1009. return ctor(value.source, reFlags.exec(value));
  1010. }
  1011. // check for circular references and return corresponding clone
  1012. stack || (stack = []);
  1013. var length = stack.length;
  1014. while (length--) {
  1015. if (stack[length].source == value) {
  1016. return stack[length].value;
  1017. }
  1018. }
  1019. // init cloned object
  1020. length = value.length;
  1021. var result = isArr ? ctor(length) : {};
  1022. // add current clone and original source value to the stack of traversed objects
  1023. stack.push({ 'value': result, 'source': value });
  1024. // recursively populate clone (susceptible to call stack limits)
  1025. if (isArr) {
  1026. var index = -1;
  1027. while (++index < length) {
  1028. result[index] = clone(value[index], deep, null, stack, thorough);
  1029. }
  1030. } else {
  1031. forOwn(value, function(objValue, key) {
  1032. result[key] = clone(objValue, deep, null, stack, thorough);
  1033. });
  1034. }
  1035. return result;
  1036. }
  1037. /**
  1038. * Assigns enumerable properties of the default object(s) to the `destination`
  1039. * object for all `destination` properties that resolve to `null`/`undefined`.
  1040. * Once a property is set, additional defaults of the same property will be
  1041. * ignored.
  1042. *
  1043. * @static
  1044. * @memberOf _
  1045. * @category Objects
  1046. * @param {Object} object The destination object.
  1047. * @param {Object} [default1, default2, ...] The default objects.
  1048. * @returns {Object} Returns the destination object.
  1049. * @example
  1050. *
  1051. * var iceCream = { 'flavor': 'chocolate' };
  1052. * _.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' });
  1053. * // => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' }
  1054. */
  1055. var defaults = createIterator(extendIteratorOptions, {
  1056. 'inLoop': 'if (result[index] == null) ' + extendIteratorOptions.inLoop
  1057. });
  1058. /**
  1059. * Creates a shallow clone of `object` excluding the specified properties.
  1060. * Property names may be specified as individual arguments or as arrays of
  1061. * property names. If `callback` is passed, it will be executed for each property
  1062. * in the `object`, dropping the properties `callback` returns truthy for. The
  1063. * `callback` is bound to `thisArg` and invoked with 3 arguments; (value, key, object).
  1064. *
  1065. * @static
  1066. * @memberOf _
  1067. * @alias omit
  1068. * @category Objects
  1069. * @param {Object} object The source object.
  1070. * @param {Function|String} callback|[prop1, prop2, ...] The properties to drop
  1071. * or the function called per iteration.
  1072. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1073. * @returns {Object} Returns an object without the dropped properties.
  1074. * @example
  1075. *
  1076. * _.drop({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'userid');
  1077. * // => { 'name': 'moe', 'age': 40 }
  1078. *
  1079. * _.drop({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) {
  1080. * return key.charAt(0) == '_';
  1081. * });
  1082. * // => { 'name': 'moe' }
  1083. */
  1084. var drop = createIterator(dropIteratorOptions);
  1085. /**
  1086. * Assigns enumerable properties of the source object(s) to the `destination`
  1087. * object. Subsequent sources will overwrite propery assignments of previous
  1088. * sources.
  1089. *
  1090. * @static
  1091. * @memberOf _
  1092. * @category Objects
  1093. * @param {Object} object The destination object.
  1094. * @param {Object} [source1, source2, ...] The source objects.
  1095. * @returns {Object} Returns the destination object.
  1096. * @example
  1097. *
  1098. * _.extend({ 'name': 'moe' }, { 'age': 40 });
  1099. * // => { 'name': 'moe', 'age': 40 }
  1100. */
  1101. var extend = createIterator(extendIteratorOptions);
  1102. /**
  1103. * Iterates over `object`'s own and inherited enumerable properties, executing
  1104. * the `callback` for each property. The `callback` is bound to `thisArg` and
  1105. * invoked with 3 arguments; (value, key, object). Callbacks may exit iteration
  1106. * early by explicitly returning `false`.
  1107. *
  1108. * @static
  1109. * @memberOf _
  1110. * @category Objects
  1111. * @param {Object} object The object to iterate over.
  1112. * @param {Function} callback The function called per iteration.
  1113. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1114. * @returns {Object} Returns `object`.
  1115. * @example
  1116. *
  1117. * function Dog(name) {
  1118. * this.name = name;
  1119. * }
  1120. *
  1121. * Dog.prototype.bark = function() {
  1122. * alert('Woof, woof!');
  1123. * };
  1124. *
  1125. * _.forIn(new Dog('Dagny'), function(value, key) {
  1126. * alert(key);
  1127. * });
  1128. * // => alerts 'name' and 'bark' (order is not guaranteed)
  1129. */
  1130. var forIn = createIterator(baseIteratorOptions, forEachIteratorOptions, forOwnIteratorOptions, {
  1131. 'useHas': false
  1132. });
  1133. /**
  1134. * Iterates over `object`'s own enumerable properties, executing the `callback`
  1135. * for each property. The `callback` is bound to `thisArg` and invoked with 3
  1136. * arguments; (value, key, object). Callbacks may exit iteration early by
  1137. * explicitly returning `false`.
  1138. *
  1139. * @static
  1140. * @memberOf _
  1141. * @category Objects
  1142. * @param {Object} object The object to iterate over.
  1143. * @param {Function} callback The function called per iteration.
  1144. * @param {Mixed} [thisArg] The `this` binding for the callback.
  1145. * @returns {Object} Returns `object`.
  1146. * @example
  1147. *
  1148. * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
  1149. * alert(key);
  1150. * });
  1151. * // => alerts '0', '1', and 'length' (order is not guaranteed)
  1152. */
  1153. var forOwn = createIterator(baseIteratorOptions, forEachIteratorOptions, forOwnIteratorOptions);
  1154. /**
  1155. * Creates a sorted array of all enumerable properties, own and inherited,
  1156. * of `object` that have function values.
  1157. *
  1158. * @static
  1159. * @memberOf _
  1160. * @alias methods
  1161. * @category Objects
  1162. * @param {Object} object The object to inspect.
  1163. * @returns {Array} Returns a new array of property names that have function values.
  1164. * @example
  1165. *
  1166. * _.functions(_);
  1167. * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
  1168. */
  1169. var functions = createIterator({
  1170. 'useHas': false,
  1171. 'args': 'object',
  1172. 'init': '[]',
  1173. 'inLoop': 'if (isFunction(value)) result.push(index)',
  1174. 'bottom': 'result.sort()'
  1175. });
  1176. /**
  1177. * Checks if the specified object `property` exists and is a direct property,
  1178. * instead of an inherited property.
  1179. *
  1180. * @static
  1181. * @memberOf _
  1182. * @category Objects
  1183. * @param {Object} object The object to check.
  1184. * @param {String} property The property to check for.
  1185. * @returns {Boolean} Returns `true` if key is a direct property, else `false`.
  1186. * @example
  1187. *
  1188. * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
  1189. * // => true
  1190. */
  1191. function has(object, property) {
  1192. return object ? hasOwnProperty.call(object, property) : false;
  1193. }
  1194. /**
  1195. * Checks if `value` is a boolean (`true` or `false`) value.
  1196. *
  1197. * @static
  1198. * @memberOf _
  1199. * @category Objects
  1200. * @param {Mixed} value The value to check.
  1201. * @returns {Boolean} Returns `true` if the `value` is a boolean value, else `false`.
  1202. * @example
  1203. *
  1204. * _.isBoolean(null);
  1205. * // => false
  1206. */
  1207. function isBoolean(value) {
  1208. return value === true || value === false || toString.call(value) == boolClass;
  1209. }
  1210. /**
  1211. * Checks if `value` is a date.
  1212. *
  1213. * @static
  1214. * @memberOf _
  1215. * @category Objects
  1216. * @param {Mixed} value The value to check.
  1217. * @returns {Boolean} Returns `true` if the `value` is a date, else `false`.
  1218. * @example
  1219. *
  1220. * _.isDate(new Date);
  1221. * // => true
  1222. */
  1223. function isDate(value) {
  1224. return toString.call(value) == dateClass;
  1225. }
  1226. /**
  1227. * Checks if `value` is a DOM element.
  1228. *
  1229. * @static
  1230. * @memberOf _
  1231. * @category Objects
  1232. * @param {Mixed} value The value to check.
  1233. * @returns {Boolean} Returns `true` if the `value` is a DOM element, else `false`.
  1234. * @example
  1235. *
  1236. * _.isElement(document.body);
  1237. * // => true
  1238. */
  1239. function isElement(value) {
  1240. return value ? value.nodeType === 1 : false;
  1241. }
  1242. /**
  1243. * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
  1244. * length of `0` and objects with no own enumerable properties are considered
  1245. * "empty".
  1246. *
  1247. * @static
  1248. * @memberOf _
  1249. * @category Objects
  1250. * @param {Array|Object|String} value The value to inspect.
  1251. * @returns {Boolean} Returns `true` if the `value` is empty, else `false`.
  1252. * @example
  1253. *
  1254. * _.isEmpty([1, 2, 3]);
  1255. * // => false
  1256. *
  1257. * _.isEmpty({});
  1258. * // => true
  1259. *
  1260. * _.isEmpty('');
  1261. * // => true
  1262. */
  1263. var isEmpty = createIterator({
  1264. 'args': 'value',
  1265. 'init': 'true',
  1266. 'top':
  1267. 'var className = toString.call(value),\n' +
  1268. ' length = value.length;\n' +
  1269. 'if (arrayLikeClasses[className]' +
  1270. (noArgsClass ? ' || isArguments(value)' : '') + ' ||\n' +
  1271. ' (className == objectClass && length > -1 && length === length >>> 0 &&\n' +
  1272. ' isFunction(value.splice))' +
  1273. ') return !length',
  1274. 'inLoop': {
  1275. 'object': 'return false'
  1276. }
  1277. });
  1278. /**
  1279. * Performs a deep comparison between two values to determine if they are
  1280. * equivalent to each other. If a value has an `isEqual` method it will be
  1281. * used to perform the comparison.
  1282. *
  1283. * @static
  1284. * @memberOf _
  1285. * @category Objects
  1286. * @param {Mixed} a The value to compare.
  1287. * @param {Mixed} b The other value to compare.
  1288. * @param {Array} [stack=[]] Internally used to keep track of traversed objects
  1289. * to avoid circular references.
  1290. * @param {Object} thorough Internally used to indicate whether or not to perform
  1291. * a more thorough comparison of non-object values.
  1292. * @returns {Boolean} Returns `true` if the values are equvalent, else `false`.
  1293. * @example
  1294. *
  1295. * var moe = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
  1296. * var clone = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
  1297. *
  1298. * moe == clone;
  1299. * // => false
  1300. *
  1301. * _.isEqual(moe, clone);
  1302. * // => true
  1303. */
  1304. function isEqual(a, b, stack, thorough) {
  1305. // a strict comparison is necessary because `null == undefined`
  1306. if (a == null || b == null) {
  1307. return a === b;
  1308. }
  1309. // avoid slower checks on non-objects
  1310. thorough || (thorough = { 'value': null });
  1311. if (thorough.value == null) {
  1312. // primitives passed from iframes use the primary document's native prototypes
  1313. thorough.value = !!(BoolProto.isEqual || NumberProto.isEqual || StringProto.isEqual);
  1314. }
  1315. if (objectTypes[typeof a] || objectTypes[typeof b] || thorough.value) {
  1316. // unwrap any LoDash wrapped values
  1317. if (a._chain) {
  1318. a = a._wrapped;
  1319. }
  1320. if (b._chain) {
  1321. b = b._wrapped;
  1322. }
  1323. // use custom `isEqual` method if available
  1324. if (a.isEqual && isFunction(a.isEqual)) {
  1325. thorough.value = null;
  1326. return a.isEqual(b);
  1327. }
  1328. if (b.isEqual && isFunction(b.isEqual)) {
  1329. thorough.value = null;
  1330. return b.isEqual(a);
  1331. }
  1332. }
  1333. // exit early for identical values
  1334. if (a === b) {
  1335. // treat `+0` vs. `-0` as not equal
  1336. return a !== 0 || (1 / a == 1 / b);
  1337. }
  1338. // compare [[Class]] names
  1339. var className = toString.call(a);
  1340. if (className != toString.call(b)) {
  1341. return false;
  1342. }
  1343. switch (className) {
  1344. case boolClass:
  1345. case dateClass:
  1346. // coerce dates and booleans to numbers, dates to milliseconds and booleans
  1347. // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
  1348. return +a == +b;
  1349. case numberClass:
  1350. // treat `NaN` vs. `NaN` as equal
  1351. return a != +a
  1352. ? b != +b
  1353. // but treat `+0` vs. `-0` as not equal
  1354. : (a == 0 ? (1 / a == 1 / b) : a == +b);
  1355. case regexpClass:
  1356. case stringClass:
  1357. // coerce regexes to strings (http://es5.github.com/#x15.10.6.4)
  1358. // treat string primitives and their corresponding object instances as equal
  1359. return a == b + '';
  1360. }
  1361. // exit early, in older browsers, if `a` is array-like but not `b`
  1362. var isArr = arrayLikeClasses[className];
  1363. if (noArgsClass && !isArr && (isArr = isArguments(a)) && !isArguments(b)) {
  1364. return false;
  1365. }
  1366. // exit for functions and DOM nodes
  1367. if (!isArr && (className != objectClass || (noNodeClass && (
  1368. (typeof a.toString != 'function' && typeof (a + '') == 'string') ||
  1369. (typeof b.toString != 'function' && typeof (b + '') == 'string'))))) {
  1370. return false;
  1371. }
  1372. // assume cyclic structures are equal
  1373. // the algorithm for detecting cyclic structures is adapted from ES 5.1
  1374. // section 15.12.3, abstract operation `JO` (http://es5.git