PageRenderTime 52ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/app/scripts/libs/lodash.js

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