PageRenderTime 30ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/ajax/libs//0.6.0/lodash.js

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