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

/ajax/libs//0.8.2/lodash.js

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