PageRenderTime 57ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/ajax/libs//0.8.0/lodash.js

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