3 * lodash 4.11.2 <https://lodash.com/>
4 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
5 * Released under MIT license <https://lodash.com/license>
6 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
7 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
14 /** Used as the semantic version number. */
15 var VERSION = '4.11.2';
17 /** Used as the size to enable large array optimizations. */
18 var LARGE_ARRAY_SIZE = 200;
20 /** Used as the `TypeError` message for "Functions" methods. */
21 var FUNC_ERROR_TEXT = 'Expected a function';
23 /** Used to stand-in for `undefined` hash values. */
24 var HASH_UNDEFINED = '__lodash_hash_undefined__';
26 /** Used as the internal argument placeholder. */
27 var PLACEHOLDER = '__lodash_placeholder__';
29 /** Used to compose bitmasks for wrapper metadata. */
34 CURRY_RIGHT_FLAG = 16,
36 PARTIAL_RIGHT_FLAG = 64,
41 /** Used to compose bitmasks for comparison styles. */
42 var UNORDERED_COMPARE_FLAG = 1,
43 PARTIAL_COMPARE_FLAG = 2;
45 /** Used as default options for `_.truncate`. */
46 var DEFAULT_TRUNC_LENGTH = 30,
47 DEFAULT_TRUNC_OMISSION = '...';
49 /** Used to detect hot functions by number of calls within a span of milliseconds. */
53 /** Used to indicate the type of lazy iteratees. */
54 var LAZY_FILTER_FLAG = 1,
58 /** Used as references for various `Number` constants. */
60 MAX_SAFE_INTEGER = 9007199254740991,
61 MAX_INTEGER = 1.7976931348623157e+308,
64 /** Used as references for the maximum length and index of an array. */
65 var MAX_ARRAY_LENGTH = 4294967295,
66 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
67 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
69 /** `Object#toString` result references. */
70 var argsTag = '[object Arguments]',
71 arrayTag = '[object Array]',
72 boolTag = '[object Boolean]',
73 dateTag = '[object Date]',
74 errorTag = '[object Error]',
75 funcTag = '[object Function]',
76 genTag = '[object GeneratorFunction]',
77 mapTag = '[object Map]',
78 numberTag = '[object Number]',
79 objectTag = '[object Object]',
80 promiseTag = '[object Promise]',
81 regexpTag = '[object RegExp]',
82 setTag = '[object Set]',
83 stringTag = '[object String]',
84 symbolTag = '[object Symbol]',
85 weakMapTag = '[object WeakMap]',
86 weakSetTag = '[object WeakSet]';
88 var arrayBufferTag = '[object ArrayBuffer]',
89 dataViewTag = '[object DataView]',
90 float32Tag = '[object Float32Array]',
91 float64Tag = '[object Float64Array]',
92 int8Tag = '[object Int8Array]',
93 int16Tag = '[object Int16Array]',
94 int32Tag = '[object Int32Array]',
95 uint8Tag = '[object Uint8Array]',
96 uint8ClampedTag = '[object Uint8ClampedArray]',
97 uint16Tag = '[object Uint16Array]',
98 uint32Tag = '[object Uint32Array]';
100 /** Used to match empty string literals in compiled template source. */
101 var reEmptyStringLeading = /\b__p \+= '';/g,
102 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
103 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
105 /** Used to match HTML entities and HTML characters. */
106 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
107 reUnescapedHtml = /[&<>"'`]/g,
108 reHasEscapedHtml = RegExp(reEscapedHtml.source),
109 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
111 /** Used to match template delimiters. */
112 var reEscape = /<%-([\s\S]+?)%>/g,
113 reEvaluate = /<%([\s\S]+?)%>/g,
114 reInterpolate = /<%=([\s\S]+?)%>/g;
116 /** Used to match property names within property paths. */
117 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
118 reIsPlainProp = /^\w*$/,
119 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;
122 * Used to match `RegExp`
123 * [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns).
125 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
126 reHasRegExpChar = RegExp(reRegExpChar.source);
128 /** Used to match leading and trailing whitespace. */
129 var reTrim = /^\s+|\s+$/g,
130 reTrimStart = /^\s+/,
133 /** Used to match non-compound words composed of alphanumeric characters. */
134 var reBasicWord = /[a-zA-Z0-9]+/g;
136 /** Used to match backslashes in property paths. */
137 var reEscapeChar = /\\(\\)?/g;
141 * [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components).
143 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
145 /** Used to match `RegExp` flags from their coerced string values. */
146 var reFlags = /\w*$/;
148 /** Used to detect hexadecimal string values. */
149 var reHasHexPrefix = /^0x/i;
151 /** Used to detect bad signed hexadecimal string values. */
152 var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
154 /** Used to detect binary string values. */
155 var reIsBinary = /^0b[01]+$/i;
157 /** Used to detect host constructors (Safari). */
158 var reIsHostCtor = /^\[object .+?Constructor\]$/;
160 /** Used to detect octal string values. */
161 var reIsOctal = /^0o[0-7]+$/i;
163 /** Used to detect unsigned integer values. */
164 var reIsUint = /^(?:0|[1-9]\d*)$/;
166 /** Used to match latin-1 supplementary letters (excluding mathematical operators). */
167 var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
169 /** Used to ensure capturing order of template delimiters. */
170 var reNoMatch = /($^)/;
172 /** Used to match unescaped characters in compiled string literals. */
173 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
175 /** Used to compose unicode character classes. */
176 var rsAstralRange = '\\ud800-\\udfff',
177 rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
178 rsComboSymbolsRange = '\\u20d0-\\u20f0',
179 rsDingbatRange = '\\u2700-\\u27bf',
180 rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
181 rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
182 rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
183 rsPunctuationRange = '\\u2000-\\u206f',
184 rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
185 rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
186 rsVarRange = '\\ufe0e\\ufe0f',
187 rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
189 /** Used to compose unicode capture groups. */
190 var rsApos = "['\u2019]",
191 rsAstral = '[' + rsAstralRange + ']',
192 rsBreak = '[' + rsBreakRange + ']',
193 rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
195 rsDingbat = '[' + rsDingbatRange + ']',
196 rsLower = '[' + rsLowerRange + ']',
197 rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
198 rsFitz = '\\ud83c[\\udffb-\\udfff]',
199 rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
200 rsNonAstral = '[^' + rsAstralRange + ']',
201 rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
202 rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
203 rsUpper = '[' + rsUpperRange + ']',
206 /** Used to compose unicode regexes. */
207 var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
208 rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
209 rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
210 rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
211 reOptMod = rsModifier + '?',
212 rsOptVar = '[' + rsVarRange + ']?',
213 rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
214 rsSeq = rsOptVar + reOptMod + rsOptJoin,
215 rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
216 rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
218 /** Used to match apostrophes. */
219 var reApos = RegExp(rsApos, 'g');
222 * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
223 * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
225 var reComboMark = RegExp(rsCombo, 'g');
227 /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
228 var reComplexSymbol = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
230 /** Used to match complex or compound words. */
231 var reComplexWord = RegExp([
232 rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
233 rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
234 rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
235 rsUpper + '+' + rsOptUpperContr,
240 /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
241 var reHasComplexSymbol = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
243 /** Used to detect strings that need a more robust regexp to match words. */
244 var reHasComplexWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
246 /** Used to assign default `context` object properties. */
248 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
249 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
250 'Promise', 'Reflect', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError',
251 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
252 '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
255 /** Used to make template sourceURLs easier to identify. */
256 var templateCounter = -1;
258 /** Used to identify `toStringTag` values of typed arrays. */
259 var typedArrayTags = {};
260 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
261 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
262 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
263 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
264 typedArrayTags[uint32Tag] = true;
265 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
266 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
267 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
268 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
269 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
270 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
271 typedArrayTags[setTag] = typedArrayTags[stringTag] =
272 typedArrayTags[weakMapTag] = false;
274 /** Used to identify `toStringTag` values supported by `_.clone`. */
275 var cloneableTags = {};
276 cloneableTags[argsTag] = cloneableTags[arrayTag] =
277 cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
278 cloneableTags[boolTag] = cloneableTags[dateTag] =
279 cloneableTags[float32Tag] = cloneableTags[float64Tag] =
280 cloneableTags[int8Tag] = cloneableTags[int16Tag] =
281 cloneableTags[int32Tag] = cloneableTags[mapTag] =
282 cloneableTags[numberTag] = cloneableTags[objectTag] =
283 cloneableTags[regexpTag] = cloneableTags[setTag] =
284 cloneableTags[stringTag] = cloneableTags[symbolTag] =
285 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
286 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
287 cloneableTags[errorTag] = cloneableTags[funcTag] =
288 cloneableTags[weakMapTag] = false;
290 /** Used to map latin-1 supplementary letters to basic latin letters. */
291 var deburredLetters = {
292 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
293 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
294 '\xc7': 'C', '\xe7': 'c',
295 '\xd0': 'D', '\xf0': 'd',
296 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
297 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
298 '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
299 '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
300 '\xd1': 'N', '\xf1': 'n',
301 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
302 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
303 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
304 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
305 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
306 '\xc6': 'Ae', '\xe6': 'ae',
307 '\xde': 'Th', '\xfe': 'th',
311 /** Used to map characters to HTML entities. */
321 /** Used to map HTML entities to characters. */
322 var htmlUnescapes = {
331 /** Used to determine if values are of the language type `Object`. */
337 /** Used to escape characters for inclusion in compiled string literals. */
338 var stringEscapes = {
347 /** Built-in method references without a dependency on `root`. */
348 var freeParseFloat = parseFloat,
349 freeParseInt = parseInt;
351 /** Detect free variable `exports`. */
352 var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
356 /** Detect free variable `module`. */
357 var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
361 /** Detect the popular CommonJS extension `module.exports`. */
362 var moduleExports = (freeModule && freeModule.exports === freeExports)
366 /** Detect free variable `global` from Node.js. */
367 var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
369 /** Detect free variable `self`. */
370 var freeSelf = checkGlobal(objectTypes[typeof self] && self);
372 /** Detect free variable `window`. */
373 var freeWindow = checkGlobal(objectTypes[typeof window] && window);
375 /** Detect `this` as the global object. */
376 var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
379 * Used as a reference to the global object.
381 * The `this` value is used if it's the global object to avoid Greasemonkey's
382 * restricted `window` object, otherwise the `window` object is used.
384 var root = freeGlobal ||
385 ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
386 freeSelf || thisGlobal || Function('return this')();
388 /*--------------------------------------------------------------------------*/
391 * Adds the key-value `pair` to `map`.
394 * @param {Object} map The map to modify.
395 * @param {Array} pair The key-value pair to add.
396 * @returns {Object} Returns `map`.
398 function addMapEntry(map, pair) {
399 // Don't return `Map#set` because it doesn't return the map instance in IE 11.
400 map.set(pair[0], pair[1]);
405 * Adds `value` to `set`.
408 * @param {Object} set The set to modify.
409 * @param {*} value The value to add.
410 * @returns {Object} Returns `set`.
412 function addSetEntry(set, value) {
418 * A faster alternative to `Function#apply`, this function invokes `func`
419 * with the `this` binding of `thisArg` and the arguments of `args`.
422 * @param {Function} func The function to invoke.
423 * @param {*} thisArg The `this` binding of `func`.
424 * @param {Array} args The arguments to invoke `func` with.
425 * @returns {*} Returns the result of `func`.
427 function apply(func, thisArg, args) {
428 var length = args.length;
430 case 0: return func.call(thisArg);
431 case 1: return func.call(thisArg, args[0]);
432 case 2: return func.call(thisArg, args[0], args[1]);
433 case 3: return func.call(thisArg, args[0], args[1], args[2]);
435 return func.apply(thisArg, args);
439 * A specialized version of `baseAggregator` for arrays.
442 * @param {Array} array The array to iterate over.
443 * @param {Function} setter The function to set `accumulator` values.
444 * @param {Function} iteratee The iteratee to transform keys.
445 * @param {Object} accumulator The initial aggregated object.
446 * @returns {Function} Returns `accumulator`.
448 function arrayAggregator(array, setter, iteratee, accumulator) {
450 length = array.length;
452 while (++index < length) {
453 var value = array[index];
454 setter(accumulator, value, iteratee(value), array);
460 * Creates a new array concatenating `array` with `other`.
463 * @param {Array} array The first array to concatenate.
464 * @param {Array} other The second array to concatenate.
465 * @returns {Array} Returns the new concatenated array.
467 function arrayConcat(array, other) {
469 length = array.length,
471 othLength = other.length,
472 result = Array(length + othLength);
474 while (++index < length) {
475 result[index] = array[index];
477 while (++othIndex < othLength) {
478 result[index++] = other[othIndex];
484 * A specialized version of `_.forEach` for arrays without support for
485 * iteratee shorthands.
488 * @param {Array} array The array to iterate over.
489 * @param {Function} iteratee The function invoked per iteration.
490 * @returns {Array} Returns `array`.
492 function arrayEach(array, iteratee) {
494 length = array.length;
496 while (++index < length) {
497 if (iteratee(array[index], index, array) === false) {
505 * A specialized version of `_.forEachRight` for arrays without support for
506 * iteratee shorthands.
509 * @param {Array} array The array to iterate over.
510 * @param {Function} iteratee The function invoked per iteration.
511 * @returns {Array} Returns `array`.
513 function arrayEachRight(array, iteratee) {
514 var length = array.length;
517 if (iteratee(array[length], length, array) === false) {
525 * A specialized version of `_.every` for arrays without support for
526 * iteratee shorthands.
529 * @param {Array} array The array to iterate over.
530 * @param {Function} predicate The function invoked per iteration.
531 * @returns {boolean} Returns `true` if all elements pass the predicate check,
534 function arrayEvery(array, predicate) {
536 length = array.length;
538 while (++index < length) {
539 if (!predicate(array[index], index, array)) {
547 * A specialized version of `_.filter` for arrays without support for
548 * iteratee shorthands.
551 * @param {Array} array The array to iterate over.
552 * @param {Function} predicate The function invoked per iteration.
553 * @returns {Array} Returns the new filtered array.
555 function arrayFilter(array, predicate) {
557 length = array.length,
561 while (++index < length) {
562 var value = array[index];
563 if (predicate(value, index, array)) {
564 result[resIndex++] = value;
571 * A specialized version of `_.includes` for arrays without support for
572 * specifying an index to search from.
575 * @param {Array} array The array to search.
576 * @param {*} target The value to search for.
577 * @returns {boolean} Returns `true` if `target` is found, else `false`.
579 function arrayIncludes(array, value) {
580 return !!array.length && baseIndexOf(array, value, 0) > -1;
584 * This function is like `arrayIncludes` except that it accepts a comparator.
587 * @param {Array} array The array to search.
588 * @param {*} target The value to search for.
589 * @param {Function} comparator The comparator invoked per element.
590 * @returns {boolean} Returns `true` if `target` is found, else `false`.
592 function arrayIncludesWith(array, value, comparator) {
594 length = array.length;
596 while (++index < length) {
597 if (comparator(value, array[index])) {
605 * A specialized version of `_.map` for arrays without support for iteratee
609 * @param {Array} array The array to iterate over.
610 * @param {Function} iteratee The function invoked per iteration.
611 * @returns {Array} Returns the new mapped array.
613 function arrayMap(array, iteratee) {
615 length = array.length,
616 result = Array(length);
618 while (++index < length) {
619 result[index] = iteratee(array[index], index, array);
625 * Appends the elements of `values` to `array`.
628 * @param {Array} array The array to modify.
629 * @param {Array} values The values to append.
630 * @returns {Array} Returns `array`.
632 function arrayPush(array, values) {
634 length = values.length,
635 offset = array.length;
637 while (++index < length) {
638 array[offset + index] = values[index];
644 * A specialized version of `_.reduce` for arrays without support for
645 * iteratee shorthands.
648 * @param {Array} array The array to iterate over.
649 * @param {Function} iteratee The function invoked per iteration.
650 * @param {*} [accumulator] The initial value.
651 * @param {boolean} [initAccum] Specify using the first element of `array` as
653 * @returns {*} Returns the accumulated value.
655 function arrayReduce(array, iteratee, accumulator, initAccum) {
657 length = array.length;
659 if (initAccum && length) {
660 accumulator = array[++index];
662 while (++index < length) {
663 accumulator = iteratee(accumulator, array[index], index, array);
669 * A specialized version of `_.reduceRight` for arrays without support for
670 * iteratee shorthands.
673 * @param {Array} array The array to iterate over.
674 * @param {Function} iteratee The function invoked per iteration.
675 * @param {*} [accumulator] The initial value.
676 * @param {boolean} [initAccum] Specify using the last element of `array` as
678 * @returns {*} Returns the accumulated value.
680 function arrayReduceRight(array, iteratee, accumulator, initAccum) {
681 var length = array.length;
682 if (initAccum && length) {
683 accumulator = array[--length];
686 accumulator = iteratee(accumulator, array[length], length, array);
692 * A specialized version of `_.some` for arrays without support for iteratee
696 * @param {Array} array The array to iterate over.
697 * @param {Function} predicate The function invoked per iteration.
698 * @returns {boolean} Returns `true` if any element passes the predicate check,
701 function arraySome(array, predicate) {
703 length = array.length;
705 while (++index < length) {
706 if (predicate(array[index], index, array)) {
714 * The base implementation of methods like `_.find` and `_.findKey`, without
715 * support for iteratee shorthands, which iterates over `collection` using
719 * @param {Array|Object} collection The collection to search.
720 * @param {Function} predicate The function invoked per iteration.
721 * @param {Function} eachFunc The function to iterate over `collection`.
722 * @param {boolean} [retKey] Specify returning the key of the found element
723 * instead of the element itself.
724 * @returns {*} Returns the found element or its key, else `undefined`.
726 function baseFind(collection, predicate, eachFunc, retKey) {
728 eachFunc(collection, function(value, key, collection) {
729 if (predicate(value, key, collection)) {
730 result = retKey ? key : value;
738 * The base implementation of `_.findIndex` and `_.findLastIndex` without
739 * support for iteratee shorthands.
742 * @param {Array} array The array to search.
743 * @param {Function} predicate The function invoked per iteration.
744 * @param {boolean} [fromRight] Specify iterating from right to left.
745 * @returns {number} Returns the index of the matched value, else `-1`.
747 function baseFindIndex(array, predicate, fromRight) {
748 var length = array.length,
749 index = fromRight ? length : -1;
751 while ((fromRight ? index-- : ++index < length)) {
752 if (predicate(array[index], index, array)) {
760 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
763 * @param {Array} array The array to search.
764 * @param {*} value The value to search for.
765 * @param {number} fromIndex The index to search from.
766 * @returns {number} Returns the index of the matched value, else `-1`.
768 function baseIndexOf(array, value, fromIndex) {
769 if (value !== value) {
770 return indexOfNaN(array, fromIndex);
772 var index = fromIndex - 1,
773 length = array.length;
775 while (++index < length) {
776 if (array[index] === value) {
784 * This function is like `baseIndexOf` except that it accepts a comparator.
787 * @param {Array} array The array to search.
788 * @param {*} value The value to search for.
789 * @param {number} fromIndex The index to search from.
790 * @param {Function} comparator The comparator invoked per element.
791 * @returns {number} Returns the index of the matched value, else `-1`.
793 function baseIndexOfWith(array, value, fromIndex, comparator) {
794 var index = fromIndex - 1,
795 length = array.length;
797 while (++index < length) {
798 if (comparator(array[index], value)) {
806 * The base implementation of `_.mean` and `_.meanBy` without support for
807 * iteratee shorthands.
810 * @param {Array} array The array to iterate over.
811 * @param {Function} iteratee The function invoked per iteration.
812 * @returns {number} Returns the mean.
814 function baseMean(array, iteratee) {
815 var length = array ? array.length : 0;
816 return length ? (baseSum(array, iteratee) / length) : NAN;
820 * The base implementation of `_.reduce` and `_.reduceRight`, without support
821 * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
824 * @param {Array|Object} collection The collection to iterate over.
825 * @param {Function} iteratee The function invoked per iteration.
826 * @param {*} accumulator The initial value.
827 * @param {boolean} initAccum Specify using the first or last element of
828 * `collection` as the initial value.
829 * @param {Function} eachFunc The function to iterate over `collection`.
830 * @returns {*} Returns the accumulated value.
832 function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
833 eachFunc(collection, function(value, index, collection) {
834 accumulator = initAccum
835 ? (initAccum = false, value)
836 : iteratee(accumulator, value, index, collection);
842 * The base implementation of `_.sortBy` which uses `comparer` to define the
843 * sort order of `array` and replaces criteria objects with their corresponding
847 * @param {Array} array The array to sort.
848 * @param {Function} comparer The function to define sort order.
849 * @returns {Array} Returns `array`.
851 function baseSortBy(array, comparer) {
852 var length = array.length;
854 array.sort(comparer);
856 array[length] = array[length].value;
862 * The base implementation of `_.sum` and `_.sumBy` without support for
863 * iteratee shorthands.
866 * @param {Array} array The array to iterate over.
867 * @param {Function} iteratee The function invoked per iteration.
868 * @returns {number} Returns the sum.
870 function baseSum(array, iteratee) {
873 length = array.length;
875 while (++index < length) {
876 var current = iteratee(array[index]);
877 if (current !== undefined) {
878 result = result === undefined ? current : (result + current);
885 * The base implementation of `_.times` without support for iteratee shorthands
886 * or max array length checks.
889 * @param {number} n The number of times to invoke `iteratee`.
890 * @param {Function} iteratee The function invoked per iteration.
891 * @returns {Array} Returns the array of results.
893 function baseTimes(n, iteratee) {
897 while (++index < n) {
898 result[index] = iteratee(index);
904 * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
905 * of key-value pairs for `object` corresponding to the property names of `props`.
908 * @param {Object} object The object to query.
909 * @param {Array} props The property names to get values for.
910 * @returns {Object} Returns the new array of key-value pairs.
912 function baseToPairs(object, props) {
913 return arrayMap(props, function(key) {
914 return [key, object[key]];
919 * The base implementation of `_.unary` without support for storing wrapper metadata.
922 * @param {Function} func The function to cap arguments for.
923 * @returns {Function} Returns the new function.
925 function baseUnary(func) {
926 return function(value) {
932 * The base implementation of `_.values` and `_.valuesIn` which creates an
933 * array of `object` property values corresponding to the property names
937 * @param {Object} object The object to query.
938 * @param {Array} props The property names to get values for.
939 * @returns {Object} Returns the array of property values.
941 function baseValues(object, props) {
942 return arrayMap(props, function(key) {
948 * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
949 * that is not found in the character symbols.
952 * @param {Array} strSymbols The string symbols to inspect.
953 * @param {Array} chrSymbols The character symbols to find.
954 * @returns {number} Returns the index of the first unmatched string symbol.
956 function charsStartIndex(strSymbols, chrSymbols) {
958 length = strSymbols.length;
960 while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
965 * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
966 * that is not found in the character symbols.
969 * @param {Array} strSymbols The string symbols to inspect.
970 * @param {Array} chrSymbols The character symbols to find.
971 * @returns {number} Returns the index of the last unmatched string symbol.
973 function charsEndIndex(strSymbols, chrSymbols) {
974 var index = strSymbols.length;
976 while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
981 * Checks if `value` is a global object.
984 * @param {*} value The value to check.
985 * @returns {null|Object} Returns `value` if it's a global object, else `null`.
987 function checkGlobal(value) {
988 return (value && value.Object === Object) ? value : null;
992 * Gets the number of `placeholder` occurrences in `array`.
995 * @param {Array} array The array to inspect.
996 * @param {*} placeholder The placeholder to search for.
997 * @returns {number} Returns the placeholder count.
999 function countHolders(array, placeholder) {
1000 var length = array.length,
1004 if (array[length] === placeholder) {
1012 * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
1015 * @param {string} letter The matched letter to deburr.
1016 * @returns {string} Returns the deburred letter.
1018 function deburrLetter(letter) {
1019 return deburredLetters[letter];
1023 * Used by `_.escape` to convert characters to HTML entities.
1026 * @param {string} chr The matched character to escape.
1027 * @returns {string} Returns the escaped character.
1029 function escapeHtmlChar(chr) {
1030 return htmlEscapes[chr];
1034 * Used by `_.template` to escape characters for inclusion in compiled string literals.
1037 * @param {string} chr The matched character to escape.
1038 * @returns {string} Returns the escaped character.
1040 function escapeStringChar(chr) {
1041 return '\\' + stringEscapes[chr];
1045 * Gets the index at which the first occurrence of `NaN` is found in `array`.
1048 * @param {Array} array The array to search.
1049 * @param {number} fromIndex The index to search from.
1050 * @param {boolean} [fromRight] Specify iterating from right to left.
1051 * @returns {number} Returns the index of the matched `NaN`, else `-1`.
1053 function indexOfNaN(array, fromIndex, fromRight) {
1054 var length = array.length,
1055 index = fromIndex + (fromRight ? 0 : -1);
1057 while ((fromRight ? index-- : ++index < length)) {
1058 var other = array[index];
1059 if (other !== other) {
1067 * Checks if `value` is a host object in IE < 9.
1070 * @param {*} value The value to check.
1071 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
1073 function isHostObject(value) {
1074 // Many host objects are `Object` objects that can coerce to strings
1075 // despite having improperly defined `toString` methods.
1077 if (value != null && typeof value.toString != 'function') {
1079 result = !!(value + '');
1086 * Converts `iterator` to an array.
1089 * @param {Object} iterator The iterator to convert.
1090 * @returns {Array} Returns the converted array.
1092 function iteratorToArray(iterator) {
1096 while (!(data = iterator.next()).done) {
1097 result.push(data.value);
1103 * Converts `map` to an array.
1106 * @param {Object} map The map to convert.
1107 * @returns {Array} Returns the converted array.
1109 function mapToArray(map) {
1111 result = Array(map.size);
1113 map.forEach(function(value, key) {
1114 result[++index] = [key, value];
1120 * Replaces all `placeholder` elements in `array` with an internal placeholder
1121 * and returns an array of their indexes.
1124 * @param {Array} array The array to modify.
1125 * @param {*} placeholder The placeholder to replace.
1126 * @returns {Array} Returns the new array of placeholder indexes.
1128 function replaceHolders(array, placeholder) {
1130 length = array.length,
1134 while (++index < length) {
1135 var value = array[index];
1136 if (value === placeholder || value === PLACEHOLDER) {
1137 array[index] = PLACEHOLDER;
1138 result[resIndex++] = index;
1145 * Converts `set` to an array.
1148 * @param {Object} set The set to convert.
1149 * @returns {Array} Returns the converted array.
1151 function setToArray(set) {
1153 result = Array(set.size);
1155 set.forEach(function(value) {
1156 result[++index] = value;
1162 * Gets the number of symbols in `string`.
1165 * @param {string} string The string to inspect.
1166 * @returns {number} Returns the string size.
1168 function stringSize(string) {
1169 if (!(string && reHasComplexSymbol.test(string))) {
1170 return string.length;
1172 var result = reComplexSymbol.lastIndex = 0;
1173 while (reComplexSymbol.test(string)) {
1180 * Converts `string` to an array.
1183 * @param {string} string The string to convert.
1184 * @returns {Array} Returns the converted array.
1186 function stringToArray(string) {
1187 return string.match(reComplexSymbol);
1191 * Used by `_.unescape` to convert HTML entities to characters.
1194 * @param {string} chr The matched character to unescape.
1195 * @returns {string} Returns the unescaped character.
1197 function unescapeHtmlChar(chr) {
1198 return htmlUnescapes[chr];
1201 /*--------------------------------------------------------------------------*/
1204 * Create a new pristine `lodash` function using the `context` object.
1210 * @param {Object} [context=root] The context object.
1211 * @returns {Function} Returns a new `lodash` function.
1214 * _.mixin({ 'foo': _.constant('foo') });
1216 * var lodash = _.runInContext();
1217 * lodash.mixin({ 'bar': lodash.constant('bar') });
1219 * _.isFunction(_.foo);
1221 * _.isFunction(_.bar);
1224 * lodash.isFunction(lodash.foo);
1226 * lodash.isFunction(lodash.bar);
1229 * // Use `context` to mock `Date#getTime` use in `_.now`.
1230 * var mock = _.runInContext({
1231 * 'Date': function() {
1232 * return { 'getTime': getTimeMock };
1236 * // Create a suped-up `defer` in Node.js.
1237 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
1239 function runInContext(context) {
1240 context = context ? _.defaults({}, context, _.pick(root, contextProps)) : root;
1242 /** Built-in constructor references. */
1243 var Date = context.Date,
1244 Error = context.Error,
1245 Math = context.Math,
1246 RegExp = context.RegExp,
1247 TypeError = context.TypeError;
1249 /** Used for built-in method references. */
1250 var arrayProto = context.Array.prototype,
1251 objectProto = context.Object.prototype,
1252 stringProto = context.String.prototype;
1254 /** Used to resolve the decompiled source of functions. */
1255 var funcToString = context.Function.prototype.toString;
1257 /** Used to check objects for own properties. */
1258 var hasOwnProperty = objectProto.hasOwnProperty;
1260 /** Used to generate unique IDs. */
1263 /** Used to infer the `Object` constructor. */
1264 var objectCtorString = funcToString.call(Object);
1267 * Used to resolve the
1268 * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
1271 var objectToString = objectProto.toString;
1273 /** Used to restore the original `_` reference in `_.noConflict`. */
1274 var oldDash = root._;
1276 /** Used to detect if a method is native. */
1277 var reIsNative = RegExp('^' +
1278 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
1279 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
1282 /** Built-in value references. */
1283 var Buffer = moduleExports ? context.Buffer : undefined,
1284 Reflect = context.Reflect,
1285 Symbol = context.Symbol,
1286 Uint8Array = context.Uint8Array,
1287 clearTimeout = context.clearTimeout,
1288 enumerate = Reflect ? Reflect.enumerate : undefined,
1289 getOwnPropertySymbols = Object.getOwnPropertySymbols,
1290 iteratorSymbol = typeof (iteratorSymbol = Symbol && Symbol.iterator) == 'symbol' ? iteratorSymbol : undefined,
1291 objectCreate = Object.create,
1292 propertyIsEnumerable = objectProto.propertyIsEnumerable,
1293 setTimeout = context.setTimeout,
1294 splice = arrayProto.splice;
1296 /* Built-in method references for those with the same name as other `lodash` methods. */
1297 var nativeCeil = Math.ceil,
1298 nativeFloor = Math.floor,
1299 nativeGetPrototype = Object.getPrototypeOf,
1300 nativeIsFinite = context.isFinite,
1301 nativeJoin = arrayProto.join,
1302 nativeKeys = Object.keys,
1303 nativeMax = Math.max,
1304 nativeMin = Math.min,
1305 nativeParseInt = context.parseInt,
1306 nativeRandom = Math.random,
1307 nativeReplace = stringProto.replace,
1308 nativeReverse = arrayProto.reverse,
1309 nativeSplit = stringProto.split;
1311 /* Built-in method references that are verified to be native. */
1312 var DataView = getNative(context, 'DataView'),
1313 Map = getNative(context, 'Map'),
1314 Promise = getNative(context, 'Promise'),
1315 Set = getNative(context, 'Set'),
1316 WeakMap = getNative(context, 'WeakMap'),
1317 nativeCreate = getNative(Object, 'create');
1319 /** Used to store function metadata. */
1320 var metaMap = WeakMap && new WeakMap;
1322 /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */
1323 var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf');
1325 /** Used to lookup unminified function names. */
1328 /** Used to detect maps, sets, and weakmaps. */
1329 var dataViewCtorString = toSource(DataView),
1330 mapCtorString = toSource(Map),
1331 promiseCtorString = toSource(Promise),
1332 setCtorString = toSource(Set),
1333 weakMapCtorString = toSource(WeakMap);
1335 /** Used to convert symbols to primitives and strings. */
1336 var symbolProto = Symbol ? Symbol.prototype : undefined,
1337 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
1338 symbolToString = symbolProto ? symbolProto.toString : undefined;
1340 /*------------------------------------------------------------------------*/
1343 * Creates a `lodash` object which wraps `value` to enable implicit method
1344 * chain sequences. Methods that operate on and return arrays, collections,
1345 * and functions can be chained together. Methods that retrieve a single value
1346 * or may return a primitive value will automatically end the chain sequence
1347 * and return the unwrapped value. Otherwise, the value must be unwrapped
1350 * Explicit chain sequences, which must be unwrapped with `_#value`, may be
1351 * enabled using `_.chain`.
1353 * The execution of chained methods is lazy, that is, it's deferred until
1354 * `_#value` is implicitly or explicitly called.
1356 * Lazy evaluation allows several methods to support shortcut fusion.
1357 * Shortcut fusion is an optimization to merge iteratee calls; this avoids
1358 * the creation of intermediate arrays and can greatly reduce the number of
1359 * iteratee executions. Sections of a chain sequence qualify for shortcut
1360 * fusion if the section is applied to an array of at least `200` elements
1361 * and any iteratees accept only one argument. The heuristic for whether a
1362 * section qualifies for shortcut fusion is subject to change.
1364 * Chaining is supported in custom builds as long as the `_#value` method is
1365 * directly or indirectly included in the build.
1367 * In addition to lodash methods, wrappers have `Array` and `String` methods.
1369 * The wrapper `Array` methods are:
1370 * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
1372 * The wrapper `String` methods are:
1373 * `replace` and `split`
1375 * The wrapper methods that support shortcut fusion are:
1376 * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
1377 * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
1378 * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
1380 * The chainable wrapper methods are:
1381 * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
1382 * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
1383 * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
1384 * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
1385 * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
1386 * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
1387 * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
1388 * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
1389 * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
1390 * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
1391 * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
1392 * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
1393 * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
1394 * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
1395 * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
1396 * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
1397 * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
1398 * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
1399 * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
1400 * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
1401 * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
1402 * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
1403 * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
1404 * `zipObject`, `zipObjectDeep`, and `zipWith`
1406 * The wrapper methods that are **not** chainable by default are:
1407 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
1408 * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `deburr`, `divide`, `each`,
1409 * `eachRight`, `endsWith`, `eq`, `escape`, `escapeRegExp`, `every`, `find`,
1410 * `findIndex`, `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `first`,
1411 * `floor`, `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`,
1412 * `forOwnRight`, `get`, `gt`, `gte`, `has`, `hasIn`, `head`, `identity`,
1413 * `includes`, `indexOf`, `inRange`, `invoke`, `isArguments`, `isArray`,
1414 * `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, `isBoolean`, `isBuffer`,
1415 * `isDate`, `isElement`, `isEmpty`, `isEqual`, `isEqualWith`, `isError`,
1416 * `isFinite`, `isFunction`, `isInteger`, `isLength`, `isMap`, `isMatch`,
1417 * `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, `isNumber`,
1418 * `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, `isSafeInteger`,
1419 * `isSet`, `isString`, `isUndefined`, `isTypedArray`, `isWeakMap`, `isWeakSet`,
1420 * `join`, `kebabCase`, `last`, `lastIndexOf`, `lowerCase`, `lowerFirst`,
1421 * `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, `min`, `minBy`, `multiply`,
1422 * `noConflict`, `noop`, `now`, `nth`, `pad`, `padEnd`, `padStart`, `parseInt`,
1423 * `pop`, `random`, `reduce`, `reduceRight`, `repeat`, `result`, `round`,
1424 * `runInContext`, `sample`, `shift`, `size`, `snakeCase`, `some`, `sortedIndex`,
1425 * `sortedIndexBy`, `sortedLastIndex`, `sortedLastIndexBy`, `startCase`,
1426 * `startsWith`, `subtract`, `sum`, `sumBy`, `template`, `times`, `toInteger`,
1427 * `toJSON`, `toLength`, `toLower`, `toNumber`, `toSafeInteger`, `toString`,
1428 * `toUpper`, `trim`, `trimEnd`, `trimStart`, `truncate`, `unescape`,
1429 * `uniqueId`, `upperCase`, `upperFirst`, `value`, and `words`
1434 * @param {*} value The value to wrap in a `lodash` instance.
1435 * @returns {Object} Returns the new `lodash` wrapper instance.
1438 * function square(n) {
1442 * var wrapped = _([1, 2, 3]);
1444 * // Returns an unwrapped value.
1445 * wrapped.reduce(_.add);
1448 * // Returns a wrapped value.
1449 * var squares = wrapped.map(square);
1451 * _.isArray(squares);
1454 * _.isArray(squares.value());
1457 function lodash(value) {
1458 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
1459 if (value instanceof LodashWrapper) {
1462 if (hasOwnProperty.call(value, '__wrapped__')) {
1463 return wrapperClone(value);
1466 return new LodashWrapper(value);
1470 * The function whose prototype chain sequence wrappers inherit from.
1474 function baseLodash() {
1475 // No operation performed.
1479 * The base constructor for creating `lodash` wrapper objects.
1482 * @param {*} value The value to wrap.
1483 * @param {boolean} [chainAll] Enable explicit method chain sequences.
1485 function LodashWrapper(value, chainAll) {
1486 this.__wrapped__ = value;
1487 this.__actions__ = [];
1488 this.__chain__ = !!chainAll;
1490 this.__values__ = undefined;
1494 * By default, the template delimiters used by lodash are like those in
1495 * embedded Ruby (ERB). Change the following template settings to use
1496 * alternative delimiters.
1502 lodash.templateSettings = {
1505 * Used to detect `data` property values to be HTML-escaped.
1507 * @memberOf _.templateSettings
1513 * Used to detect code to be evaluated.
1515 * @memberOf _.templateSettings
1518 'evaluate': reEvaluate,
1521 * Used to detect `data` property values to inject.
1523 * @memberOf _.templateSettings
1526 'interpolate': reInterpolate,
1529 * Used to reference the data object in the template text.
1531 * @memberOf _.templateSettings
1537 * Used to import variables into the compiled template.
1539 * @memberOf _.templateSettings
1545 * A reference to the `lodash` function.
1547 * @memberOf _.templateSettings.imports
1554 // Ensure wrappers are instances of `baseLodash`.
1555 lodash.prototype = baseLodash.prototype;
1556 lodash.prototype.constructor = lodash;
1558 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
1559 LodashWrapper.prototype.constructor = LodashWrapper;
1561 /*------------------------------------------------------------------------*/
1564 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
1568 * @param {*} value The value to wrap.
1570 function LazyWrapper(value) {
1571 this.__wrapped__ = value;
1572 this.__actions__ = [];
1574 this.__filtered__ = false;
1575 this.__iteratees__ = [];
1576 this.__takeCount__ = MAX_ARRAY_LENGTH;
1577 this.__views__ = [];
1581 * Creates a clone of the lazy wrapper object.
1585 * @memberOf LazyWrapper
1586 * @returns {Object} Returns the cloned `LazyWrapper` object.
1588 function lazyClone() {
1589 var result = new LazyWrapper(this.__wrapped__);
1590 result.__actions__ = copyArray(this.__actions__);
1591 result.__dir__ = this.__dir__;
1592 result.__filtered__ = this.__filtered__;
1593 result.__iteratees__ = copyArray(this.__iteratees__);
1594 result.__takeCount__ = this.__takeCount__;
1595 result.__views__ = copyArray(this.__views__);
1600 * Reverses the direction of lazy iteration.
1604 * @memberOf LazyWrapper
1605 * @returns {Object} Returns the new reversed `LazyWrapper` object.
1607 function lazyReverse() {
1608 if (this.__filtered__) {
1609 var result = new LazyWrapper(this);
1610 result.__dir__ = -1;
1611 result.__filtered__ = true;
1613 result = this.clone();
1614 result.__dir__ *= -1;
1620 * Extracts the unwrapped value from its lazy wrapper.
1624 * @memberOf LazyWrapper
1625 * @returns {*} Returns the unwrapped value.
1627 function lazyValue() {
1628 var array = this.__wrapped__.value(),
1630 isArr = isArray(array),
1632 arrLength = isArr ? array.length : 0,
1633 view = getView(0, arrLength, this.__views__),
1636 length = end - start,
1637 index = isRight ? end : (start - 1),
1638 iteratees = this.__iteratees__,
1639 iterLength = iteratees.length,
1641 takeCount = nativeMin(length, this.__takeCount__);
1643 if (!isArr || arrLength < LARGE_ARRAY_SIZE ||
1644 (arrLength == length && takeCount == length)) {
1645 return baseWrapperValue(array, this.__actions__);
1650 while (length-- && resIndex < takeCount) {
1654 value = array[index];
1656 while (++iterIndex < iterLength) {
1657 var data = iteratees[iterIndex],
1658 iteratee = data.iteratee,
1660 computed = iteratee(value);
1662 if (type == LAZY_MAP_FLAG) {
1664 } else if (!computed) {
1665 if (type == LAZY_FILTER_FLAG) {
1672 result[resIndex++] = value;
1677 // Ensure `LazyWrapper` is an instance of `baseLodash`.
1678 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
1679 LazyWrapper.prototype.constructor = LazyWrapper;
1681 /*------------------------------------------------------------------------*/
1684 * Creates a hash object.
1688 * @returns {Object} Returns the new hash object.
1693 * Removes `key` and its value from the hash.
1696 * @param {Object} hash The hash to modify.
1697 * @param {string} key The key of the value to remove.
1698 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1700 function hashDelete(hash, key) {
1701 return hashHas(hash, key) && delete hash[key];
1705 * Gets the hash value for `key`.
1708 * @param {Object} hash The hash to query.
1709 * @param {string} key The key of the value to get.
1710 * @returns {*} Returns the entry value.
1712 function hashGet(hash, key) {
1714 var result = hash[key];
1715 return result === HASH_UNDEFINED ? undefined : result;
1717 return hasOwnProperty.call(hash, key) ? hash[key] : undefined;
1721 * Checks if a hash value for `key` exists.
1724 * @param {Object} hash The hash to query.
1725 * @param {string} key The key of the entry to check.
1726 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1728 function hashHas(hash, key) {
1729 return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key);
1733 * Sets the hash `key` to `value`.
1736 * @param {Object} hash The hash to modify.
1737 * @param {string} key The key of the value to set.
1738 * @param {*} value The value to set.
1740 function hashSet(hash, key, value) {
1741 hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
1744 // Avoid inheriting from `Object.prototype` when possible.
1745 Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto;
1747 /*------------------------------------------------------------------------*/
1750 * Creates a map cache object to store key-value pairs.
1754 * @param {Array} [values] The values to cache.
1756 function MapCache(values) {
1758 length = values ? values.length : 0;
1761 while (++index < length) {
1762 var entry = values[index];
1763 this.set(entry[0], entry[1]);
1768 * Removes all key-value entries from the map.
1772 * @memberOf MapCache
1774 function mapClear() {
1777 'map': Map ? new Map : [],
1783 * Removes `key` and its value from the map.
1787 * @memberOf MapCache
1788 * @param {string} key The key of the value to remove.
1789 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1791 function mapDelete(key) {
1792 var data = this.__data__;
1793 if (isKeyable(key)) {
1794 return hashDelete(typeof key == 'string' ? data.string : data.hash, key);
1796 return Map ? data.map['delete'](key) : assocDelete(data.map, key);
1800 * Gets the map value for `key`.
1804 * @memberOf MapCache
1805 * @param {string} key The key of the value to get.
1806 * @returns {*} Returns the entry value.
1808 function mapGet(key) {
1809 var data = this.__data__;
1810 if (isKeyable(key)) {
1811 return hashGet(typeof key == 'string' ? data.string : data.hash, key);
1813 return Map ? data.map.get(key) : assocGet(data.map, key);
1817 * Checks if a map value for `key` exists.
1821 * @memberOf MapCache
1822 * @param {string} key The key of the entry to check.
1823 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1825 function mapHas(key) {
1826 var data = this.__data__;
1827 if (isKeyable(key)) {
1828 return hashHas(typeof key == 'string' ? data.string : data.hash, key);
1830 return Map ? data.map.has(key) : assocHas(data.map, key);
1834 * Sets the map `key` to `value`.
1838 * @memberOf MapCache
1839 * @param {string} key The key of the value to set.
1840 * @param {*} value The value to set.
1841 * @returns {Object} Returns the map cache instance.
1843 function mapSet(key, value) {
1844 var data = this.__data__;
1845 if (isKeyable(key)) {
1846 hashSet(typeof key == 'string' ? data.string : data.hash, key, value);
1848 data.map.set(key, value);
1850 assocSet(data.map, key, value);
1855 // Add methods to `MapCache`.
1856 MapCache.prototype.clear = mapClear;
1857 MapCache.prototype['delete'] = mapDelete;
1858 MapCache.prototype.get = mapGet;
1859 MapCache.prototype.has = mapHas;
1860 MapCache.prototype.set = mapSet;
1862 /*------------------------------------------------------------------------*/
1866 * Creates a set cache object to store unique values.
1870 * @param {Array} [values] The values to cache.
1872 function SetCache(values) {
1874 length = values ? values.length : 0;
1876 this.__data__ = new MapCache;
1877 while (++index < length) {
1878 this.push(values[index]);
1883 * Checks if `value` is in `cache`.
1886 * @param {Object} cache The set cache to search.
1887 * @param {*} value The value to search for.
1888 * @returns {number} Returns `true` if `value` is found, else `false`.
1890 function cacheHas(cache, value) {
1891 var map = cache.__data__;
1892 if (isKeyable(value)) {
1893 var data = map.__data__,
1894 hash = typeof value == 'string' ? data.string : data.hash;
1896 return hash[value] === HASH_UNDEFINED;
1898 return map.has(value);
1902 * Adds `value` to the set cache.
1906 * @memberOf SetCache
1907 * @param {*} value The value to cache.
1909 function cachePush(value) {
1910 var map = this.__data__;
1911 if (isKeyable(value)) {
1912 var data = map.__data__,
1913 hash = typeof value == 'string' ? data.string : data.hash;
1915 hash[value] = HASH_UNDEFINED;
1918 map.set(value, HASH_UNDEFINED);
1922 // Add methods to `SetCache`.
1923 SetCache.prototype.push = cachePush;
1925 /*------------------------------------------------------------------------*/
1928 * Creates a stack cache object to store key-value pairs.
1932 * @param {Array} [values] The values to cache.
1934 function Stack(values) {
1936 length = values ? values.length : 0;
1939 while (++index < length) {
1940 var entry = values[index];
1941 this.set(entry[0], entry[1]);
1946 * Removes all key-value entries from the stack.
1952 function stackClear() {
1953 this.__data__ = { 'array': [], 'map': null };
1957 * Removes `key` and its value from the stack.
1962 * @param {string} key The key of the value to remove.
1963 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1965 function stackDelete(key) {
1966 var data = this.__data__,
1969 return array ? assocDelete(array, key) : data.map['delete'](key);
1973 * Gets the stack value for `key`.
1978 * @param {string} key The key of the value to get.
1979 * @returns {*} Returns the entry value.
1981 function stackGet(key) {
1982 var data = this.__data__,
1985 return array ? assocGet(array, key) : data.map.get(key);
1989 * Checks if a stack value for `key` exists.
1994 * @param {string} key The key of the entry to check.
1995 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1997 function stackHas(key) {
1998 var data = this.__data__,
2001 return array ? assocHas(array, key) : data.map.has(key);
2005 * Sets the stack `key` to `value`.
2010 * @param {string} key The key of the value to set.
2011 * @param {*} value The value to set.
2012 * @returns {Object} Returns the stack cache instance.
2014 function stackSet(key, value) {
2015 var data = this.__data__,
2019 if (array.length < (LARGE_ARRAY_SIZE - 1)) {
2020 assocSet(array, key, value);
2023 data.map = new MapCache(array);
2028 map.set(key, value);
2033 // Add methods to `Stack`.
2034 Stack.prototype.clear = stackClear;
2035 Stack.prototype['delete'] = stackDelete;
2036 Stack.prototype.get = stackGet;
2037 Stack.prototype.has = stackHas;
2038 Stack.prototype.set = stackSet;
2040 /*------------------------------------------------------------------------*/
2043 * Removes `key` and its value from the associative array.
2046 * @param {Array} array The array to modify.
2047 * @param {string} key The key of the value to remove.
2048 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2050 function assocDelete(array, key) {
2051 var index = assocIndexOf(array, key);
2055 var lastIndex = array.length - 1;
2056 if (index == lastIndex) {
2059 splice.call(array, index, 1);
2065 * Gets the associative array value for `key`.
2068 * @param {Array} array The array to query.
2069 * @param {string} key The key of the value to get.
2070 * @returns {*} Returns the entry value.
2072 function assocGet(array, key) {
2073 var index = assocIndexOf(array, key);
2074 return index < 0 ? undefined : array[index][1];
2078 * Checks if an associative array value for `key` exists.
2081 * @param {Array} array The array to query.
2082 * @param {string} key The key of the entry to check.
2083 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2085 function assocHas(array, key) {
2086 return assocIndexOf(array, key) > -1;
2090 * Gets the index at which the `key` is found in `array` of key-value pairs.
2093 * @param {Array} array The array to search.
2094 * @param {*} key The key to search for.
2095 * @returns {number} Returns the index of the matched value, else `-1`.
2097 function assocIndexOf(array, key) {
2098 var length = array.length;
2100 if (eq(array[length][0], key)) {
2108 * Sets the associative array `key` to `value`.
2111 * @param {Array} array The array to modify.
2112 * @param {string} key The key of the value to set.
2113 * @param {*} value The value to set.
2115 function assocSet(array, key, value) {
2116 var index = assocIndexOf(array, key);
2118 array.push([key, value]);
2120 array[index][1] = value;
2124 /*------------------------------------------------------------------------*/
2127 * Used by `_.defaults` to customize its `_.assignIn` use.
2130 * @param {*} objValue The destination value.
2131 * @param {*} srcValue The source value.
2132 * @param {string} key The key of the property to assign.
2133 * @param {Object} object The parent object of `objValue`.
2134 * @returns {*} Returns the value to assign.
2136 function assignInDefaults(objValue, srcValue, key, object) {
2137 if (objValue === undefined ||
2138 (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
2145 * This function is like `assignValue` except that it doesn't assign
2146 * `undefined` values.
2149 * @param {Object} object The object to modify.
2150 * @param {string} key The key of the property to assign.
2151 * @param {*} value The value to assign.
2153 function assignMergeValue(object, key, value) {
2154 if ((value !== undefined && !eq(object[key], value)) ||
2155 (typeof key == 'number' && value === undefined && !(key in object))) {
2156 object[key] = value;
2161 * Assigns `value` to `key` of `object` if the existing value is not equivalent
2162 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
2163 * for equality comparisons.
2166 * @param {Object} object The object to modify.
2167 * @param {string} key The key of the property to assign.
2168 * @param {*} value The value to assign.
2170 function assignValue(object, key, value) {
2171 var objValue = object[key];
2172 if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
2173 (value === undefined && !(key in object))) {
2174 object[key] = value;
2179 * Aggregates elements of `collection` on `accumulator` with keys transformed
2180 * by `iteratee` and values set by `setter`.
2183 * @param {Array|Object} collection The collection to iterate over.
2184 * @param {Function} setter The function to set `accumulator` values.
2185 * @param {Function} iteratee The iteratee to transform keys.
2186 * @param {Object} accumulator The initial aggregated object.
2187 * @returns {Function} Returns `accumulator`.
2189 function baseAggregator(collection, setter, iteratee, accumulator) {
2190 baseEach(collection, function(value, key, collection) {
2191 setter(accumulator, value, iteratee(value), collection);
2197 * The base implementation of `_.assign` without support for multiple sources
2198 * or `customizer` functions.
2201 * @param {Object} object The destination object.
2202 * @param {Object} source The source object.
2203 * @returns {Object} Returns `object`.
2205 function baseAssign(object, source) {
2206 return object && copyObject(source, keys(source), object);
2210 * The base implementation of `_.at` without support for individual paths.
2213 * @param {Object} object The object to iterate over.
2214 * @param {string[]} paths The property paths of elements to pick.
2215 * @returns {Array} Returns the new array of picked elements.
2217 function baseAt(object, paths) {
2219 isNil = object == null,
2220 length = paths.length,
2221 result = Array(length);
2223 while (++index < length) {
2224 result[index] = isNil ? undefined : get(object, paths[index]);
2230 * The base implementation of `_.clamp` which doesn't coerce arguments to numbers.
2233 * @param {number} number The number to clamp.
2234 * @param {number} [lower] The lower bound.
2235 * @param {number} upper The upper bound.
2236 * @returns {number} Returns the clamped number.
2238 function baseClamp(number, lower, upper) {
2239 if (number === number) {
2240 if (upper !== undefined) {
2241 number = number <= upper ? number : upper;
2243 if (lower !== undefined) {
2244 number = number >= lower ? number : lower;
2251 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
2252 * traversed objects.
2255 * @param {*} value The value to clone.
2256 * @param {boolean} [isDeep] Specify a deep clone.
2257 * @param {boolean} [isFull] Specify a clone including symbols.
2258 * @param {Function} [customizer] The function to customize cloning.
2259 * @param {string} [key] The key of `value`.
2260 * @param {Object} [object] The parent object of `value`.
2261 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
2262 * @returns {*} Returns the cloned value.
2264 function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
2267 result = object ? customizer(value, key, object, stack) : customizer(value);
2269 if (result !== undefined) {
2272 if (!isObject(value)) {
2275 var isArr = isArray(value);
2277 result = initCloneArray(value);
2279 return copyArray(value, result);
2282 var tag = getTag(value),
2283 isFunc = tag == funcTag || tag == genTag;
2285 if (isBuffer(value)) {
2286 return cloneBuffer(value, isDeep);
2288 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
2289 if (isHostObject(value)) {
2290 return object ? value : {};
2292 result = initCloneObject(isFunc ? {} : value);
2294 return copySymbols(value, baseAssign(result, value));
2297 if (!cloneableTags[tag]) {
2298 return object ? value : {};
2300 result = initCloneByTag(value, tag, baseClone, isDeep);
2303 // Check for circular references and return its corresponding clone.
2304 stack || (stack = new Stack);
2305 var stacked = stack.get(value);
2309 stack.set(value, result);
2312 var props = isFull ? getAllKeys(value) : keys(value);
2314 // Recursively populate clone (susceptible to call stack limits).
2315 arrayEach(props || value, function(subValue, key) {
2318 subValue = value[key];
2320 assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
2326 * The base implementation of `_.conforms` which doesn't clone `source`.
2329 * @param {Object} source The object of property predicates to conform to.
2330 * @returns {Function} Returns the new function.
2332 function baseConforms(source) {
2333 var props = keys(source),
2334 length = props.length;
2336 return function(object) {
2337 if (object == null) {
2342 var key = props[index],
2343 predicate = source[key],
2344 value = object[key];
2346 if ((value === undefined &&
2347 !(key in Object(object))) || !predicate(value)) {
2356 * The base implementation of `_.create` without support for assigning
2357 * properties to the created object.
2360 * @param {Object} prototype The object to inherit from.
2361 * @returns {Object} Returns the new object.
2363 function baseCreate(proto) {
2364 return isObject(proto) ? objectCreate(proto) : {};
2368 * The base implementation of `_.delay` and `_.defer` which accepts an array
2369 * of `func` arguments.
2372 * @param {Function} func The function to delay.
2373 * @param {number} wait The number of milliseconds to delay invocation.
2374 * @param {Object} args The arguments to provide to `func`.
2375 * @returns {number} Returns the timer id.
2377 function baseDelay(func, wait, args) {
2378 if (typeof func != 'function') {
2379 throw new TypeError(FUNC_ERROR_TEXT);
2381 return setTimeout(function() { func.apply(undefined, args); }, wait);
2385 * The base implementation of methods like `_.difference` without support
2386 * for excluding multiple arrays or iteratee shorthands.
2389 * @param {Array} array The array to inspect.
2390 * @param {Array} values The values to exclude.
2391 * @param {Function} [iteratee] The iteratee invoked per element.
2392 * @param {Function} [comparator] The comparator invoked per element.
2393 * @returns {Array} Returns the new array of filtered values.
2395 function baseDifference(array, values, iteratee, comparator) {
2397 includes = arrayIncludes,
2399 length = array.length,
2401 valuesLength = values.length;
2407 values = arrayMap(values, baseUnary(iteratee));
2410 includes = arrayIncludesWith;
2413 else if (values.length >= LARGE_ARRAY_SIZE) {
2414 includes = cacheHas;
2416 values = new SetCache(values);
2419 while (++index < length) {
2420 var value = array[index],
2421 computed = iteratee ? iteratee(value) : value;
2423 value = (comparator || value !== 0) ? value : 0;
2424 if (isCommon && computed === computed) {
2425 var valuesIndex = valuesLength;
2426 while (valuesIndex--) {
2427 if (values[valuesIndex] === computed) {
2433 else if (!includes(values, computed, comparator)) {
2441 * The base implementation of `_.forEach` without support for iteratee shorthands.
2444 * @param {Array|Object} collection The collection to iterate over.
2445 * @param {Function} iteratee The function invoked per iteration.
2446 * @returns {Array|Object} Returns `collection`.
2448 var baseEach = createBaseEach(baseForOwn);
2451 * The base implementation of `_.forEachRight` without support for iteratee shorthands.
2454 * @param {Array|Object} collection The collection to iterate over.
2455 * @param {Function} iteratee The function invoked per iteration.
2456 * @returns {Array|Object} Returns `collection`.
2458 var baseEachRight = createBaseEach(baseForOwnRight, true);
2461 * The base implementation of `_.every` without support for iteratee shorthands.
2464 * @param {Array|Object} collection The collection to iterate over.
2465 * @param {Function} predicate The function invoked per iteration.
2466 * @returns {boolean} Returns `true` if all elements pass the predicate check,
2469 function baseEvery(collection, predicate) {
2471 baseEach(collection, function(value, index, collection) {
2472 result = !!predicate(value, index, collection);
2479 * The base implementation of methods like `_.max` and `_.min` which accepts a
2480 * `comparator` to determine the extremum value.
2483 * @param {Array} array The array to iterate over.
2484 * @param {Function} iteratee The iteratee invoked per iteration.
2485 * @param {Function} comparator The comparator used to compare values.
2486 * @returns {*} Returns the extremum value.
2488 function baseExtremum(array, iteratee, comparator) {
2490 length = array.length;
2492 while (++index < length) {
2493 var value = array[index],
2494 current = iteratee(value);
2496 if (current != null && (computed === undefined
2497 ? (current === current && !isSymbol(current))
2498 : comparator(current, computed)
2500 var computed = current,
2508 * The base implementation of `_.fill` without an iteratee call guard.
2511 * @param {Array} array The array to fill.
2512 * @param {*} value The value to fill `array` with.
2513 * @param {number} [start=0] The start position.
2514 * @param {number} [end=array.length] The end position.
2515 * @returns {Array} Returns `array`.
2517 function baseFill(array, value, start, end) {
2518 var length = array.length;
2520 start = toInteger(start);
2522 start = -start > length ? 0 : (length + start);
2524 end = (end === undefined || end > length) ? length : toInteger(end);
2528 end = start > end ? 0 : toLength(end);
2529 while (start < end) {
2530 array[start++] = value;
2536 * The base implementation of `_.filter` without support for iteratee shorthands.
2539 * @param {Array|Object} collection The collection to iterate over.
2540 * @param {Function} predicate The function invoked per iteration.
2541 * @returns {Array} Returns the new filtered array.
2543 function baseFilter(collection, predicate) {
2545 baseEach(collection, function(value, index, collection) {
2546 if (predicate(value, index, collection)) {
2554 * The base implementation of `_.flatten` with support for restricting flattening.
2557 * @param {Array} array The array to flatten.
2558 * @param {number} depth The maximum recursion depth.
2559 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
2560 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
2561 * @param {Array} [result=[]] The initial result value.
2562 * @returns {Array} Returns the new flattened array.
2564 function baseFlatten(array, depth, predicate, isStrict, result) {
2566 length = array.length;
2568 predicate || (predicate = isFlattenable);
2569 result || (result = []);
2571 while (++index < length) {
2572 var value = array[index];
2573 if (depth > 0 && predicate(value)) {
2575 // Recursively flatten arrays (susceptible to call stack limits).
2576 baseFlatten(value, depth - 1, predicate, isStrict, result);
2578 arrayPush(result, value);
2580 } else if (!isStrict) {
2581 result[result.length] = value;
2588 * The base implementation of `baseForOwn` which iterates over `object`
2589 * properties returned by `keysFunc` and invokes `iteratee` for each property.
2590 * Iteratee functions may exit iteration early by explicitly returning `false`.
2593 * @param {Object} object The object to iterate over.
2594 * @param {Function} iteratee The function invoked per iteration.
2595 * @param {Function} keysFunc The function to get the keys of `object`.
2596 * @returns {Object} Returns `object`.
2598 var baseFor = createBaseFor();
2601 * This function is like `baseFor` except that it iterates over properties
2602 * in the opposite order.
2605 * @param {Object} object The object to iterate over.
2606 * @param {Function} iteratee The function invoked per iteration.
2607 * @param {Function} keysFunc The function to get the keys of `object`.
2608 * @returns {Object} Returns `object`.
2610 var baseForRight = createBaseFor(true);
2613 * The base implementation of `_.forOwn` without support for iteratee shorthands.
2616 * @param {Object} object The object to iterate over.
2617 * @param {Function} iteratee The function invoked per iteration.
2618 * @returns {Object} Returns `object`.
2620 function baseForOwn(object, iteratee) {
2621 return object && baseFor(object, iteratee, keys);
2625 * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
2628 * @param {Object} object The object to iterate over.
2629 * @param {Function} iteratee The function invoked per iteration.
2630 * @returns {Object} Returns `object`.
2632 function baseForOwnRight(object, iteratee) {
2633 return object && baseForRight(object, iteratee, keys);
2637 * The base implementation of `_.functions` which creates an array of
2638 * `object` function property names filtered from `props`.
2641 * @param {Object} object The object to inspect.
2642 * @param {Array} props The property names to filter.
2643 * @returns {Array} Returns the new array of filtered property names.
2645 function baseFunctions(object, props) {
2646 return arrayFilter(props, function(key) {
2647 return isFunction(object[key]);
2652 * The base implementation of `_.get` without support for default values.
2655 * @param {Object} object The object to query.
2656 * @param {Array|string} path The path of the property to get.
2657 * @returns {*} Returns the resolved value.
2659 function baseGet(object, path) {
2660 path = isKey(path, object) ? [path] : castPath(path);
2663 length = path.length;
2665 while (object != null && index < length) {
2666 object = object[toKey(path[index++])];
2668 return (index && index == length) ? object : undefined;
2672 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
2673 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
2674 * symbols of `object`.
2677 * @param {Object} object The object to query.
2678 * @param {Function} keysFunc The function to get the keys of `object`.
2679 * @param {Function} symbolsFunc The function to get the symbols of `object`.
2680 * @returns {Array} Returns the array of property names and symbols.
2682 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
2683 var result = keysFunc(object);
2684 return isArray(object)
2686 : arrayPush(result, symbolsFunc(object));
2690 * The base implementation of `_.gt` which doesn't coerce arguments to numbers.
2693 * @param {*} value The value to compare.
2694 * @param {*} other The other value to compare.
2695 * @returns {boolean} Returns `true` if `value` is greater than `other`,
2698 function baseGt(value, other) {
2699 return value > other;
2703 * The base implementation of `_.has` without support for deep paths.
2706 * @param {Object} object The object to query.
2707 * @param {Array|string} key The key to check.
2708 * @returns {boolean} Returns `true` if `key` exists, else `false`.
2710 function baseHas(object, key) {
2711 // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
2712 // that are composed entirely of index properties, return `false` for
2713 // `hasOwnProperty` checks of them.
2714 return hasOwnProperty.call(object, key) ||
2715 (typeof object == 'object' && key in object && getPrototype(object) === null);
2719 * The base implementation of `_.hasIn` without support for deep paths.
2722 * @param {Object} object The object to query.
2723 * @param {Array|string} key The key to check.
2724 * @returns {boolean} Returns `true` if `key` exists, else `false`.
2726 function baseHasIn(object, key) {
2727 return key in Object(object);
2731 * The base implementation of `_.inRange` which doesn't coerce arguments to numbers.
2734 * @param {number} number The number to check.
2735 * @param {number} start The start of the range.
2736 * @param {number} end The end of the range.
2737 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
2739 function baseInRange(number, start, end) {
2740 return number >= nativeMin(start, end) && number < nativeMax(start, end);
2744 * The base implementation of methods like `_.intersection`, without support
2745 * for iteratee shorthands, that accepts an array of arrays to inspect.
2748 * @param {Array} arrays The arrays to inspect.
2749 * @param {Function} [iteratee] The iteratee invoked per element.
2750 * @param {Function} [comparator] The comparator invoked per element.
2751 * @returns {Array} Returns the new array of shared values.
2753 function baseIntersection(arrays, iteratee, comparator) {
2754 var includes = comparator ? arrayIncludesWith : arrayIncludes,
2755 length = arrays[0].length,
2756 othLength = arrays.length,
2757 othIndex = othLength,
2758 caches = Array(othLength),
2759 maxLength = Infinity,
2762 while (othIndex--) {
2763 var array = arrays[othIndex];
2764 if (othIndex && iteratee) {
2765 array = arrayMap(array, baseUnary(iteratee));
2767 maxLength = nativeMin(array.length, maxLength);
2768 caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
2769 ? new SetCache(othIndex && array)
2778 while (++index < length && result.length < maxLength) {
2779 var value = array[index],
2780 computed = iteratee ? iteratee(value) : value;
2782 value = (comparator || value !== 0) ? value : 0;
2784 ? cacheHas(seen, computed)
2785 : includes(result, computed, comparator)
2787 othIndex = othLength;
2788 while (--othIndex) {
2789 var cache = caches[othIndex];
2791 ? cacheHas(cache, computed)
2792 : includes(arrays[othIndex], computed, comparator))
2798 seen.push(computed);
2807 * The base implementation of `_.invert` and `_.invertBy` which inverts
2808 * `object` with values transformed by `iteratee` and set by `setter`.
2811 * @param {Object} object The object to iterate over.
2812 * @param {Function} setter The function to set `accumulator` values.
2813 * @param {Function} iteratee The iteratee to transform values.
2814 * @param {Object} accumulator The initial inverted object.
2815 * @returns {Function} Returns `accumulator`.
2817 function baseInverter(object, setter, iteratee, accumulator) {
2818 baseForOwn(object, function(value, key, object) {
2819 setter(accumulator, iteratee(value), key, object);
2825 * The base implementation of `_.invoke` without support for individual
2829 * @param {Object} object The object to query.
2830 * @param {Array|string} path The path of the method to invoke.
2831 * @param {Array} args The arguments to invoke the method with.
2832 * @returns {*} Returns the result of the invoked method.
2834 function baseInvoke(object, path, args) {
2835 if (!isKey(path, object)) {
2836 path = castPath(path);
2837 object = parent(object, path);
2840 var func = object == null ? object : object[toKey(path)];
2841 return func == null ? undefined : apply(func, object, args);
2845 * The base implementation of `_.isEqual` which supports partial comparisons
2846 * and tracks traversed objects.
2849 * @param {*} value The value to compare.
2850 * @param {*} other The other value to compare.
2851 * @param {Function} [customizer] The function to customize comparisons.
2852 * @param {boolean} [bitmask] The bitmask of comparison flags.
2853 * The bitmask may be composed of the following flags:
2854 * 1 - Unordered comparison
2855 * 2 - Partial comparison
2856 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
2857 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
2859 function baseIsEqual(value, other, customizer, bitmask, stack) {
2860 if (value === other) {
2863 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
2864 return value !== value && other !== other;
2866 return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
2870 * A specialized version of `baseIsEqual` for arrays and objects which performs
2871 * deep comparisons and tracks traversed objects enabling objects with circular
2872 * references to be compared.
2875 * @param {Object} object The object to compare.
2876 * @param {Object} other The other object to compare.
2877 * @param {Function} equalFunc The function to determine equivalents of values.
2878 * @param {Function} [customizer] The function to customize comparisons.
2879 * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
2881 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
2882 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
2884 function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
2885 var objIsArr = isArray(object),
2886 othIsArr = isArray(other),
2891 objTag = getTag(object);
2892 objTag = objTag == argsTag ? objectTag : objTag;
2895 othTag = getTag(other);
2896 othTag = othTag == argsTag ? objectTag : othTag;
2898 var objIsObj = objTag == objectTag && !isHostObject(object),
2899 othIsObj = othTag == objectTag && !isHostObject(other),
2900 isSameTag = objTag == othTag;
2902 if (isSameTag && !objIsObj) {
2903 stack || (stack = new Stack);
2904 return (objIsArr || isTypedArray(object))
2905 ? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
2906 : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
2908 if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
2909 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
2910 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
2912 if (objIsWrapped || othIsWrapped) {
2913 var objUnwrapped = objIsWrapped ? object.value() : object,
2914 othUnwrapped = othIsWrapped ? other.value() : other;
2916 stack || (stack = new Stack);
2917 return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
2923 stack || (stack = new Stack);
2924 return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
2928 * The base implementation of `_.isMatch` without support for iteratee shorthands.
2931 * @param {Object} object The object to inspect.
2932 * @param {Object} source The object of property values to match.
2933 * @param {Array} matchData The property names, values, and compare flags to match.
2934 * @param {Function} [customizer] The function to customize comparisons.
2935 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
2937 function baseIsMatch(object, source, matchData, customizer) {
2938 var index = matchData.length,
2940 noCustomizer = !customizer;
2942 if (object == null) {
2945 object = Object(object);
2947 var data = matchData[index];
2948 if ((noCustomizer && data[2])
2949 ? data[1] !== object[data[0]]
2950 : !(data[0] in object)
2955 while (++index < length) {
2956 data = matchData[index];
2958 objValue = object[key],
2961 if (noCustomizer && data[2]) {
2962 if (objValue === undefined && !(key in object)) {
2966 var stack = new Stack;
2968 var result = customizer(objValue, srcValue, key, object, source, stack);
2970 if (!(result === undefined
2971 ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
2982 * The base implementation of `_.iteratee`.
2985 * @param {*} [value=_.identity] The value to convert to an iteratee.
2986 * @returns {Function} Returns the iteratee.
2988 function baseIteratee(value) {
2989 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
2990 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
2991 if (typeof value == 'function') {
2994 if (value == null) {
2997 if (typeof value == 'object') {
2998 return isArray(value)
2999 ? baseMatchesProperty(value[0], value[1])
3000 : baseMatches(value);
3002 return property(value);
3006 * The base implementation of `_.keys` which doesn't skip the constructor
3007 * property of prototypes or treat sparse arrays as dense.
3010 * @param {Object} object The object to query.
3011 * @returns {Array} Returns the array of property names.
3013 function baseKeys(object) {
3014 return nativeKeys(Object(object));
3018 * The base implementation of `_.keysIn` which doesn't skip the constructor
3019 * property of prototypes or treat sparse arrays as dense.
3022 * @param {Object} object The object to query.
3023 * @returns {Array} Returns the array of property names.
3025 function baseKeysIn(object) {
3026 object = object == null ? object : Object(object);
3029 for (var key in object) {
3035 // Fallback for IE < 9 with es6-shim.
3036 if (enumerate && !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf')) {
3037 baseKeysIn = function(object) {
3038 return iteratorToArray(enumerate(object));
3043 * The base implementation of `_.lt` which doesn't coerce arguments to numbers.
3046 * @param {*} value The value to compare.
3047 * @param {*} other The other value to compare.
3048 * @returns {boolean} Returns `true` if `value` is less than `other`,
3051 function baseLt(value, other) {
3052 return value < other;
3056 * The base implementation of `_.map` without support for iteratee shorthands.
3059 * @param {Array|Object} collection The collection to iterate over.
3060 * @param {Function} iteratee The function invoked per iteration.
3061 * @returns {Array} Returns the new mapped array.
3063 function baseMap(collection, iteratee) {
3065 result = isArrayLike(collection) ? Array(collection.length) : [];
3067 baseEach(collection, function(value, key, collection) {
3068 result[++index] = iteratee(value, key, collection);
3074 * The base implementation of `_.matches` which doesn't clone `source`.
3077 * @param {Object} source The object of property values to match.
3078 * @returns {Function} Returns the new function.
3080 function baseMatches(source) {
3081 var matchData = getMatchData(source);
3082 if (matchData.length == 1 && matchData[0][2]) {
3083 return matchesStrictComparable(matchData[0][0], matchData[0][1]);
3085 return function(object) {
3086 return object === source || baseIsMatch(object, source, matchData);
3091 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
3094 * @param {string} path The path of the property to get.
3095 * @param {*} srcValue The value to match.
3096 * @returns {Function} Returns the new function.
3098 function baseMatchesProperty(path, srcValue) {
3099 if (isKey(path) && isStrictComparable(srcValue)) {
3100 return matchesStrictComparable(toKey(path), srcValue);
3102 return function(object) {
3103 var objValue = get(object, path);
3104 return (objValue === undefined && objValue === srcValue)
3105 ? hasIn(object, path)
3106 : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
3111 * The base implementation of `_.merge` without support for multiple sources.
3114 * @param {Object} object The destination object.
3115 * @param {Object} source The source object.
3116 * @param {number} srcIndex The index of `source`.
3117 * @param {Function} [customizer] The function to customize merged values.
3118 * @param {Object} [stack] Tracks traversed source values and their merged
3121 function baseMerge(object, source, srcIndex, customizer, stack) {
3122 if (object === source) {
3125 if (!(isArray(source) || isTypedArray(source))) {
3126 var props = keysIn(source);
3128 arrayEach(props || source, function(srcValue, key) {
3131 srcValue = source[key];
3133 if (isObject(srcValue)) {
3134 stack || (stack = new Stack);
3135 baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
3138 var newValue = customizer
3139 ? customizer(object[key], srcValue, (key + ''), object, source, stack)
3142 if (newValue === undefined) {
3143 newValue = srcValue;
3145 assignMergeValue(object, key, newValue);
3151 * A specialized version of `baseMerge` for arrays and objects which performs
3152 * deep merges and tracks traversed objects enabling objects with circular
3153 * references to be merged.
3156 * @param {Object} object The destination object.
3157 * @param {Object} source The source object.
3158 * @param {string} key The key of the value to merge.
3159 * @param {number} srcIndex The index of `source`.
3160 * @param {Function} mergeFunc The function to merge values.
3161 * @param {Function} [customizer] The function to customize assigned values.
3162 * @param {Object} [stack] Tracks traversed source values and their merged
3165 function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
3166 var objValue = object[key],
3167 srcValue = source[key],
3168 stacked = stack.get(srcValue);
3171 assignMergeValue(object, key, stacked);
3174 var newValue = customizer
3175 ? customizer(objValue, srcValue, (key + ''), object, source, stack)
3178 var isCommon = newValue === undefined;
3181 newValue = srcValue;
3182 if (isArray(srcValue) || isTypedArray(srcValue)) {
3183 if (isArray(objValue)) {
3184 newValue = objValue;
3186 else if (isArrayLikeObject(objValue)) {
3187 newValue = copyArray(objValue);
3191 newValue = baseClone(srcValue, true);
3194 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
3195 if (isArguments(objValue)) {
3196 newValue = toPlainObject(objValue);
3198 else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
3200 newValue = baseClone(srcValue, true);
3203 newValue = objValue;
3210 stack.set(srcValue, newValue);
3213 // Recursively merge objects and arrays (susceptible to call stack limits).
3214 mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
3216 stack['delete'](srcValue);
3217 assignMergeValue(object, key, newValue);
3221 * The base implementation of `_.nth` which doesn't coerce `n` to an integer.
3224 * @param {Array} array The array to query.
3225 * @param {number} n The index of the element to return.
3226 * @returns {*} Returns the nth element of `array`.
3228 function baseNth(array, n) {
3229 var length = array.length;
3233 n += n < 0 ? length : 0;
3234 return isIndex(n, length) ? array[n] : undefined;
3238 * The base implementation of `_.orderBy` without param guards.
3241 * @param {Array|Object} collection The collection to iterate over.
3242 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
3243 * @param {string[]} orders The sort orders of `iteratees`.
3244 * @returns {Array} Returns the new sorted array.
3246 function baseOrderBy(collection, iteratees, orders) {
3248 iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee()));
3250 var result = baseMap(collection, function(value, key, collection) {
3251 var criteria = arrayMap(iteratees, function(iteratee) {
3252 return iteratee(value);
3254 return { 'criteria': criteria, 'index': ++index, 'value': value };
3257 return baseSortBy(result, function(object, other) {
3258 return compareMultiple(object, other, orders);
3263 * The base implementation of `_.pick` without support for individual
3264 * property identifiers.
3267 * @param {Object} object The source object.
3268 * @param {string[]} props The property identifiers to pick.
3269 * @returns {Object} Returns the new object.
3271 function basePick(object, props) {
3272 object = Object(object);
3273 return arrayReduce(props, function(result, key) {
3274 if (key in object) {
3275 result[key] = object[key];
3282 * The base implementation of `_.pickBy` without support for iteratee shorthands.
3285 * @param {Object} object The source object.
3286 * @param {Function} predicate The function invoked per property.
3287 * @returns {Object} Returns the new object.
3289 function basePickBy(object, predicate) {
3291 props = getAllKeysIn(object),
3292 length = props.length,
3295 while (++index < length) {
3296 var key = props[index],
3297 value = object[key];
3299 if (predicate(value, key)) {
3300 result[key] = value;
3307 * The base implementation of `_.property` without support for deep paths.
3310 * @param {string} key The key of the property to get.
3311 * @returns {Function} Returns the new function.
3313 function baseProperty(key) {
3314 return function(object) {
3315 return object == null ? undefined : object[key];
3320 * A specialized version of `baseProperty` which supports deep paths.
3323 * @param {Array|string} path The path of the property to get.
3324 * @returns {Function} Returns the new function.
3326 function basePropertyDeep(path) {
3327 return function(object) {
3328 return baseGet(object, path);
3333 * The base implementation of `_.pullAllBy` without support for iteratee
3337 * @param {Array} array The array to modify.
3338 * @param {Array} values The values to remove.
3339 * @param {Function} [iteratee] The iteratee invoked per element.
3340 * @param {Function} [comparator] The comparator invoked per element.
3341 * @returns {Array} Returns `array`.
3343 function basePullAll(array, values, iteratee, comparator) {
3344 var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
3346 length = values.length,
3350 seen = arrayMap(array, baseUnary(iteratee));
3352 while (++index < length) {
3354 value = values[index],
3355 computed = iteratee ? iteratee(value) : value;
3357 while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
3358 if (seen !== array) {
3359 splice.call(seen, fromIndex, 1);
3361 splice.call(array, fromIndex, 1);
3368 * The base implementation of `_.pullAt` without support for individual
3369 * indexes or capturing the removed elements.
3372 * @param {Array} array The array to modify.
3373 * @param {number[]} indexes The indexes of elements to remove.
3374 * @returns {Array} Returns `array`.
3376 function basePullAt(array, indexes) {
3377 var length = array ? indexes.length : 0,
3378 lastIndex = length - 1;
3381 var index = indexes[length];
3382 if (length == lastIndex || index !== previous) {
3383 var previous = index;
3384 if (isIndex(index)) {
3385 splice.call(array, index, 1);
3387 else if (!isKey(index, array)) {
3388 var path = castPath(index),
3389 object = parent(array, path);
3391 if (object != null) {
3392 delete object[toKey(last(path))];
3396 delete array[toKey(index)];
3404 * The base implementation of `_.random` without support for returning
3405 * floating-point numbers.
3408 * @param {number} lower The lower bound.
3409 * @param {number} upper The upper bound.
3410 * @returns {number} Returns the random number.
3412 function baseRandom(lower, upper) {
3413 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
3417 * The base implementation of `_.range` and `_.rangeRight` which doesn't
3418 * coerce arguments to numbers.
3421 * @param {number} start The start of the range.
3422 * @param {number} end The end of the range.
3423 * @param {number} step The value to increment or decrement by.
3424 * @param {boolean} [fromRight] Specify iterating from right to left.
3425 * @returns {Array} Returns the new array of numbers.
3427 function baseRange(start, end, step, fromRight) {
3429 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
3430 result = Array(length);
3433 result[fromRight ? length : ++index] = start;
3440 * The base implementation of `_.repeat` which doesn't coerce arguments.
3443 * @param {string} string The string to repeat.
3444 * @param {number} n The number of times to repeat the string.
3445 * @returns {string} Returns the repeated string.
3447 function baseRepeat(string, n) {
3449 if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
3452 // Leverage the exponentiation by squaring algorithm for a faster repeat.
3453 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
3458 n = nativeFloor(n / 2);
3468 * The base implementation of `_.set`.
3471 * @param {Object} object The object to query.
3472 * @param {Array|string} path The path of the property to set.
3473 * @param {*} value The value to set.
3474 * @param {Function} [customizer] The function to customize path creation.
3475 * @returns {Object} Returns `object`.
3477 function baseSet(object, path, value, customizer) {
3478 path = isKey(path, object) ? [path] : castPath(path);
3481 length = path.length,
3482 lastIndex = length - 1,
3485 while (nested != null && ++index < length) {
3486 var key = toKey(path[index]);
3487 if (isObject(nested)) {
3488 var newValue = value;
3489 if (index != lastIndex) {
3490 var objValue = nested[key];
3491 newValue = customizer ? customizer(objValue, key, nested) : undefined;
3492 if (newValue === undefined) {
3493 newValue = objValue == null
3494 ? (isIndex(path[index + 1]) ? [] : {})
3498 assignValue(nested, key, newValue);
3500 nested = nested[key];
3506 * The base implementation of `setData` without support for hot loop detection.
3509 * @param {Function} func The function to associate metadata with.
3510 * @param {*} data The metadata.
3511 * @returns {Function} Returns `func`.
3513 var baseSetData = !metaMap ? identity : function(func, data) {
3514 metaMap.set(func, data);
3519 * The base implementation of `_.slice` without an iteratee call guard.
3522 * @param {Array} array The array to slice.
3523 * @param {number} [start=0] The start position.
3524 * @param {number} [end=array.length] The end position.
3525 * @returns {Array} Returns the slice of `array`.
3527 function baseSlice(array, start, end) {
3529 length = array.length;
3532 start = -start > length ? 0 : (length + start);
3534 end = end > length ? length : end;
3538 length = start > end ? 0 : ((end - start) >>> 0);
3541 var result = Array(length);
3542 while (++index < length) {
3543 result[index] = array[index + start];
3549 * The base implementation of `_.some` without support for iteratee shorthands.
3552 * @param {Array|Object} collection The collection to iterate over.
3553 * @param {Function} predicate The function invoked per iteration.
3554 * @returns {boolean} Returns `true` if any element passes the predicate check,
3557 function baseSome(collection, predicate) {
3560 baseEach(collection, function(value, index, collection) {
3561 result = predicate(value, index, collection);
3568 * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
3569 * performs a binary search of `array` to determine the index at which `value`
3570 * should be inserted into `array` in order to maintain its sort order.
3573 * @param {Array} array The sorted array to inspect.
3574 * @param {*} value The value to evaluate.
3575 * @param {boolean} [retHighest] Specify returning the highest qualified index.
3576 * @returns {number} Returns the index at which `value` should be inserted
3579 function baseSortedIndex(array, value, retHighest) {
3581 high = array ? array.length : low;
3583 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
3584 while (low < high) {
3585 var mid = (low + high) >>> 1,
3586 computed = array[mid];
3588 if (computed !== null && !isSymbol(computed) &&
3589 (retHighest ? (computed <= value) : (computed < value))) {
3597 return baseSortedIndexBy(array, value, identity, retHighest);
3601 * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
3602 * which invokes `iteratee` for `value` and each element of `array` to compute
3603 * their sort ranking. The iteratee is invoked with one argument; (value).
3606 * @param {Array} array The sorted array to inspect.
3607 * @param {*} value The value to evaluate.
3608 * @param {Function} iteratee The iteratee invoked per element.
3609 * @param {boolean} [retHighest] Specify returning the highest qualified index.
3610 * @returns {number} Returns the index at which `value` should be inserted
3613 function baseSortedIndexBy(array, value, iteratee, retHighest) {
3614 value = iteratee(value);
3617 high = array ? array.length : 0,
3618 valIsNaN = value !== value,
3619 valIsNull = value === null,
3620 valIsSymbol = isSymbol(value),
3621 valIsUndefined = value === undefined;
3623 while (low < high) {
3624 var mid = nativeFloor((low + high) / 2),
3625 computed = iteratee(array[mid]),
3626 othIsDefined = computed !== undefined,
3627 othIsNull = computed === null,
3628 othIsReflexive = computed === computed,
3629 othIsSymbol = isSymbol(computed);
3632 var setLow = retHighest || othIsReflexive;
3633 } else if (valIsUndefined) {
3634 setLow = othIsReflexive && (retHighest || othIsDefined);
3635 } else if (valIsNull) {
3636 setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
3637 } else if (valIsSymbol) {
3638 setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
3639 } else if (othIsNull || othIsSymbol) {
3642 setLow = retHighest ? (computed <= value) : (computed < value);
3650 return nativeMin(high, MAX_ARRAY_INDEX);
3654 * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
3655 * support for iteratee shorthands.
3658 * @param {Array} array The array to inspect.
3659 * @param {Function} [iteratee] The iteratee invoked per element.
3660 * @returns {Array} Returns the new duplicate free array.
3662 function baseSortedUniq(array, iteratee) {
3664 length = array.length,
3668 while (++index < length) {
3669 var value = array[index],
3670 computed = iteratee ? iteratee(value) : value;
3672 if (!index || !eq(computed, seen)) {
3673 var seen = computed;
3674 result[resIndex++] = value === 0 ? 0 : value;
3681 * The base implementation of `_.toNumber` which doesn't ensure correct
3682 * conversions of binary, hexadecimal, or octal string values.
3685 * @param {*} value The value to process.
3686 * @returns {number} Returns the number.
3688 function baseToNumber(value) {
3689 if (typeof value == 'number') {
3692 if (isSymbol(value)) {
3699 * The base implementation of `_.toString` which doesn't convert nullish
3700 * values to empty strings.
3703 * @param {*} value The value to process.
3704 * @returns {string} Returns the string.
3706 function baseToString(value) {
3707 // Exit early for strings to avoid a performance hit in some environments.
3708 if (typeof value == 'string') {
3711 if (isSymbol(value)) {
3712 return symbolToString ? symbolToString.call(value) : '';
3714 var result = (value + '');
3715 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
3719 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
3722 * @param {Array} array The array to inspect.
3723 * @param {Function} [iteratee] The iteratee invoked per element.
3724 * @param {Function} [comparator] The comparator invoked per element.
3725 * @returns {Array} Returns the new duplicate free array.
3727 function baseUniq(array, iteratee, comparator) {
3729 includes = arrayIncludes,
3730 length = array.length,
3737 includes = arrayIncludesWith;
3739 else if (length >= LARGE_ARRAY_SIZE) {
3740 var set = iteratee ? null : createSet(array);
3742 return setToArray(set);
3745 includes = cacheHas;
3746 seen = new SetCache;
3749 seen = iteratee ? [] : result;
3752 while (++index < length) {
3753 var value = array[index],
3754 computed = iteratee ? iteratee(value) : value;
3756 value = (comparator || value !== 0) ? value : 0;
3757 if (isCommon && computed === computed) {
3758 var seenIndex = seen.length;
3759 while (seenIndex--) {
3760 if (seen[seenIndex] === computed) {
3765 seen.push(computed);
3769 else if (!includes(seen, computed, comparator)) {
3770 if (seen !== result) {
3771 seen.push(computed);
3780 * The base implementation of `_.unset`.
3783 * @param {Object} object The object to modify.
3784 * @param {Array|string} path The path of the property to unset.
3785 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
3787 function baseUnset(object, path) {
3788 path = isKey(path, object) ? [path] : castPath(path);
3789 object = parent(object, path);
3791 var key = toKey(last(path));
3792 return !(object != null && baseHas(object, key)) || delete object[key];
3796 * The base implementation of `_.update`.
3799 * @param {Object} object The object to query.
3800 * @param {Array|string} path The path of the property to update.
3801 * @param {Function} updater The function to produce the updated value.
3802 * @param {Function} [customizer] The function to customize path creation.
3803 * @returns {Object} Returns `object`.
3805 function baseUpdate(object, path, updater, customizer) {
3806 return baseSet(object, path, updater(baseGet(object, path)), customizer);
3810 * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
3811 * without support for iteratee shorthands.
3814 * @param {Array} array The array to query.
3815 * @param {Function} predicate The function invoked per iteration.
3816 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
3817 * @param {boolean} [fromRight] Specify iterating from right to left.
3818 * @returns {Array} Returns the slice of `array`.
3820 function baseWhile(array, predicate, isDrop, fromRight) {
3821 var length = array.length,
3822 index = fromRight ? length : -1;
3824 while ((fromRight ? index-- : ++index < length) &&
3825 predicate(array[index], index, array)) {}
3828 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
3829 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
3833 * The base implementation of `wrapperValue` which returns the result of
3834 * performing a sequence of actions on the unwrapped `value`, where each
3835 * successive action is supplied the return value of the previous.
3838 * @param {*} value The unwrapped value.
3839 * @param {Array} actions Actions to perform to resolve the unwrapped value.
3840 * @returns {*} Returns the resolved value.
3842 function baseWrapperValue(value, actions) {
3844 if (result instanceof LazyWrapper) {
3845 result = result.value();
3847 return arrayReduce(actions, function(result, action) {
3848 return action.func.apply(action.thisArg, arrayPush([result], action.args));
3853 * The base implementation of methods like `_.xor`, without support for
3854 * iteratee shorthands, that accepts an array of arrays to inspect.
3857 * @param {Array} arrays The arrays to inspect.
3858 * @param {Function} [iteratee] The iteratee invoked per element.
3859 * @param {Function} [comparator] The comparator invoked per element.
3860 * @returns {Array} Returns the new array of values.
3862 function baseXor(arrays, iteratee, comparator) {
3864 length = arrays.length;
3866 while (++index < length) {
3869 baseDifference(result, arrays[index], iteratee, comparator),
3870 baseDifference(arrays[index], result, iteratee, comparator)
3874 return (result && result.length) ? baseUniq(result, iteratee, comparator) : [];
3878 * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
3881 * @param {Array} props The property identifiers.
3882 * @param {Array} values The property values.
3883 * @param {Function} assignFunc The function to assign values.
3884 * @returns {Object} Returns the new object.
3886 function baseZipObject(props, values, assignFunc) {
3888 length = props.length,
3889 valsLength = values.length,
3892 while (++index < length) {
3893 var value = index < valsLength ? values[index] : undefined;
3894 assignFunc(result, props[index], value);
3900 * Casts `value` to an empty array if it's not an array like object.
3903 * @param {*} value The value to inspect.
3904 * @returns {Array|Object} Returns the cast array-like object.
3906 function castArrayLikeObject(value) {
3907 return isArrayLikeObject(value) ? value : [];
3911 * Casts `value` to `identity` if it's not a function.
3914 * @param {*} value The value to inspect.
3915 * @returns {Function} Returns cast function.
3917 function castFunction(value) {
3918 return typeof value == 'function' ? value : identity;
3922 * Casts `value` to a path array if it's not one.
3925 * @param {*} value The value to inspect.
3926 * @returns {Array} Returns the cast property path array.
3928 function castPath(value) {
3929 return isArray(value) ? value : stringToPath(value);
3933 * Casts `array` to a slice if it's needed.
3936 * @param {Array} array The array to inspect.
3937 * @param {number} start The start position.
3938 * @param {number} [end=array.length] The end position.
3939 * @returns {Array} Returns the cast slice.
3941 function castSlice(array, start, end) {
3942 var length = array.length;
3943 end = end === undefined ? length : end;
3944 return (!start && end >= length) ? array : baseSlice(array, start, end);
3948 * Creates a clone of `buffer`.
3951 * @param {Buffer} buffer The buffer to clone.
3952 * @param {boolean} [isDeep] Specify a deep clone.
3953 * @returns {Buffer} Returns the cloned buffer.
3955 function cloneBuffer(buffer, isDeep) {
3957 return buffer.slice();
3959 var result = new buffer.constructor(buffer.length);
3960 buffer.copy(result);
3965 * Creates a clone of `arrayBuffer`.
3968 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
3969 * @returns {ArrayBuffer} Returns the cloned array buffer.
3971 function cloneArrayBuffer(arrayBuffer) {
3972 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
3973 new Uint8Array(result).set(new Uint8Array(arrayBuffer));
3978 * Creates a clone of `dataView`.
3981 * @param {Object} dataView The data view to clone.
3982 * @param {boolean} [isDeep] Specify a deep clone.
3983 * @returns {Object} Returns the cloned data view.
3985 function cloneDataView(dataView, isDeep) {
3986 var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
3987 return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
3991 * Creates a clone of `map`.
3994 * @param {Object} map The map to clone.
3995 * @param {Function} cloneFunc The function to clone values.
3996 * @param {boolean} [isDeep] Specify a deep clone.
3997 * @returns {Object} Returns the cloned map.
3999 function cloneMap(map, isDeep, cloneFunc) {
4000 var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
4001 return arrayReduce(array, addMapEntry, new map.constructor);
4005 * Creates a clone of `regexp`.
4008 * @param {Object} regexp The regexp to clone.
4009 * @returns {Object} Returns the cloned regexp.
4011 function cloneRegExp(regexp) {
4012 var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
4013 result.lastIndex = regexp.lastIndex;
4018 * Creates a clone of `set`.
4021 * @param {Object} set The set to clone.
4022 * @param {Function} cloneFunc The function to clone values.
4023 * @param {boolean} [isDeep] Specify a deep clone.
4024 * @returns {Object} Returns the cloned set.
4026 function cloneSet(set, isDeep, cloneFunc) {
4027 var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
4028 return arrayReduce(array, addSetEntry, new set.constructor);
4032 * Creates a clone of the `symbol` object.
4035 * @param {Object} symbol The symbol object to clone.
4036 * @returns {Object} Returns the cloned symbol object.
4038 function cloneSymbol(symbol) {
4039 return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
4043 * Creates a clone of `typedArray`.
4046 * @param {Object} typedArray The typed array to clone.
4047 * @param {boolean} [isDeep] Specify a deep clone.
4048 * @returns {Object} Returns the cloned typed array.
4050 function cloneTypedArray(typedArray, isDeep) {
4051 var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
4052 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
4056 * Compares values to sort them in ascending order.
4059 * @param {*} value The value to compare.
4060 * @param {*} other The other value to compare.
4061 * @returns {number} Returns the sort order indicator for `value`.
4063 function compareAscending(value, other) {
4064 if (value !== other) {
4065 var valIsDefined = value !== undefined,
4066 valIsNull = value === null,
4067 valIsReflexive = value === value,
4068 valIsSymbol = isSymbol(value);
4070 var othIsDefined = other !== undefined,
4071 othIsNull = other === null,
4072 othIsReflexive = other === other,
4073 othIsSymbol = isSymbol(other);
4075 if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
4076 (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
4077 (valIsNull && othIsDefined && othIsReflexive) ||
4078 (!valIsDefined && othIsReflexive) ||
4082 if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
4083 (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
4084 (othIsNull && valIsDefined && valIsReflexive) ||
4085 (!othIsDefined && valIsReflexive) ||
4094 * Used by `_.orderBy` to compare multiple properties of a value to another
4095 * and stable sort them.
4097 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
4098 * specify an order of "desc" for descending or "asc" for ascending sort order
4099 * of corresponding values.
4102 * @param {Object} object The object to compare.
4103 * @param {Object} other The other object to compare.
4104 * @param {boolean[]|string[]} orders The order to sort by for each property.
4105 * @returns {number} Returns the sort order indicator for `object`.
4107 function compareMultiple(object, other, orders) {
4109 objCriteria = object.criteria,
4110 othCriteria = other.criteria,
4111 length = objCriteria.length,
4112 ordersLength = orders.length;
4114 while (++index < length) {
4115 var result = compareAscending(objCriteria[index], othCriteria[index]);
4117 if (index >= ordersLength) {
4120 var order = orders[index];
4121 return result * (order == 'desc' ? -1 : 1);
4124 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
4125 // that causes it, under certain circumstances, to provide the same value for
4126 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
4127 // for more details.
4129 // This also ensures a stable sort in V8 and other engines.
4130 // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
4131 return object.index - other.index;
4135 * Creates an array that is the composition of partially applied arguments,
4136 * placeholders, and provided arguments into a single array of arguments.
4139 * @param {Array|Object} args The provided arguments.
4140 * @param {Array} partials The arguments to prepend to those provided.
4141 * @param {Array} holders The `partials` placeholder indexes.
4142 * @params {boolean} [isCurried] Specify composing for a curried function.
4143 * @returns {Array} Returns the new array of composed arguments.
4145 function composeArgs(args, partials, holders, isCurried) {
4147 argsLength = args.length,
4148 holdersLength = holders.length,
4150 leftLength = partials.length,
4151 rangeLength = nativeMax(argsLength - holdersLength, 0),
4152 result = Array(leftLength + rangeLength),
4153 isUncurried = !isCurried;
4155 while (++leftIndex < leftLength) {
4156 result[leftIndex] = partials[leftIndex];
4158 while (++argsIndex < holdersLength) {
4159 if (isUncurried || argsIndex < argsLength) {
4160 result[holders[argsIndex]] = args[argsIndex];
4163 while (rangeLength--) {
4164 result[leftIndex++] = args[argsIndex++];
4170 * This function is like `composeArgs` except that the arguments composition
4171 * is tailored for `_.partialRight`.
4174 * @param {Array|Object} args The provided arguments.
4175 * @param {Array} partials The arguments to append to those provided.
4176 * @param {Array} holders The `partials` placeholder indexes.
4177 * @params {boolean} [isCurried] Specify composing for a curried function.
4178 * @returns {Array} Returns the new array of composed arguments.
4180 function composeArgsRight(args, partials, holders, isCurried) {
4182 argsLength = args.length,
4184 holdersLength = holders.length,
4186 rightLength = partials.length,
4187 rangeLength = nativeMax(argsLength - holdersLength, 0),
4188 result = Array(rangeLength + rightLength),
4189 isUncurried = !isCurried;
4191 while (++argsIndex < rangeLength) {
4192 result[argsIndex] = args[argsIndex];
4194 var offset = argsIndex;
4195 while (++rightIndex < rightLength) {
4196 result[offset + rightIndex] = partials[rightIndex];
4198 while (++holdersIndex < holdersLength) {
4199 if (isUncurried || argsIndex < argsLength) {
4200 result[offset + holders[holdersIndex]] = args[argsIndex++];
4207 * Copies the values of `source` to `array`.
4210 * @param {Array} source The array to copy values from.
4211 * @param {Array} [array=[]] The array to copy values to.
4212 * @returns {Array} Returns `array`.
4214 function copyArray(source, array) {
4216 length = source.length;
4218 array || (array = Array(length));
4219 while (++index < length) {
4220 array[index] = source[index];
4226 * Copies properties of `source` to `object`.
4229 * @param {Object} source The object to copy properties from.
4230 * @param {Array} props The property identifiers to copy.
4231 * @param {Object} [object={}] The object to copy properties to.
4232 * @param {Function} [customizer] The function to customize copied values.
4233 * @returns {Object} Returns `object`.
4235 function copyObject(source, props, object, customizer) {
4236 object || (object = {});
4239 length = props.length;
4241 while (++index < length) {
4242 var key = props[index];
4244 var newValue = customizer
4245 ? customizer(object[key], source[key], key, object, source)
4248 assignValue(object, key, newValue);
4254 * Copies own symbol properties of `source` to `object`.
4257 * @param {Object} source The object to copy symbols from.
4258 * @param {Object} [object={}] The object to copy symbols to.
4259 * @returns {Object} Returns `object`.
4261 function copySymbols(source, object) {
4262 return copyObject(source, getSymbols(source), object);
4266 * Creates a function like `_.groupBy`.
4269 * @param {Function} setter The function to set accumulator values.
4270 * @param {Function} [initializer] The accumulator object initializer.
4271 * @returns {Function} Returns the new aggregator function.
4273 function createAggregator(setter, initializer) {
4274 return function(collection, iteratee) {
4275 var func = isArray(collection) ? arrayAggregator : baseAggregator,
4276 accumulator = initializer ? initializer() : {};
4278 return func(collection, setter, getIteratee(iteratee), accumulator);
4283 * Creates a function like `_.assign`.
4286 * @param {Function} assigner The function to assign values.
4287 * @returns {Function} Returns the new assigner function.
4289 function createAssigner(assigner) {
4290 return rest(function(object, sources) {
4292 length = sources.length,
4293 customizer = length > 1 ? sources[length - 1] : undefined,
4294 guard = length > 2 ? sources[2] : undefined;
4296 customizer = typeof customizer == 'function'
4297 ? (length--, customizer)
4300 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
4301 customizer = length < 3 ? undefined : customizer;
4304 object = Object(object);
4305 while (++index < length) {
4306 var source = sources[index];
4308 assigner(object, source, index, customizer);
4316 * Creates a `baseEach` or `baseEachRight` function.
4319 * @param {Function} eachFunc The function to iterate over a collection.
4320 * @param {boolean} [fromRight] Specify iterating from right to left.
4321 * @returns {Function} Returns the new base function.
4323 function createBaseEach(eachFunc, fromRight) {
4324 return function(collection, iteratee) {
4325 if (collection == null) {
4328 if (!isArrayLike(collection)) {
4329 return eachFunc(collection, iteratee);
4331 var length = collection.length,
4332 index = fromRight ? length : -1,
4333 iterable = Object(collection);
4335 while ((fromRight ? index-- : ++index < length)) {
4336 if (iteratee(iterable[index], index, iterable) === false) {
4345 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
4348 * @param {boolean} [fromRight] Specify iterating from right to left.
4349 * @returns {Function} Returns the new base function.
4351 function createBaseFor(fromRight) {
4352 return function(object, iteratee, keysFunc) {
4354 iterable = Object(object),
4355 props = keysFunc(object),
4356 length = props.length;
4359 var key = props[fromRight ? length : ++index];
4360 if (iteratee(iterable[key], key, iterable) === false) {
4369 * Creates a function that wraps `func` to invoke it with the optional `this`
4370 * binding of `thisArg`.
4373 * @param {Function} func The function to wrap.
4374 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper`
4376 * @param {*} [thisArg] The `this` binding of `func`.
4377 * @returns {Function} Returns the new wrapped function.
4379 function createBaseWrapper(func, bitmask, thisArg) {
4380 var isBind = bitmask & BIND_FLAG,
4381 Ctor = createCtorWrapper(func);
4383 function wrapper() {
4384 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
4385 return fn.apply(isBind ? thisArg : this, arguments);
4391 * Creates a function like `_.lowerFirst`.
4394 * @param {string} methodName The name of the `String` case method to use.
4395 * @returns {Function} Returns the new function.
4397 function createCaseFirst(methodName) {
4398 return function(string) {
4399 string = toString(string);
4401 var strSymbols = reHasComplexSymbol.test(string)
4402 ? stringToArray(string)
4405 var chr = strSymbols
4409 var trailing = strSymbols
4410 ? castSlice(strSymbols, 1).join('')
4413 return chr[methodName]() + trailing;
4418 * Creates a function like `_.camelCase`.
4421 * @param {Function} callback The function to combine each word.
4422 * @returns {Function} Returns the new compounder function.
4424 function createCompounder(callback) {
4425 return function(string) {
4426 return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
4431 * Creates a function that produces an instance of `Ctor` regardless of
4432 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
4435 * @param {Function} Ctor The constructor to wrap.
4436 * @returns {Function} Returns the new wrapped function.
4438 function createCtorWrapper(Ctor) {
4440 // Use a `switch` statement to work with class constructors. See
4441 // http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
4442 // for more details.
4443 var args = arguments;
4444 switch (args.length) {
4445 case 0: return new Ctor;
4446 case 1: return new Ctor(args[0]);
4447 case 2: return new Ctor(args[0], args[1]);
4448 case 3: return new Ctor(args[0], args[1], args[2]);
4449 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
4450 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
4451 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
4452 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
4454 var thisBinding = baseCreate(Ctor.prototype),
4455 result = Ctor.apply(thisBinding, args);
4457 // Mimic the constructor's `return` behavior.
4458 // See https://es5.github.io/#x13.2.2 for more details.
4459 return isObject(result) ? result : thisBinding;
4464 * Creates a function that wraps `func` to enable currying.
4467 * @param {Function} func The function to wrap.
4468 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper`
4470 * @param {number} arity The arity of `func`.
4471 * @returns {Function} Returns the new wrapped function.
4473 function createCurryWrapper(func, bitmask, arity) {
4474 var Ctor = createCtorWrapper(func);
4476 function wrapper() {
4477 var length = arguments.length,
4478 args = Array(length),
4480 placeholder = getPlaceholder(wrapper);
4483 args[index] = arguments[index];
4485 var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
4487 : replaceHolders(args, placeholder);
4489 length -= holders.length;
4490 if (length < arity) {
4491 return createRecurryWrapper(
4492 func, bitmask, createHybridWrapper, wrapper.placeholder, undefined,
4493 args, holders, undefined, undefined, arity - length);
4495 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
4496 return apply(fn, this, args);
4502 * Creates a `_.flow` or `_.flowRight` function.
4505 * @param {boolean} [fromRight] Specify iterating from right to left.
4506 * @returns {Function} Returns the new flow function.
4508 function createFlow(fromRight) {
4509 return rest(function(funcs) {
4510 funcs = baseFlatten(funcs, 1);
4512 var length = funcs.length,
4514 prereq = LodashWrapper.prototype.thru;
4520 var func = funcs[index];
4521 if (typeof func != 'function') {
4522 throw new TypeError(FUNC_ERROR_TEXT);
4524 if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
4525 var wrapper = new LodashWrapper([], true);
4528 index = wrapper ? index : length;
4529 while (++index < length) {
4530 func = funcs[index];
4532 var funcName = getFuncName(func),
4533 data = funcName == 'wrapper' ? getData(func) : undefined;
4535 if (data && isLaziable(data[0]) &&
4536 data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) &&
4537 !data[4].length && data[9] == 1
4539 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
4541 wrapper = (func.length == 1 && isLaziable(func))
4542 ? wrapper[funcName]()
4543 : wrapper.thru(func);
4547 var args = arguments,
4550 if (wrapper && args.length == 1 &&
4551 isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
4552 return wrapper.plant(value).value();
4555 result = length ? funcs[index].apply(this, args) : value;
4557 while (++index < length) {
4558 result = funcs[index].call(this, result);
4566 * Creates a function that wraps `func` to invoke it with optional `this`
4567 * binding of `thisArg`, partial application, and currying.
4570 * @param {Function|string} func The function or method name to wrap.
4571 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper`
4573 * @param {*} [thisArg] The `this` binding of `func`.
4574 * @param {Array} [partials] The arguments to prepend to those provided to
4576 * @param {Array} [holders] The `partials` placeholder indexes.
4577 * @param {Array} [partialsRight] The arguments to append to those provided
4578 * to the new function.
4579 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
4580 * @param {Array} [argPos] The argument positions of the new function.
4581 * @param {number} [ary] The arity cap of `func`.
4582 * @param {number} [arity] The arity of `func`.
4583 * @returns {Function} Returns the new wrapped function.
4585 function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
4586 var isAry = bitmask & ARY_FLAG,
4587 isBind = bitmask & BIND_FLAG,
4588 isBindKey = bitmask & BIND_KEY_FLAG,
4589 isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG),
4590 isFlip = bitmask & FLIP_FLAG,
4591 Ctor = isBindKey ? undefined : createCtorWrapper(func);
4593 function wrapper() {
4594 var length = arguments.length,
4596 args = Array(length);
4599 args[index] = arguments[index];
4602 var placeholder = getPlaceholder(wrapper),
4603 holdersCount = countHolders(args, placeholder);
4606 args = composeArgs(args, partials, holders, isCurried);
4608 if (partialsRight) {
4609 args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
4611 length -= holdersCount;
4612 if (isCurried && length < arity) {
4613 var newHolders = replaceHolders(args, placeholder);
4614 return createRecurryWrapper(
4615 func, bitmask, createHybridWrapper, wrapper.placeholder, thisArg,
4616 args, newHolders, argPos, ary, arity - length
4619 var thisBinding = isBind ? thisArg : this,
4620 fn = isBindKey ? thisBinding[func] : func;
4622 length = args.length;
4624 args = reorder(args, argPos);
4625 } else if (isFlip && length > 1) {
4628 if (isAry && ary < length) {
4631 if (this && this !== root && this instanceof wrapper) {
4632 fn = Ctor || createCtorWrapper(fn);
4634 return fn.apply(thisBinding, args);
4640 * Creates a function like `_.invertBy`.
4643 * @param {Function} setter The function to set accumulator values.
4644 * @param {Function} toIteratee The function to resolve iteratees.
4645 * @returns {Function} Returns the new inverter function.
4647 function createInverter(setter, toIteratee) {
4648 return function(object, iteratee) {
4649 return baseInverter(object, setter, toIteratee(iteratee), {});
4654 * Creates a function that performs a mathematical operation on two values.
4657 * @param {Function} operator The function to perform the operation.
4658 * @returns {Function} Returns the new mathematical operation function.
4660 function createMathOperation(operator) {
4661 return function(value, other) {
4663 if (value === undefined && other === undefined) {
4666 if (value !== undefined) {
4669 if (other !== undefined) {
4670 if (result === undefined) {
4673 if (typeof value == 'string' || typeof other == 'string') {
4674 value = baseToString(value);
4675 other = baseToString(other);
4677 value = baseToNumber(value);
4678 other = baseToNumber(other);
4680 result = operator(value, other);
4687 * Creates a function like `_.over`.
4690 * @param {Function} arrayFunc The function to iterate over iteratees.
4691 * @returns {Function} Returns the new invoker function.
4693 function createOver(arrayFunc) {
4694 return rest(function(iteratees) {
4695 iteratees = (iteratees.length == 1 && isArray(iteratees[0]))
4696 ? arrayMap(iteratees[0], baseUnary(getIteratee()))
4697 : arrayMap(baseFlatten(iteratees, 1, isFlattenableIteratee), baseUnary(getIteratee()));
4699 return rest(function(args) {
4701 return arrayFunc(iteratees, function(iteratee) {
4702 return apply(iteratee, thisArg, args);
4709 * Creates the padding for `string` based on `length`. The `chars` string
4710 * is truncated if the number of characters exceeds `length`.
4713 * @param {number} length The padding length.
4714 * @param {string} [chars=' '] The string used as padding.
4715 * @returns {string} Returns the padding for `string`.
4717 function createPadding(length, chars) {
4718 chars = chars === undefined ? ' ' : baseToString(chars);
4720 var charsLength = chars.length;
4721 if (charsLength < 2) {
4722 return charsLength ? baseRepeat(chars, length) : chars;
4724 var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
4725 return reHasComplexSymbol.test(chars)
4726 ? castSlice(stringToArray(result), 0, length).join('')
4727 : result.slice(0, length);
4731 * Creates a function that wraps `func` to invoke it with the `this` binding
4732 * of `thisArg` and `partials` prepended to the arguments it receives.
4735 * @param {Function} func The function to wrap.
4736 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper`
4738 * @param {*} thisArg The `this` binding of `func`.
4739 * @param {Array} partials The arguments to prepend to those provided to
4741 * @returns {Function} Returns the new wrapped function.
4743 function createPartialWrapper(func, bitmask, thisArg, partials) {
4744 var isBind = bitmask & BIND_FLAG,
4745 Ctor = createCtorWrapper(func);
4747 function wrapper() {
4749 argsLength = arguments.length,
4751 leftLength = partials.length,
4752 args = Array(leftLength + argsLength),
4753 fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
4755 while (++leftIndex < leftLength) {
4756 args[leftIndex] = partials[leftIndex];
4758 while (argsLength--) {
4759 args[leftIndex++] = arguments[++argsIndex];
4761 return apply(fn, isBind ? thisArg : this, args);
4767 * Creates a `_.range` or `_.rangeRight` function.
4770 * @param {boolean} [fromRight] Specify iterating from right to left.
4771 * @returns {Function} Returns the new range function.
4773 function createRange(fromRight) {
4774 return function(start, end, step) {
4775 if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
4776 end = step = undefined;
4778 // Ensure the sign of `-0` is preserved.
4779 start = toNumber(start);
4780 start = start === start ? start : 0;
4781 if (end === undefined) {
4785 end = toNumber(end) || 0;
4787 step = step === undefined ? (start < end ? 1 : -1) : (toNumber(step) || 0);
4788 return baseRange(start, end, step, fromRight);
4793 * Creates a function that performs a relational operation on two values.
4796 * @param {Function} operator The function to perform the operation.
4797 * @returns {Function} Returns the new relational operation function.
4799 function createRelationalOperation(operator) {
4800 return function(value, other) {
4801 if (!(typeof value == 'string' && typeof other == 'string')) {
4802 value = toNumber(value);
4803 other = toNumber(other);
4805 return operator(value, other);
4810 * Creates a function that wraps `func` to continue currying.
4813 * @param {Function} func The function to wrap.
4814 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper`
4816 * @param {Function} wrapFunc The function to create the `func` wrapper.
4817 * @param {*} placeholder The placeholder value.
4818 * @param {*} [thisArg] The `this` binding of `func`.
4819 * @param {Array} [partials] The arguments to prepend to those provided to
4821 * @param {Array} [holders] The `partials` placeholder indexes.
4822 * @param {Array} [argPos] The argument positions of the new function.
4823 * @param {number} [ary] The arity cap of `func`.
4824 * @param {number} [arity] The arity of `func`.
4825 * @returns {Function} Returns the new wrapped function.
4827 function createRecurryWrapper(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
4828 var isCurry = bitmask & CURRY_FLAG,
4829 newHolders = isCurry ? holders : undefined,
4830 newHoldersRight = isCurry ? undefined : holders,
4831 newPartials = isCurry ? partials : undefined,
4832 newPartialsRight = isCurry ? undefined : partials;
4834 bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
4835 bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
4837 if (!(bitmask & CURRY_BOUND_FLAG)) {
4838 bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
4841 func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
4842 newHoldersRight, argPos, ary, arity
4845 var result = wrapFunc.apply(undefined, newData);
4846 if (isLaziable(func)) {
4847 setData(result, newData);
4849 result.placeholder = placeholder;
4854 * Creates a function like `_.round`.
4857 * @param {string} methodName The name of the `Math` method to use when rounding.
4858 * @returns {Function} Returns the new round function.
4860 function createRound(methodName) {
4861 var func = Math[methodName];
4862 return function(number, precision) {
4863 number = toNumber(number);
4864 precision = toInteger(precision);
4866 // Shift with exponential notation to avoid floating-point issues.
4867 // See [MDN](https://mdn.io/round#Examples) for more details.
4868 var pair = (toString(number) + 'e').split('e'),
4869 value = func(pair[0] + 'e' + (+pair[1] + precision));
4871 pair = (toString(value) + 'e').split('e');
4872 return +(pair[0] + 'e' + (+pair[1] - precision));
4874 return func(number);
4879 * Creates a set of `values`.
4882 * @param {Array} values The values to add to the set.
4883 * @returns {Object} Returns the new set.
4885 var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
4886 return new Set(values);
4890 * Creates a function that either curries or invokes `func` with optional
4891 * `this` binding and partially applied arguments.
4894 * @param {Function|string} func The function or method name to wrap.
4895 * @param {number} bitmask The bitmask of wrapper flags.
4896 * The bitmask may be composed of the following flags:
4899 * 4 - `_.curry` or `_.curryRight` of a bound function
4901 * 16 - `_.curryRight`
4903 * 64 - `_.partialRight`
4906 * @param {*} [thisArg] The `this` binding of `func`.
4907 * @param {Array} [partials] The arguments to be partially applied.
4908 * @param {Array} [holders] The `partials` placeholder indexes.
4909 * @param {Array} [argPos] The argument positions of the new function.
4910 * @param {number} [ary] The arity cap of `func`.
4911 * @param {number} [arity] The arity of `func`.
4912 * @returns {Function} Returns the new wrapped function.
4914 function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
4915 var isBindKey = bitmask & BIND_KEY_FLAG;
4916 if (!isBindKey && typeof func != 'function') {
4917 throw new TypeError(FUNC_ERROR_TEXT);
4919 var length = partials ? partials.length : 0;
4921 bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
4922 partials = holders = undefined;
4924 ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
4925 arity = arity === undefined ? arity : toInteger(arity);
4926 length -= holders ? holders.length : 0;
4928 if (bitmask & PARTIAL_RIGHT_FLAG) {
4929 var partialsRight = partials,
4930 holdersRight = holders;
4932 partials = holders = undefined;
4934 var data = isBindKey ? undefined : getData(func);
4937 func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
4942 mergeData(newData, data);
4945 bitmask = newData[1];
4946 thisArg = newData[2];
4947 partials = newData[3];
4948 holders = newData[4];
4949 arity = newData[9] = newData[9] == null
4950 ? (isBindKey ? 0 : func.length)
4951 : nativeMax(newData[9] - length, 0);
4953 if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) {
4954 bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG);
4956 if (!bitmask || bitmask == BIND_FLAG) {
4957 var result = createBaseWrapper(func, bitmask, thisArg);
4958 } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) {
4959 result = createCurryWrapper(func, bitmask, arity);
4960 } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) {
4961 result = createPartialWrapper(func, bitmask, thisArg, partials);
4963 result = createHybridWrapper.apply(undefined, newData);
4965 var setter = data ? baseSetData : setData;
4966 return setter(result, newData);
4970 * A specialized version of `baseIsEqualDeep` for arrays with support for
4971 * partial deep comparisons.
4974 * @param {Array} array The array to compare.
4975 * @param {Array} other The other array to compare.
4976 * @param {Function} equalFunc The function to determine equivalents of values.
4977 * @param {Function} customizer The function to customize comparisons.
4978 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
4980 * @param {Object} stack Tracks traversed `array` and `other` objects.
4981 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
4983 function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
4985 isPartial = bitmask & PARTIAL_COMPARE_FLAG,
4986 isUnordered = bitmask & UNORDERED_COMPARE_FLAG,
4987 arrLength = array.length,
4988 othLength = other.length;
4990 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
4993 // Assume cyclic values are equal.
4994 var stacked = stack.get(array);
4996 return stacked == other;
4999 stack.set(array, other);
5001 // Ignore non-index properties.
5002 while (++index < arrLength) {
5003 var arrValue = array[index],
5004 othValue = other[index];
5007 var compared = isPartial
5008 ? customizer(othValue, arrValue, index, other, array, stack)
5009 : customizer(arrValue, othValue, index, array, other, stack);
5011 if (compared !== undefined) {
5018 // Recursively compare arrays (susceptible to call stack limits).
5020 if (!arraySome(other, function(othValue) {
5021 return arrValue === othValue ||
5022 equalFunc(arrValue, othValue, customizer, bitmask, stack);
5028 arrValue === othValue ||
5029 equalFunc(arrValue, othValue, customizer, bitmask, stack)
5035 stack['delete'](array);
5040 * A specialized version of `baseIsEqualDeep` for comparing objects of
5041 * the same `toStringTag`.
5043 * **Note:** This function only supports comparing values with tags of
5044 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
5047 * @param {Object} object The object to compare.
5048 * @param {Object} other The other object to compare.
5049 * @param {string} tag The `toStringTag` of the objects to compare.
5050 * @param {Function} equalFunc The function to determine equivalents of values.
5051 * @param {Function} customizer The function to customize comparisons.
5052 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
5054 * @param {Object} stack Tracks traversed `object` and `other` objects.
5055 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
5057 function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
5060 if ((object.byteLength != other.byteLength) ||
5061 (object.byteOffset != other.byteOffset)) {
5064 object = object.buffer;
5065 other = other.buffer;
5067 case arrayBufferTag:
5068 if ((object.byteLength != other.byteLength) ||
5069 !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
5076 // Coerce dates and booleans to numbers, dates to milliseconds and
5077 // booleans to `1` or `0` treating invalid dates coerced to `NaN` as
5079 return +object == +other;
5082 return object.name == other.name && object.message == other.message;
5085 // Treat `NaN` vs. `NaN` as equal.
5086 return (object != +object) ? other != +other : object == +other;
5090 // Coerce regexes to strings and treat strings, primitives and objects,
5091 // as equal. See http://www.ecma-international.org/ecma-262/6.0/#sec-regexp.prototype.tostring
5092 // for more details.
5093 return object == (other + '');
5096 var convert = mapToArray;
5099 var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
5100 convert || (convert = setToArray);
5102 if (object.size != other.size && !isPartial) {
5105 // Assume cyclic values are equal.
5106 var stacked = stack.get(object);
5108 return stacked == other;
5110 bitmask |= UNORDERED_COMPARE_FLAG;
5111 stack.set(object, other);
5113 // Recursively compare objects (susceptible to call stack limits).
5114 return equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
5117 if (symbolValueOf) {
5118 return symbolValueOf.call(object) == symbolValueOf.call(other);
5125 * A specialized version of `baseIsEqualDeep` for objects with support for
5126 * partial deep comparisons.
5129 * @param {Object} object The object to compare.
5130 * @param {Object} other The other object to compare.
5131 * @param {Function} equalFunc The function to determine equivalents of values.
5132 * @param {Function} customizer The function to customize comparisons.
5133 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
5135 * @param {Object} stack Tracks traversed `object` and `other` objects.
5136 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
5138 function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
5139 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
5140 objProps = keys(object),
5141 objLength = objProps.length,
5142 othProps = keys(other),
5143 othLength = othProps.length;
5145 if (objLength != othLength && !isPartial) {
5148 var index = objLength;
5150 var key = objProps[index];
5151 if (!(isPartial ? key in other : baseHas(other, key))) {
5155 // Assume cyclic values are equal.
5156 var stacked = stack.get(object);
5158 return stacked == other;
5161 stack.set(object, other);
5163 var skipCtor = isPartial;
5164 while (++index < objLength) {
5165 key = objProps[index];
5166 var objValue = object[key],
5167 othValue = other[key];
5170 var compared = isPartial
5171 ? customizer(othValue, objValue, key, other, object, stack)
5172 : customizer(objValue, othValue, key, object, other, stack);
5174 // Recursively compare objects (susceptible to call stack limits).
5175 if (!(compared === undefined
5176 ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
5182 skipCtor || (skipCtor = key == 'constructor');
5184 if (result && !skipCtor) {
5185 var objCtor = object.constructor,
5186 othCtor = other.constructor;
5188 // Non `Object` object instances with different constructors are not equal.
5189 if (objCtor != othCtor &&
5190 ('constructor' in object && 'constructor' in other) &&
5191 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
5192 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
5196 stack['delete'](object);
5201 * Creates an array of own enumerable property names and symbols of `object`.
5204 * @param {Object} object The object to query.
5205 * @returns {Array} Returns the array of property names and symbols.
5207 function getAllKeys(object) {
5208 return baseGetAllKeys(object, keys, getSymbols);
5212 * Creates an array of own and inherited enumerable property names and
5213 * symbols of `object`.
5216 * @param {Object} object The object to query.
5217 * @returns {Array} Returns the array of property names and symbols.
5219 function getAllKeysIn(object) {
5220 return baseGetAllKeys(object, keysIn, getSymbolsIn);
5224 * Gets metadata for `func`.
5227 * @param {Function} func The function to query.
5228 * @returns {*} Returns the metadata for `func`.
5230 var getData = !metaMap ? noop : function(func) {
5231 return metaMap.get(func);
5235 * Gets the name of `func`.
5238 * @param {Function} func The function to query.
5239 * @returns {string} Returns the function name.
5241 function getFuncName(func) {
5242 var result = (func.name + ''),
5243 array = realNames[result],
5244 length = hasOwnProperty.call(realNames, result) ? array.length : 0;
5247 var data = array[length],
5248 otherFunc = data.func;
5249 if (otherFunc == null || otherFunc == func) {
5257 * Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
5258 * this function returns the custom method, otherwise it returns `baseIteratee`.
5259 * If arguments are provided, the chosen function is invoked with them and
5260 * its result is returned.
5263 * @param {*} [value] The value to convert to an iteratee.
5264 * @param {number} [arity] The arity of the created iteratee.
5265 * @returns {Function} Returns the chosen function or its result.
5267 function getIteratee() {
5268 var result = lodash.iteratee || iteratee;
5269 result = result === iteratee ? baseIteratee : result;
5270 return arguments.length ? result(arguments[0], arguments[1]) : result;
5274 * Gets the "length" property value of `object`.
5276 * **Note:** This function is used to avoid a
5277 * [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects
5278 * Safari on at least iOS 8.1-8.3 ARM64.
5281 * @param {Object} object The object to query.
5282 * @returns {*} Returns the "length" value.
5284 var getLength = baseProperty('length');
5287 * Gets the property names, values, and compare flags of `object`.
5290 * @param {Object} object The object to query.
5291 * @returns {Array} Returns the match data of `object`.
5293 function getMatchData(object) {
5294 var result = toPairs(object),
5295 length = result.length;
5298 result[length][2] = isStrictComparable(result[length][1]);
5304 * Gets the native function at `key` of `object`.
5307 * @param {Object} object The object to query.
5308 * @param {string} key The key of the method to get.
5309 * @returns {*} Returns the function if it's native, else `undefined`.
5311 function getNative(object, key) {
5312 var value = object[key];
5313 return isNative(value) ? value : undefined;
5317 * Gets the argument placeholder value for `func`.
5320 * @param {Function} func The function to inspect.
5321 * @returns {*} Returns the placeholder value.
5323 function getPlaceholder(func) {
5324 var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
5325 return object.placeholder;
5329 * Gets the `[[Prototype]]` of `value`.
5332 * @param {*} value The value to query.
5333 * @returns {null|Object} Returns the `[[Prototype]]`.
5335 function getPrototype(value) {
5336 return nativeGetPrototype(Object(value));
5340 * Creates an array of the own enumerable symbol properties of `object`.
5343 * @param {Object} object The object to query.
5344 * @returns {Array} Returns the array of symbols.
5346 function getSymbols(object) {
5347 // Coerce `object` to an object to avoid non-object errors in V8.
5348 // See https://bugs.chromium.org/p/v8/issues/detail?id=3443 for more details.
5349 return getOwnPropertySymbols(Object(object));
5352 // Fallback for IE < 11.
5353 if (!getOwnPropertySymbols) {
5354 getSymbols = function() {
5360 * Creates an array of the own and inherited enumerable symbol properties
5364 * @param {Object} object The object to query.
5365 * @returns {Array} Returns the array of symbols.
5367 var getSymbolsIn = !getOwnPropertySymbols ? getSymbols : function(object) {
5370 arrayPush(result, getSymbols(object));
5371 object = getPrototype(object);
5377 * Gets the `toStringTag` of `value`.
5380 * @param {*} value The value to query.
5381 * @returns {string} Returns the `toStringTag`.
5383 function getTag(value) {
5384 return objectToString.call(value);
5387 // Fallback for data views, maps, sets, and weak maps in IE 11,
5388 // for data views in Edge, and promises in Node.js.
5389 if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
5390 (Map && getTag(new Map) != mapTag) ||
5391 (Promise && getTag(Promise.resolve()) != promiseTag) ||
5392 (Set && getTag(new Set) != setTag) ||
5393 (WeakMap && getTag(new WeakMap) != weakMapTag)) {
5394 getTag = function(value) {
5395 var result = objectToString.call(value),
5396 Ctor = result == objectTag ? value.constructor : undefined,
5397 ctorString = Ctor ? toSource(Ctor) : undefined;
5400 switch (ctorString) {
5401 case dataViewCtorString: return dataViewTag;
5402 case mapCtorString: return mapTag;
5403 case promiseCtorString: return promiseTag;
5404 case setCtorString: return setTag;
5405 case weakMapCtorString: return weakMapTag;
5413 * Gets the view, applying any `transforms` to the `start` and `end` positions.
5416 * @param {number} start The start of the view.
5417 * @param {number} end The end of the view.
5418 * @param {Array} transforms The transformations to apply to the view.
5419 * @returns {Object} Returns an object containing the `start` and `end`
5420 * positions of the view.
5422 function getView(start, end, transforms) {
5424 length = transforms.length;
5426 while (++index < length) {
5427 var data = transforms[index],
5430 switch (data.type) {
5431 case 'drop': start += size; break;
5432 case 'dropRight': end -= size; break;
5433 case 'take': end = nativeMin(end, start + size); break;
5434 case 'takeRight': start = nativeMax(start, end - size); break;
5437 return { 'start': start, 'end': end };
5441 * Checks if `path` exists on `object`.
5444 * @param {Object} object The object to query.
5445 * @param {Array|string} path The path to check.
5446 * @param {Function} hasFunc The function to check properties.
5447 * @returns {boolean} Returns `true` if `path` exists, else `false`.
5449 function hasPath(object, path, hasFunc) {
5450 path = isKey(path, object) ? [path] : castPath(path);
5454 length = path.length;
5456 while (++index < length) {
5457 var key = toKey(path[index]);
5458 if (!(result = object != null && hasFunc(object, key))) {
5461 object = object[key];
5466 var length = object ? object.length : 0;
5467 return !!length && isLength(length) && isIndex(key, length) &&
5468 (isArray(object) || isString(object) || isArguments(object));
5472 * Initializes an array clone.
5475 * @param {Array} array The array to clone.
5476 * @returns {Array} Returns the initialized clone.
5478 function initCloneArray(array) {
5479 var length = array.length,
5480 result = array.constructor(length);
5482 // Add properties assigned by `RegExp#exec`.
5483 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
5484 result.index = array.index;
5485 result.input = array.input;
5491 * Initializes an object clone.
5494 * @param {Object} object The object to clone.
5495 * @returns {Object} Returns the initialized clone.
5497 function initCloneObject(object) {
5498 return (typeof object.constructor == 'function' && !isPrototype(object))
5499 ? baseCreate(getPrototype(object))
5504 * Initializes an object clone based on its `toStringTag`.
5506 * **Note:** This function only supports cloning values with tags of
5507 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
5510 * @param {Object} object The object to clone.
5511 * @param {string} tag The `toStringTag` of the object to clone.
5512 * @param {Function} cloneFunc The function to clone values.
5513 * @param {boolean} [isDeep] Specify a deep clone.
5514 * @returns {Object} Returns the initialized clone.
5516 function initCloneByTag(object, tag, cloneFunc, isDeep) {
5517 var Ctor = object.constructor;
5519 case arrayBufferTag:
5520 return cloneArrayBuffer(object);
5524 return new Ctor(+object);
5527 return cloneDataView(object, isDeep);
5529 case float32Tag: case float64Tag:
5530 case int8Tag: case int16Tag: case int32Tag:
5531 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
5532 return cloneTypedArray(object, isDeep);
5535 return cloneMap(object, isDeep, cloneFunc);
5539 return new Ctor(object);
5542 return cloneRegExp(object);
5545 return cloneSet(object, isDeep, cloneFunc);
5548 return cloneSymbol(object);
5553 * Creates an array of index keys for `object` values of arrays,
5554 * `arguments` objects, and strings, otherwise `null` is returned.
5557 * @param {Object} object The object to query.
5558 * @returns {Array|null} Returns index keys, else `null`.
5560 function indexKeys(object) {
5561 var length = object ? object.length : undefined;
5562 if (isLength(length) &&
5563 (isArray(object) || isString(object) || isArguments(object))) {
5564 return baseTimes(length, String);
5570 * Checks if `value` is a flattenable `arguments` object or array.
5573 * @param {*} value The value to check.
5574 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
5576 function isFlattenable(value) {
5577 return isArrayLikeObject(value) && (isArray(value) || isArguments(value));
5581 * Checks if `value` is a flattenable array and not a `_.matchesProperty`
5582 * iteratee shorthand.
5585 * @param {*} value The value to check.
5586 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
5588 function isFlattenableIteratee(value) {
5589 return isArray(value) && !(value.length == 2 && !isFunction(value[0]));
5593 * Checks if `value` is a valid array-like index.
5596 * @param {*} value The value to check.
5597 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
5598 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
5600 function isIndex(value, length) {
5601 length = length == null ? MAX_SAFE_INTEGER : length;
5603 (typeof value == 'number' || reIsUint.test(value)) &&
5604 (value > -1 && value % 1 == 0 && value < length);
5608 * Checks if the given arguments are from an iteratee call.
5611 * @param {*} value The potential iteratee value argument.
5612 * @param {*} index The potential iteratee index or key argument.
5613 * @param {*} object The potential iteratee object argument.
5614 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
5617 function isIterateeCall(value, index, object) {
5618 if (!isObject(object)) {
5621 var type = typeof index;
5622 if (type == 'number'
5623 ? (isArrayLike(object) && isIndex(index, object.length))
5624 : (type == 'string' && index in object)
5626 return eq(object[index], value);
5632 * Checks if `value` is a property name and not a property path.
5635 * @param {*} value The value to check.
5636 * @param {Object} [object] The object to query keys on.
5637 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
5639 function isKey(value, object) {
5640 if (isArray(value)) {
5643 var type = typeof value;
5644 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
5645 value == null || isSymbol(value)) {
5648 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
5649 (object != null && value in Object(object));
5653 * Checks if `value` is suitable for use as unique object key.
5656 * @param {*} value The value to check.
5657 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
5659 function isKeyable(value) {
5660 var type = typeof value;
5661 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
5662 ? (value !== '__proto__')
5667 * Checks if `func` has a lazy counterpart.
5670 * @param {Function} func The function to check.
5671 * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
5674 function isLaziable(func) {
5675 var funcName = getFuncName(func),
5676 other = lodash[funcName];
5678 if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
5681 if (func === other) {
5684 var data = getData(other);
5685 return !!data && func === data[0];
5689 * Checks if `value` is likely a prototype object.
5692 * @param {*} value The value to check.
5693 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
5695 function isPrototype(value) {
5696 var Ctor = value && value.constructor,
5697 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
5699 return value === proto;
5703 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
5706 * @param {*} value The value to check.
5707 * @returns {boolean} Returns `true` if `value` if suitable for strict
5708 * equality comparisons, else `false`.
5710 function isStrictComparable(value) {
5711 return value === value && !isObject(value);
5715 * A specialized version of `matchesProperty` for source values suitable
5716 * for strict equality comparisons, i.e. `===`.
5719 * @param {string} key The key of the property to get.
5720 * @param {*} srcValue The value to match.
5721 * @returns {Function} Returns the new function.
5723 function matchesStrictComparable(key, srcValue) {
5724 return function(object) {
5725 if (object == null) {
5728 return object[key] === srcValue &&
5729 (srcValue !== undefined || (key in Object(object)));
5734 * Merges the function metadata of `source` into `data`.
5736 * Merging metadata reduces the number of wrappers used to invoke a function.
5737 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
5738 * may be applied regardless of execution order. Methods like `_.ary` and
5739 * `_.rearg` modify function arguments, making the order in which they are
5740 * executed important, preventing the merging of metadata. However, we make
5741 * an exception for a safe combined case where curried functions have `_.ary`
5742 * and or `_.rearg` applied.
5745 * @param {Array} data The destination metadata.
5746 * @param {Array} source The source metadata.
5747 * @returns {Array} Returns `data`.
5749 function mergeData(data, source) {
5750 var bitmask = data[1],
5751 srcBitmask = source[1],
5752 newBitmask = bitmask | srcBitmask,
5753 isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG);
5756 ((srcBitmask == ARY_FLAG) && (bitmask == CURRY_FLAG)) ||
5757 ((srcBitmask == ARY_FLAG) && (bitmask == REARG_FLAG) && (data[7].length <= source[8])) ||
5758 ((srcBitmask == (ARY_FLAG | REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == CURRY_FLAG));
5760 // Exit early if metadata can't be merged.
5761 if (!(isCommon || isCombo)) {
5764 // Use source `thisArg` if available.
5765 if (srcBitmask & BIND_FLAG) {
5766 data[2] = source[2];
5767 // Set when currying a bound function.
5768 newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG;
5770 // Compose partial arguments.
5771 var value = source[3];
5773 var partials = data[3];
5774 data[3] = partials ? composeArgs(partials, value, source[4]) : value;
5775 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
5777 // Compose partial right arguments.
5781 data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
5782 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
5784 // Use source `argPos` if available.
5789 // Use source `ary` if it's smaller.
5790 if (srcBitmask & ARY_FLAG) {
5791 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
5793 // Use source `arity` if one is not provided.
5794 if (data[9] == null) {
5795 data[9] = source[9];
5797 // Use source `func` and merge bitmasks.
5798 data[0] = source[0];
5799 data[1] = newBitmask;
5805 * Used by `_.defaultsDeep` to customize its `_.merge` use.
5808 * @param {*} objValue The destination value.
5809 * @param {*} srcValue The source value.
5810 * @param {string} key The key of the property to merge.
5811 * @param {Object} object The parent object of `objValue`.
5812 * @param {Object} source The parent object of `srcValue`.
5813 * @param {Object} [stack] Tracks traversed source values and their merged
5815 * @returns {*} Returns the value to assign.
5817 function mergeDefaults(objValue, srcValue, key, object, source, stack) {
5818 if (isObject(objValue) && isObject(srcValue)) {
5819 baseMerge(objValue, srcValue, undefined, mergeDefaults, stack.set(srcValue, objValue));
5825 * Gets the parent value at `path` of `object`.
5828 * @param {Object} object The object to query.
5829 * @param {Array} path The path to get the parent value of.
5830 * @returns {*} Returns the parent value.
5832 function parent(object, path) {
5833 return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
5837 * Reorder `array` according to the specified indexes where the element at
5838 * the first index is assigned as the first element, the element at
5839 * the second index is assigned as the second element, and so on.
5842 * @param {Array} array The array to reorder.
5843 * @param {Array} indexes The arranged array indexes.
5844 * @returns {Array} Returns `array`.
5846 function reorder(array, indexes) {
5847 var arrLength = array.length,
5848 length = nativeMin(indexes.length, arrLength),
5849 oldArray = copyArray(array);
5852 var index = indexes[length];
5853 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
5859 * Sets metadata for `func`.
5861 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
5862 * period of time, it will trip its breaker and transition to an identity
5863 * function to avoid garbage collection pauses in V8. See
5864 * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
5868 * @param {Function} func The function to associate metadata with.
5869 * @param {*} data The metadata.
5870 * @returns {Function} Returns `func`.
5872 var setData = (function() {
5876 return function(key, value) {
5878 remaining = HOT_SPAN - (stamp - lastCalled);
5881 if (remaining > 0) {
5882 if (++count >= HOT_COUNT) {
5888 return baseSetData(key, value);
5893 * Converts `string` to a property path array.
5896 * @param {string} string The string to convert.
5897 * @returns {Array} Returns the property path array.
5899 var stringToPath = memoize(function(string) {
5901 toString(string).replace(rePropName, function(match, number, quote, string) {
5902 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
5908 * Converts `value` to a string key if it's not a string or symbol.
5911 * @param {*} value The value to inspect.
5912 * @returns {string|symbol} Returns the key.
5914 function toKey(value) {
5915 if (typeof value == 'string' || isSymbol(value)) {
5918 var result = (value + '');
5919 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
5923 * Converts `func` to its source code.
5926 * @param {Function} func The function to process.
5927 * @returns {string} Returns the source code.
5929 function toSource(func) {
5932 return funcToString.call(func);
5942 * Creates a clone of `wrapper`.
5945 * @param {Object} wrapper The wrapper to clone.
5946 * @returns {Object} Returns the cloned wrapper.
5948 function wrapperClone(wrapper) {
5949 if (wrapper instanceof LazyWrapper) {
5950 return wrapper.clone();
5952 var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
5953 result.__actions__ = copyArray(wrapper.__actions__);
5954 result.__index__ = wrapper.__index__;
5955 result.__values__ = wrapper.__values__;
5959 /*------------------------------------------------------------------------*/
5962 * Creates an array of elements split into groups the length of `size`.
5963 * If `array` can't be split evenly, the final chunk will be the remaining
5970 * @param {Array} array The array to process.
5971 * @param {number} [size=1] The length of each chunk
5972 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
5973 * @returns {Array} Returns the new array containing chunks.
5976 * _.chunk(['a', 'b', 'c', 'd'], 2);
5977 * // => [['a', 'b'], ['c', 'd']]
5979 * _.chunk(['a', 'b', 'c', 'd'], 3);
5980 * // => [['a', 'b', 'c'], ['d']]
5982 function chunk(array, size, guard) {
5983 if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
5986 size = nativeMax(toInteger(size), 0);
5988 var length = array ? array.length : 0;
5989 if (!length || size < 1) {
5994 result = Array(nativeCeil(length / size));
5996 while (index < length) {
5997 result[resIndex++] = baseSlice(array, index, (index += size));
6003 * Creates an array with all falsey values removed. The values `false`, `null`,
6004 * `0`, `""`, `undefined`, and `NaN` are falsey.
6010 * @param {Array} array The array to compact.
6011 * @returns {Array} Returns the new array of filtered values.
6014 * _.compact([0, 1, false, 2, '', 3]);
6017 function compact(array) {
6019 length = array ? array.length : 0,
6023 while (++index < length) {
6024 var value = array[index];
6026 result[resIndex++] = value;
6033 * Creates a new array concatenating `array` with any additional arrays
6040 * @param {Array} array The array to concatenate.
6041 * @param {...*} [values] The values to concatenate.
6042 * @returns {Array} Returns the new concatenated array.
6046 * var other = _.concat(array, 2, [3], [[4]]);
6048 * console.log(other);
6049 * // => [1, 2, 3, [4]]
6051 * console.log(array);
6055 var length = arguments.length,
6056 array = castArray(arguments[0]);
6059 return length ? copyArray(array) : [];
6061 var args = Array(length - 1);
6063 args[length - 1] = arguments[length];
6065 return arrayConcat(array, baseFlatten(args, 1));
6069 * Creates an array of unique `array` values not included in the other given
6070 * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
6071 * for equality comparisons. The order of result values is determined by the
6072 * order they occur in the first array.
6078 * @param {Array} array The array to inspect.
6079 * @param {...Array} [values] The values to exclude.
6080 * @returns {Array} Returns the new array of filtered values.
6081 * @see _.without, _.xor
6084 * _.difference([3, 2, 1], [4, 2]);
6087 var difference = rest(function(array, values) {
6088 return isArrayLikeObject(array)
6089 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
6094 * This method is like `_.difference` except that it accepts `iteratee` which
6095 * is invoked for each element of `array` and `values` to generate the criterion
6096 * by which they're compared. Result values are chosen from the first array.
6097 * The iteratee is invoked with one argument: (value).
6103 * @param {Array} array The array to inspect.
6104 * @param {...Array} [values] The values to exclude.
6105 * @param {Array|Function|Object|string} [iteratee=_.identity]
6106 * The iteratee invoked per element.
6107 * @returns {Array} Returns the new array of filtered values.
6110 * _.differenceBy([3.1, 2.2, 1.3], [4.4, 2.5], Math.floor);
6113 * // The `_.property` iteratee shorthand.
6114 * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
6115 * // => [{ 'x': 2 }]
6117 var differenceBy = rest(function(array, values) {
6118 var iteratee = last(values);
6119 if (isArrayLikeObject(iteratee)) {
6120 iteratee = undefined;
6122 return isArrayLikeObject(array)
6123 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee))
6128 * This method is like `_.difference` except that it accepts `comparator`
6129 * which is invoked to compare elements of `array` to `values`. Result values
6130 * are chosen from the first array. The comparator is invoked with two arguments:
6137 * @param {Array} array The array to inspect.
6138 * @param {...Array} [values] The values to exclude.
6139 * @param {Function} [comparator] The comparator invoked per element.
6140 * @returns {Array} Returns the new array of filtered values.
6143 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
6145 * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
6146 * // => [{ 'x': 2, 'y': 1 }]
6148 var differenceWith = rest(function(array, values) {
6149 var comparator = last(values);
6150 if (isArrayLikeObject(comparator)) {
6151 comparator = undefined;
6153 return isArrayLikeObject(array)
6154 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
6159 * Creates a slice of `array` with `n` elements dropped from the beginning.
6165 * @param {Array} array The array to query.
6166 * @param {number} [n=1] The number of elements to drop.
6167 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
6168 * @returns {Array} Returns the slice of `array`.
6171 * _.drop([1, 2, 3]);
6174 * _.drop([1, 2, 3], 2);
6177 * _.drop([1, 2, 3], 5);
6180 * _.drop([1, 2, 3], 0);
6183 function drop(array, n, guard) {
6184 var length = array ? array.length : 0;
6188 n = (guard || n === undefined) ? 1 : toInteger(n);
6189 return baseSlice(array, n < 0 ? 0 : n, length);
6193 * Creates a slice of `array` with `n` elements dropped from the end.
6199 * @param {Array} array The array to query.
6200 * @param {number} [n=1] The number of elements to drop.
6201 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
6202 * @returns {Array} Returns the slice of `array`.
6205 * _.dropRight([1, 2, 3]);
6208 * _.dropRight([1, 2, 3], 2);
6211 * _.dropRight([1, 2, 3], 5);
6214 * _.dropRight([1, 2, 3], 0);
6217 function dropRight(array, n, guard) {
6218 var length = array ? array.length : 0;
6222 n = (guard || n === undefined) ? 1 : toInteger(n);
6224 return baseSlice(array, 0, n < 0 ? 0 : n);
6228 * Creates a slice of `array` excluding elements dropped from the end.
6229 * Elements are dropped until `predicate` returns falsey. The predicate is
6230 * invoked with three arguments: (value, index, array).
6236 * @param {Array} array The array to query.
6237 * @param {Array|Function|Object|string} [predicate=_.identity]
6238 * The function invoked per iteration.
6239 * @returns {Array} Returns the slice of `array`.
6243 * { 'user': 'barney', 'active': true },
6244 * { 'user': 'fred', 'active': false },
6245 * { 'user': 'pebbles', 'active': false }
6248 * _.dropRightWhile(users, function(o) { return !o.active; });
6249 * // => objects for ['barney']
6251 * // The `_.matches` iteratee shorthand.
6252 * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
6253 * // => objects for ['barney', 'fred']
6255 * // The `_.matchesProperty` iteratee shorthand.
6256 * _.dropRightWhile(users, ['active', false]);
6257 * // => objects for ['barney']
6259 * // The `_.property` iteratee shorthand.
6260 * _.dropRightWhile(users, 'active');
6261 * // => objects for ['barney', 'fred', 'pebbles']
6263 function dropRightWhile(array, predicate) {
6264 return (array && array.length)
6265 ? baseWhile(array, getIteratee(predicate, 3), true, true)
6270 * Creates a slice of `array` excluding elements dropped from the beginning.
6271 * Elements are dropped until `predicate` returns falsey. The predicate is
6272 * invoked with three arguments: (value, index, array).
6278 * @param {Array} array The array to query.
6279 * @param {Array|Function|Object|string} [predicate=_.identity]
6280 * The function invoked per iteration.
6281 * @returns {Array} Returns the slice of `array`.
6285 * { 'user': 'barney', 'active': false },
6286 * { 'user': 'fred', 'active': false },
6287 * { 'user': 'pebbles', 'active': true }
6290 * _.dropWhile(users, function(o) { return !o.active; });
6291 * // => objects for ['pebbles']
6293 * // The `_.matches` iteratee shorthand.
6294 * _.dropWhile(users, { 'user': 'barney', 'active': false });
6295 * // => objects for ['fred', 'pebbles']
6297 * // The `_.matchesProperty` iteratee shorthand.
6298 * _.dropWhile(users, ['active', false]);
6299 * // => objects for ['pebbles']
6301 * // The `_.property` iteratee shorthand.
6302 * _.dropWhile(users, 'active');
6303 * // => objects for ['barney', 'fred', 'pebbles']
6305 function dropWhile(array, predicate) {
6306 return (array && array.length)
6307 ? baseWhile(array, getIteratee(predicate, 3), true)
6312 * Fills elements of `array` with `value` from `start` up to, but not
6315 * **Note:** This method mutates `array`.
6321 * @param {Array} array The array to fill.
6322 * @param {*} value The value to fill `array` with.
6323 * @param {number} [start=0] The start position.
6324 * @param {number} [end=array.length] The end position.
6325 * @returns {Array} Returns `array`.
6328 * var array = [1, 2, 3];
6330 * _.fill(array, 'a');
6331 * console.log(array);
6332 * // => ['a', 'a', 'a']
6334 * _.fill(Array(3), 2);
6337 * _.fill([4, 6, 8, 10], '*', 1, 3);
6338 * // => [4, '*', '*', 10]
6340 function fill(array, value, start, end) {
6341 var length = array ? array.length : 0;
6345 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
6349 return baseFill(array, value, start, end);
6353 * This method is like `_.find` except that it returns the index of the first
6354 * element `predicate` returns truthy for instead of the element itself.
6360 * @param {Array} array The array to search.
6361 * @param {Array|Function|Object|string} [predicate=_.identity]
6362 * The function invoked per iteration.
6363 * @returns {number} Returns the index of the found element, else `-1`.
6367 * { 'user': 'barney', 'active': false },
6368 * { 'user': 'fred', 'active': false },
6369 * { 'user': 'pebbles', 'active': true }
6372 * _.findIndex(users, function(o) { return o.user == 'barney'; });
6375 * // The `_.matches` iteratee shorthand.
6376 * _.findIndex(users, { 'user': 'fred', 'active': false });
6379 * // The `_.matchesProperty` iteratee shorthand.
6380 * _.findIndex(users, ['active', false]);
6383 * // The `_.property` iteratee shorthand.
6384 * _.findIndex(users, 'active');
6387 function findIndex(array, predicate) {
6388 return (array && array.length)
6389 ? baseFindIndex(array, getIteratee(predicate, 3))
6394 * This method is like `_.findIndex` except that it iterates over elements
6395 * of `collection` from right to left.
6401 * @param {Array} array The array to search.
6402 * @param {Array|Function|Object|string} [predicate=_.identity]
6403 * The function invoked per iteration.
6404 * @returns {number} Returns the index of the found element, else `-1`.
6408 * { 'user': 'barney', 'active': true },
6409 * { 'user': 'fred', 'active': false },
6410 * { 'user': 'pebbles', 'active': false }
6413 * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
6416 * // The `_.matches` iteratee shorthand.
6417 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
6420 * // The `_.matchesProperty` iteratee shorthand.
6421 * _.findLastIndex(users, ['active', false]);
6424 * // The `_.property` iteratee shorthand.
6425 * _.findLastIndex(users, 'active');
6428 function findLastIndex(array, predicate) {
6429 return (array && array.length)
6430 ? baseFindIndex(array, getIteratee(predicate, 3), true)
6435 * Flattens `array` a single level deep.
6441 * @param {Array} array The array to flatten.
6442 * @returns {Array} Returns the new flattened array.
6445 * _.flatten([1, [2, [3, [4]], 5]]);
6446 * // => [1, 2, [3, [4]], 5]
6448 function flatten(array) {
6449 var length = array ? array.length : 0;
6450 return length ? baseFlatten(array, 1) : [];
6454 * Recursively flattens `array`.
6460 * @param {Array} array The array to flatten.
6461 * @returns {Array} Returns the new flattened array.
6464 * _.flattenDeep([1, [2, [3, [4]], 5]]);
6465 * // => [1, 2, 3, 4, 5]
6467 function flattenDeep(array) {
6468 var length = array ? array.length : 0;
6469 return length ? baseFlatten(array, INFINITY) : [];
6473 * Recursively flatten `array` up to `depth` times.
6479 * @param {Array} array The array to flatten.
6480 * @param {number} [depth=1] The maximum recursion depth.
6481 * @returns {Array} Returns the new flattened array.
6484 * var array = [1, [2, [3, [4]], 5]];
6486 * _.flattenDepth(array, 1);
6487 * // => [1, 2, [3, [4]], 5]
6489 * _.flattenDepth(array, 2);
6490 * // => [1, 2, 3, [4], 5]
6492 function flattenDepth(array, depth) {
6493 var length = array ? array.length : 0;
6497 depth = depth === undefined ? 1 : toInteger(depth);
6498 return baseFlatten(array, depth);
6502 * The inverse of `_.toPairs`; this method returns an object composed
6503 * from key-value `pairs`.
6509 * @param {Array} pairs The key-value pairs.
6510 * @returns {Object} Returns the new object.
6513 * _.fromPairs([['fred', 30], ['barney', 40]]);
6514 * // => { 'fred': 30, 'barney': 40 }
6516 function fromPairs(pairs) {
6518 length = pairs ? pairs.length : 0,
6521 while (++index < length) {
6522 var pair = pairs[index];
6523 result[pair[0]] = pair[1];
6529 * Gets the first element of `array`.
6536 * @param {Array} array The array to query.
6537 * @returns {*} Returns the first element of `array`.
6540 * _.head([1, 2, 3]);
6546 function head(array) {
6547 return (array && array.length) ? array[0] : undefined;
6551 * Gets the index at which the first occurrence of `value` is found in `array`
6552 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
6553 * for equality comparisons. If `fromIndex` is negative, it's used as the
6554 * offset from the end of `array`.
6560 * @param {Array} array The array to search.
6561 * @param {*} value The value to search for.
6562 * @param {number} [fromIndex=0] The index to search from.
6563 * @returns {number} Returns the index of the matched value, else `-1`.
6566 * _.indexOf([1, 2, 1, 2], 2);
6569 * // Search from the `fromIndex`.
6570 * _.indexOf([1, 2, 1, 2], 2, 2);
6573 function indexOf(array, value, fromIndex) {
6574 var length = array ? array.length : 0;
6578 fromIndex = toInteger(fromIndex);
6579 if (fromIndex < 0) {
6580 fromIndex = nativeMax(length + fromIndex, 0);
6582 return baseIndexOf(array, value, fromIndex);
6586 * Gets all but the last element of `array`.
6592 * @param {Array} array The array to query.
6593 * @returns {Array} Returns the slice of `array`.
6596 * _.initial([1, 2, 3]);
6599 function initial(array) {
6600 return dropRight(array, 1);
6604 * Creates an array of unique values that are included in all given arrays
6605 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
6606 * for equality comparisons. The order of result values is determined by the
6607 * order they occur in the first array.
6613 * @param {...Array} [arrays] The arrays to inspect.
6614 * @returns {Array} Returns the new array of intersecting values.
6617 * _.intersection([2, 1], [4, 2], [1, 2]);
6620 var intersection = rest(function(arrays) {
6621 var mapped = arrayMap(arrays, castArrayLikeObject);
6622 return (mapped.length && mapped[0] === arrays[0])
6623 ? baseIntersection(mapped)
6628 * This method is like `_.intersection` except that it accepts `iteratee`
6629 * which is invoked for each element of each `arrays` to generate the criterion
6630 * by which they're compared. Result values are chosen from the first array.
6631 * The iteratee is invoked with one argument: (value).
6637 * @param {...Array} [arrays] The arrays to inspect.
6638 * @param {Array|Function|Object|string} [iteratee=_.identity]
6639 * The iteratee invoked per element.
6640 * @returns {Array} Returns the new array of intersecting values.
6643 * _.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
6646 * // The `_.property` iteratee shorthand.
6647 * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
6648 * // => [{ 'x': 1 }]
6650 var intersectionBy = rest(function(arrays) {
6651 var iteratee = last(arrays),
6652 mapped = arrayMap(arrays, castArrayLikeObject);
6654 if (iteratee === last(mapped)) {
6655 iteratee = undefined;
6659 return (mapped.length && mapped[0] === arrays[0])
6660 ? baseIntersection(mapped, getIteratee(iteratee))
6665 * This method is like `_.intersection` except that it accepts `comparator`
6666 * which is invoked to compare elements of `arrays`. Result values are chosen
6667 * from the first array. The comparator is invoked with two arguments:
6674 * @param {...Array} [arrays] The arrays to inspect.
6675 * @param {Function} [comparator] The comparator invoked per element.
6676 * @returns {Array} Returns the new array of intersecting values.
6679 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
6680 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
6682 * _.intersectionWith(objects, others, _.isEqual);
6683 * // => [{ 'x': 1, 'y': 2 }]
6685 var intersectionWith = rest(function(arrays) {
6686 var comparator = last(arrays),
6687 mapped = arrayMap(arrays, castArrayLikeObject);
6689 if (comparator === last(mapped)) {
6690 comparator = undefined;
6694 return (mapped.length && mapped[0] === arrays[0])
6695 ? baseIntersection(mapped, undefined, comparator)
6700 * Converts all elements in `array` into a string separated by `separator`.
6706 * @param {Array} array The array to convert.
6707 * @param {string} [separator=','] The element separator.
6708 * @returns {string} Returns the joined string.
6711 * _.join(['a', 'b', 'c'], '~');
6714 function join(array, separator) {
6715 return array ? nativeJoin.call(array, separator) : '';
6719 * Gets the last element of `array`.
6725 * @param {Array} array The array to query.
6726 * @returns {*} Returns the last element of `array`.
6729 * _.last([1, 2, 3]);
6732 function last(array) {
6733 var length = array ? array.length : 0;
6734 return length ? array[length - 1] : undefined;
6738 * This method is like `_.indexOf` except that it iterates over elements of
6739 * `array` from right to left.
6745 * @param {Array} array The array to search.
6746 * @param {*} value The value to search for.
6747 * @param {number} [fromIndex=array.length-1] The index to search from.
6748 * @returns {number} Returns the index of the matched value, else `-1`.
6751 * _.lastIndexOf([1, 2, 1, 2], 2);
6754 * // Search from the `fromIndex`.
6755 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
6758 function lastIndexOf(array, value, fromIndex) {
6759 var length = array ? array.length : 0;
6764 if (fromIndex !== undefined) {
6765 index = toInteger(fromIndex);
6768 ? nativeMax(length + index, 0)
6769 : nativeMin(index, length - 1)
6772 if (value !== value) {
6773 return indexOfNaN(array, index, true);
6776 if (array[index] === value) {
6784 * Gets the nth element of `array`. If `n` is negative, the nth element
6785 * from the end is returned.
6791 * @param {Array} array The array to query.
6792 * @param {number} [n=0] The index of the element to return.
6793 * @returns {*} Returns the nth element of `array`.
6796 * var array = ['a', 'b', 'c', 'd'];
6804 function nth(array, n) {
6805 return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
6809 * Removes all given values from `array` using
6810 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
6811 * for equality comparisons.
6813 * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
6814 * to remove elements from an array by predicate.
6820 * @param {Array} array The array to modify.
6821 * @param {...*} [values] The values to remove.
6822 * @returns {Array} Returns `array`.
6825 * var array = [1, 2, 3, 1, 2, 3];
6827 * _.pull(array, 2, 3);
6828 * console.log(array);
6831 var pull = rest(pullAll);
6834 * This method is like `_.pull` except that it accepts an array of values to remove.
6836 * **Note:** Unlike `_.difference`, this method mutates `array`.
6842 * @param {Array} array The array to modify.
6843 * @param {Array} values The values to remove.
6844 * @returns {Array} Returns `array`.
6847 * var array = [1, 2, 3, 1, 2, 3];
6849 * _.pullAll(array, [2, 3]);
6850 * console.log(array);
6853 function pullAll(array, values) {
6854 return (array && array.length && values && values.length)
6855 ? basePullAll(array, values)
6860 * This method is like `_.pullAll` except that it accepts `iteratee` which is
6861 * invoked for each element of `array` and `values` to generate the criterion
6862 * by which they're compared. The iteratee is invoked with one argument: (value).
6864 * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
6870 * @param {Array} array The array to modify.
6871 * @param {Array} values The values to remove.
6872 * @param {Array|Function|Object|string} [iteratee=_.identity]
6873 * The iteratee invoked per element.
6874 * @returns {Array} Returns `array`.
6877 * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
6879 * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
6880 * console.log(array);
6881 * // => [{ 'x': 2 }]
6883 function pullAllBy(array, values, iteratee) {
6884 return (array && array.length && values && values.length)
6885 ? basePullAll(array, values, getIteratee(iteratee))
6890 * This method is like `_.pullAll` except that it accepts `comparator` which
6891 * is invoked to compare elements of `array` to `values`. The comparator is
6892 * invoked with two arguments: (arrVal, othVal).
6894 * **Note:** Unlike `_.differenceWith`, this method mutates `array`.
6900 * @param {Array} array The array to modify.
6901 * @param {Array} values The values to remove.
6902 * @param {Function} [comparator] The comparator invoked per element.
6903 * @returns {Array} Returns `array`.
6906 * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
6908 * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
6909 * console.log(array);
6910 * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
6912 function pullAllWith(array, values, comparator) {
6913 return (array && array.length && values && values.length)
6914 ? basePullAll(array, values, undefined, comparator)
6919 * Removes elements from `array` corresponding to `indexes` and returns an
6920 * array of removed elements.
6922 * **Note:** Unlike `_.at`, this method mutates `array`.
6928 * @param {Array} array The array to modify.
6929 * @param {...(number|number[])} [indexes] The indexes of elements to remove.
6930 * @returns {Array} Returns the new array of removed elements.
6933 * var array = [5, 10, 15, 20];
6934 * var evens = _.pullAt(array, 1, 3);
6936 * console.log(array);
6939 * console.log(evens);
6942 var pullAt = rest(function(array, indexes) {
6943 indexes = baseFlatten(indexes, 1);
6945 var length = array ? array.length : 0,
6946 result = baseAt(array, indexes);
6948 basePullAt(array, arrayMap(indexes, function(index) {
6949 return isIndex(index, length) ? +index : index;
6950 }).sort(compareAscending));
6956 * Removes all elements from `array` that `predicate` returns truthy for
6957 * and returns an array of the removed elements. The predicate is invoked
6958 * with three arguments: (value, index, array).
6960 * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
6961 * to pull elements from an array by value.
6967 * @param {Array} array The array to modify.
6968 * @param {Array|Function|Object|string} [predicate=_.identity]
6969 * The function invoked per iteration.
6970 * @returns {Array} Returns the new array of removed elements.
6973 * var array = [1, 2, 3, 4];
6974 * var evens = _.remove(array, function(n) {
6975 * return n % 2 == 0;
6978 * console.log(array);
6981 * console.log(evens);
6984 function remove(array, predicate) {
6986 if (!(array && array.length)) {
6991 length = array.length;
6993 predicate = getIteratee(predicate, 3);
6994 while (++index < length) {
6995 var value = array[index];
6996 if (predicate(value, index, array)) {
6998 indexes.push(index);
7001 basePullAt(array, indexes);
7006 * Reverses `array` so that the first element becomes the last, the second
7007 * element becomes the second to last, and so on.
7009 * **Note:** This method mutates `array` and is based on
7010 * [`Array#reverse`](https://mdn.io/Array/reverse).
7016 * @param {Array} array The array to modify.
7017 * @returns {Array} Returns `array`.
7020 * var array = [1, 2, 3];
7025 * console.log(array);
7028 function reverse(array) {
7029 return array ? nativeReverse.call(array) : array;
7033 * Creates a slice of `array` from `start` up to, but not including, `end`.
7035 * **Note:** This method is used instead of
7036 * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
7043 * @param {Array} array The array to slice.
7044 * @param {number} [start=0] The start position.
7045 * @param {number} [end=array.length] The end position.
7046 * @returns {Array} Returns the slice of `array`.
7048 function slice(array, start, end) {
7049 var length = array ? array.length : 0;
7053 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
7058 start = start == null ? 0 : toInteger(start);
7059 end = end === undefined ? length : toInteger(end);
7061 return baseSlice(array, start, end);
7065 * Uses a binary search to determine the lowest index at which `value`
7066 * should be inserted into `array` in order to maintain its sort order.
7072 * @param {Array} array The sorted array to inspect.
7073 * @param {*} value The value to evaluate.
7074 * @returns {number} Returns the index at which `value` should be inserted
7078 * _.sortedIndex([30, 50], 40);
7081 * _.sortedIndex([4, 5], 4);
7084 function sortedIndex(array, value) {
7085 return baseSortedIndex(array, value);
7089 * This method is like `_.sortedIndex` except that it accepts `iteratee`
7090 * which is invoked for `value` and each element of `array` to compute their
7091 * sort ranking. The iteratee is invoked with one argument: (value).
7097 * @param {Array} array The sorted array to inspect.
7098 * @param {*} value The value to evaluate.
7099 * @param {Array|Function|Object|string} [iteratee=_.identity]
7100 * The iteratee invoked per element.
7101 * @returns {number} Returns the index at which `value` should be inserted
7105 * var dict = { 'thirty': 30, 'forty': 40, 'fifty': 50 };
7107 * _.sortedIndexBy(['thirty', 'fifty'], 'forty', _.propertyOf(dict));
7110 * // The `_.property` iteratee shorthand.
7111 * _.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
7114 function sortedIndexBy(array, value, iteratee) {
7115 return baseSortedIndexBy(array, value, getIteratee(iteratee));
7119 * This method is like `_.indexOf` except that it performs a binary
7120 * search on a sorted `array`.
7126 * @param {Array} array The array to search.
7127 * @param {*} value The value to search for.
7128 * @returns {number} Returns the index of the matched value, else `-1`.
7131 * _.sortedIndexOf([1, 1, 2, 2], 2);
7134 function sortedIndexOf(array, value) {
7135 var length = array ? array.length : 0;
7137 var index = baseSortedIndex(array, value);
7138 if (index < length && eq(array[index], value)) {
7146 * This method is like `_.sortedIndex` except that it returns the highest
7147 * index at which `value` should be inserted into `array` in order to
7148 * maintain its sort order.
7154 * @param {Array} array The sorted array to inspect.
7155 * @param {*} value The value to evaluate.
7156 * @returns {number} Returns the index at which `value` should be inserted
7160 * _.sortedLastIndex([4, 5], 4);
7163 function sortedLastIndex(array, value) {
7164 return baseSortedIndex(array, value, true);
7168 * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
7169 * which is invoked for `value` and each element of `array` to compute their
7170 * sort ranking. The iteratee is invoked with one argument: (value).
7176 * @param {Array} array The sorted array to inspect.
7177 * @param {*} value The value to evaluate.
7178 * @param {Array|Function|Object|string} [iteratee=_.identity]
7179 * The iteratee invoked per element.
7180 * @returns {number} Returns the index at which `value` should be inserted
7184 * // The `_.property` iteratee shorthand.
7185 * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
7188 function sortedLastIndexBy(array, value, iteratee) {
7189 return baseSortedIndexBy(array, value, getIteratee(iteratee), true);
7193 * This method is like `_.lastIndexOf` except that it performs a binary
7194 * search on a sorted `array`.
7200 * @param {Array} array The array to search.
7201 * @param {*} value The value to search for.
7202 * @returns {number} Returns the index of the matched value, else `-1`.
7205 * _.sortedLastIndexOf([1, 1, 2, 2], 2);
7208 function sortedLastIndexOf(array, value) {
7209 var length = array ? array.length : 0;
7211 var index = baseSortedIndex(array, value, true) - 1;
7212 if (eq(array[index], value)) {
7220 * This method is like `_.uniq` except that it's designed and optimized
7221 * for sorted arrays.
7227 * @param {Array} array The array to inspect.
7228 * @returns {Array} Returns the new duplicate free array.
7231 * _.sortedUniq([1, 1, 2]);
7234 function sortedUniq(array) {
7235 return (array && array.length)
7236 ? baseSortedUniq(array)
7241 * This method is like `_.uniqBy` except that it's designed and optimized
7242 * for sorted arrays.
7248 * @param {Array} array The array to inspect.
7249 * @param {Function} [iteratee] The iteratee invoked per element.
7250 * @returns {Array} Returns the new duplicate free array.
7253 * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
7256 function sortedUniqBy(array, iteratee) {
7257 return (array && array.length)
7258 ? baseSortedUniq(array, getIteratee(iteratee))
7263 * Gets all but the first element of `array`.
7269 * @param {Array} array The array to query.
7270 * @returns {Array} Returns the slice of `array`.
7273 * _.tail([1, 2, 3]);
7276 function tail(array) {
7277 return drop(array, 1);
7281 * Creates a slice of `array` with `n` elements taken from the beginning.
7287 * @param {Array} array The array to query.
7288 * @param {number} [n=1] The number of elements to take.
7289 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
7290 * @returns {Array} Returns the slice of `array`.
7293 * _.take([1, 2, 3]);
7296 * _.take([1, 2, 3], 2);
7299 * _.take([1, 2, 3], 5);
7302 * _.take([1, 2, 3], 0);
7305 function take(array, n, guard) {
7306 if (!(array && array.length)) {
7309 n = (guard || n === undefined) ? 1 : toInteger(n);
7310 return baseSlice(array, 0, n < 0 ? 0 : n);
7314 * Creates a slice of `array` with `n` elements taken from the end.
7320 * @param {Array} array The array to query.
7321 * @param {number} [n=1] The number of elements to take.
7322 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
7323 * @returns {Array} Returns the slice of `array`.
7326 * _.takeRight([1, 2, 3]);
7329 * _.takeRight([1, 2, 3], 2);
7332 * _.takeRight([1, 2, 3], 5);
7335 * _.takeRight([1, 2, 3], 0);
7338 function takeRight(array, n, guard) {
7339 var length = array ? array.length : 0;
7343 n = (guard || n === undefined) ? 1 : toInteger(n);
7345 return baseSlice(array, n < 0 ? 0 : n, length);
7349 * Creates a slice of `array` with elements taken from the end. Elements are
7350 * taken until `predicate` returns falsey. The predicate is invoked with
7351 * three arguments: (value, index, array).
7357 * @param {Array} array The array to query.
7358 * @param {Array|Function|Object|string} [predicate=_.identity]
7359 * The function invoked per iteration.
7360 * @returns {Array} Returns the slice of `array`.
7364 * { 'user': 'barney', 'active': true },
7365 * { 'user': 'fred', 'active': false },
7366 * { 'user': 'pebbles', 'active': false }
7369 * _.takeRightWhile(users, function(o) { return !o.active; });
7370 * // => objects for ['fred', 'pebbles']
7372 * // The `_.matches` iteratee shorthand.
7373 * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
7374 * // => objects for ['pebbles']
7376 * // The `_.matchesProperty` iteratee shorthand.
7377 * _.takeRightWhile(users, ['active', false]);
7378 * // => objects for ['fred', 'pebbles']
7380 * // The `_.property` iteratee shorthand.
7381 * _.takeRightWhile(users, 'active');
7384 function takeRightWhile(array, predicate) {
7385 return (array && array.length)
7386 ? baseWhile(array, getIteratee(predicate, 3), false, true)
7391 * Creates a slice of `array` with elements taken from the beginning. Elements
7392 * are taken until `predicate` returns falsey. The predicate is invoked with
7393 * three arguments: (value, index, array).
7399 * @param {Array} array The array to query.
7400 * @param {Array|Function|Object|string} [predicate=_.identity]
7401 * The function invoked per iteration.
7402 * @returns {Array} Returns the slice of `array`.
7406 * { 'user': 'barney', 'active': false },
7407 * { 'user': 'fred', 'active': false},
7408 * { 'user': 'pebbles', 'active': true }
7411 * _.takeWhile(users, function(o) { return !o.active; });
7412 * // => objects for ['barney', 'fred']
7414 * // The `_.matches` iteratee shorthand.
7415 * _.takeWhile(users, { 'user': 'barney', 'active': false });
7416 * // => objects for ['barney']
7418 * // The `_.matchesProperty` iteratee shorthand.
7419 * _.takeWhile(users, ['active', false]);
7420 * // => objects for ['barney', 'fred']
7422 * // The `_.property` iteratee shorthand.
7423 * _.takeWhile(users, 'active');
7426 function takeWhile(array, predicate) {
7427 return (array && array.length)
7428 ? baseWhile(array, getIteratee(predicate, 3))
7433 * Creates an array of unique values, in order, from all given arrays using
7434 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
7435 * for equality comparisons.
7441 * @param {...Array} [arrays] The arrays to inspect.
7442 * @returns {Array} Returns the new array of combined values.
7445 * _.union([2, 1], [4, 2], [1, 2]);
7448 var union = rest(function(arrays) {
7449 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
7453 * This method is like `_.union` except that it accepts `iteratee` which is
7454 * invoked for each element of each `arrays` to generate the criterion by
7455 * which uniqueness is computed. The iteratee is invoked with one argument:
7462 * @param {...Array} [arrays] The arrays to inspect.
7463 * @param {Array|Function|Object|string} [iteratee=_.identity]
7464 * The iteratee invoked per element.
7465 * @returns {Array} Returns the new array of combined values.
7468 * _.unionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
7469 * // => [2.1, 1.2, 4.3]
7471 * // The `_.property` iteratee shorthand.
7472 * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
7473 * // => [{ 'x': 1 }, { 'x': 2 }]
7475 var unionBy = rest(function(arrays) {
7476 var iteratee = last(arrays);
7477 if (isArrayLikeObject(iteratee)) {
7478 iteratee = undefined;
7480 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee));
7484 * This method is like `_.union` except that it accepts `comparator` which
7485 * is invoked to compare elements of `arrays`. The comparator is invoked
7486 * with two arguments: (arrVal, othVal).
7492 * @param {...Array} [arrays] The arrays to inspect.
7493 * @param {Function} [comparator] The comparator invoked per element.
7494 * @returns {Array} Returns the new array of combined values.
7497 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
7498 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
7500 * _.unionWith(objects, others, _.isEqual);
7501 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
7503 var unionWith = rest(function(arrays) {
7504 var comparator = last(arrays);
7505 if (isArrayLikeObject(comparator)) {
7506 comparator = undefined;
7508 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
7512 * Creates a duplicate-free version of an array, using
7513 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
7514 * for equality comparisons, in which only the first occurrence of each
7521 * @param {Array} array The array to inspect.
7522 * @returns {Array} Returns the new duplicate free array.
7525 * _.uniq([2, 1, 2]);
7528 function uniq(array) {
7529 return (array && array.length)
7535 * This method is like `_.uniq` except that it accepts `iteratee` which is
7536 * invoked for each element in `array` to generate the criterion by which
7537 * uniqueness is computed. The iteratee is invoked with one argument: (value).
7543 * @param {Array} array The array to inspect.
7544 * @param {Array|Function|Object|string} [iteratee=_.identity]
7545 * The iteratee invoked per element.
7546 * @returns {Array} Returns the new duplicate free array.
7549 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
7552 * // The `_.property` iteratee shorthand.
7553 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
7554 * // => [{ 'x': 1 }, { 'x': 2 }]
7556 function uniqBy(array, iteratee) {
7557 return (array && array.length)
7558 ? baseUniq(array, getIteratee(iteratee))
7563 * This method is like `_.uniq` except that it accepts `comparator` which
7564 * is invoked to compare elements of `array`. The comparator is invoked with
7565 * two arguments: (arrVal, othVal).
7571 * @param {Array} array The array to inspect.
7572 * @param {Function} [comparator] The comparator invoked per element.
7573 * @returns {Array} Returns the new duplicate free array.
7576 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
7578 * _.uniqWith(objects, _.isEqual);
7579 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
7581 function uniqWith(array, comparator) {
7582 return (array && array.length)
7583 ? baseUniq(array, undefined, comparator)
7588 * This method is like `_.zip` except that it accepts an array of grouped
7589 * elements and creates an array regrouping the elements to their pre-zip
7596 * @param {Array} array The array of grouped elements to process.
7597 * @returns {Array} Returns the new array of regrouped elements.
7600 * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
7601 * // => [['fred', 30, true], ['barney', 40, false]]
7604 * // => [['fred', 'barney'], [30, 40], [true, false]]
7606 function unzip(array) {
7607 if (!(array && array.length)) {
7611 array = arrayFilter(array, function(group) {
7612 if (isArrayLikeObject(group)) {
7613 length = nativeMax(group.length, length);
7617 return baseTimes(length, function(index) {
7618 return arrayMap(array, baseProperty(index));
7623 * This method is like `_.unzip` except that it accepts `iteratee` to specify
7624 * how regrouped values should be combined. The iteratee is invoked with the
7625 * elements of each group: (...group).
7631 * @param {Array} array The array of grouped elements to process.
7632 * @param {Function} [iteratee=_.identity] The function to combine
7634 * @returns {Array} Returns the new array of regrouped elements.
7637 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
7638 * // => [[1, 10, 100], [2, 20, 200]]
7640 * _.unzipWith(zipped, _.add);
7641 * // => [3, 30, 300]
7643 function unzipWith(array, iteratee) {
7644 if (!(array && array.length)) {
7647 var result = unzip(array);
7648 if (iteratee == null) {
7651 return arrayMap(result, function(group) {
7652 return apply(iteratee, undefined, group);
7657 * Creates an array excluding all given values using
7658 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
7659 * for equality comparisons.
7665 * @param {Array} array The array to filter.
7666 * @param {...*} [values] The values to exclude.
7667 * @returns {Array} Returns the new array of filtered values.
7668 * @see _.difference, _.xor
7671 * _.without([1, 2, 1, 3], 1, 2);
7674 var without = rest(function(array, values) {
7675 return isArrayLikeObject(array)
7676 ? baseDifference(array, values)
7681 * Creates an array of unique values that is the
7682 * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
7683 * of the given arrays. The order of result values is determined by the order
7684 * they occur in the arrays.
7690 * @param {...Array} [arrays] The arrays to inspect.
7691 * @returns {Array} Returns the new array of values.
7692 * @see _.difference, _.without
7695 * _.xor([2, 1], [4, 2]);
7698 var xor = rest(function(arrays) {
7699 return baseXor(arrayFilter(arrays, isArrayLikeObject));
7703 * This method is like `_.xor` except that it accepts `iteratee` which is
7704 * invoked for each element of each `arrays` to generate the criterion by
7705 * which by which they're compared. The iteratee is invoked with one argument:
7712 * @param {...Array} [arrays] The arrays to inspect.
7713 * @param {Array|Function|Object|string} [iteratee=_.identity]
7714 * The iteratee invoked per element.
7715 * @returns {Array} Returns the new array of values.
7718 * _.xorBy([2.1, 1.2], [4.3, 2.4], Math.floor);
7721 * // The `_.property` iteratee shorthand.
7722 * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
7723 * // => [{ 'x': 2 }]
7725 var xorBy = rest(function(arrays) {
7726 var iteratee = last(arrays);
7727 if (isArrayLikeObject(iteratee)) {
7728 iteratee = undefined;
7730 return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee));
7734 * This method is like `_.xor` except that it accepts `comparator` which is
7735 * invoked to compare elements of `arrays`. The comparator is invoked with
7736 * two arguments: (arrVal, othVal).
7742 * @param {...Array} [arrays] The arrays to inspect.
7743 * @param {Function} [comparator] The comparator invoked per element.
7744 * @returns {Array} Returns the new array of values.
7747 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
7748 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
7750 * _.xorWith(objects, others, _.isEqual);
7751 * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
7753 var xorWith = rest(function(arrays) {
7754 var comparator = last(arrays);
7755 if (isArrayLikeObject(comparator)) {
7756 comparator = undefined;
7758 return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
7762 * Creates an array of grouped elements, the first of which contains the
7763 * first elements of the given arrays, the second of which contains the
7764 * second elements of the given arrays, and so on.
7770 * @param {...Array} [arrays] The arrays to process.
7771 * @returns {Array} Returns the new array of grouped elements.
7774 * _.zip(['fred', 'barney'], [30, 40], [true, false]);
7775 * // => [['fred', 30, true], ['barney', 40, false]]
7777 var zip = rest(unzip);
7780 * This method is like `_.fromPairs` except that it accepts two arrays,
7781 * one of property identifiers and one of corresponding values.
7787 * @param {Array} [props=[]] The property identifiers.
7788 * @param {Array} [values=[]] The property values.
7789 * @returns {Object} Returns the new object.
7792 * _.zipObject(['a', 'b'], [1, 2]);
7793 * // => { 'a': 1, 'b': 2 }
7795 function zipObject(props, values) {
7796 return baseZipObject(props || [], values || [], assignValue);
7800 * This method is like `_.zipObject` except that it supports property paths.
7806 * @param {Array} [props=[]] The property identifiers.
7807 * @param {Array} [values=[]] The property values.
7808 * @returns {Object} Returns the new object.
7811 * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
7812 * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
7814 function zipObjectDeep(props, values) {
7815 return baseZipObject(props || [], values || [], baseSet);
7819 * This method is like `_.zip` except that it accepts `iteratee` to specify
7820 * how grouped values should be combined. The iteratee is invoked with the
7821 * elements of each group: (...group).
7827 * @param {...Array} [arrays] The arrays to process.
7828 * @param {Function} [iteratee=_.identity] The function to combine grouped values.
7829 * @returns {Array} Returns the new array of grouped elements.
7832 * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
7837 var zipWith = rest(function(arrays) {
7838 var length = arrays.length,
7839 iteratee = length > 1 ? arrays[length - 1] : undefined;
7841 iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
7842 return unzipWith(arrays, iteratee);
7845 /*------------------------------------------------------------------------*/
7848 * Creates a `lodash` wrapper instance that wraps `value` with explicit method
7849 * chain sequences enabled. The result of such sequences must be unwrapped
7856 * @param {*} value The value to wrap.
7857 * @returns {Object} Returns the new `lodash` wrapper instance.
7861 * { 'user': 'barney', 'age': 36 },
7862 * { 'user': 'fred', 'age': 40 },
7863 * { 'user': 'pebbles', 'age': 1 }
7869 * .map(function(o) {
7870 * return o.user + ' is ' + o.age;
7874 * // => 'pebbles is 1'
7876 function chain(value) {
7877 var result = lodash(value);
7878 result.__chain__ = true;
7883 * This method invokes `interceptor` and returns `value`. The interceptor
7884 * is invoked with one argument; (value). The purpose of this method is to
7885 * "tap into" a method chain sequence in order to modify intermediate results.
7891 * @param {*} value The value to provide to `interceptor`.
7892 * @param {Function} interceptor The function to invoke.
7893 * @returns {*} Returns `value`.
7897 * .tap(function(array) {
7898 * // Mutate input array.
7905 function tap(value, interceptor) {
7911 * This method is like `_.tap` except that it returns the result of `interceptor`.
7912 * The purpose of this method is to "pass thru" values replacing intermediate
7913 * results in a method chain sequence.
7919 * @param {*} value The value to provide to `interceptor`.
7920 * @param {Function} interceptor The function to invoke.
7921 * @returns {*} Returns the result of `interceptor`.
7927 * .thru(function(value) {
7933 function thru(value, interceptor) {
7934 return interceptor(value);
7938 * This method is the wrapper version of `_.at`.
7944 * @param {...(string|string[])} [paths] The property paths of elements to pick.
7945 * @returns {Object} Returns the new `lodash` wrapper instance.
7948 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
7950 * _(object).at(['a[0].b.c', 'a[1]']).value();
7953 * _(['a', 'b', 'c']).at(0, 2).value();
7956 var wrapperAt = rest(function(paths) {
7957 paths = baseFlatten(paths, 1);
7958 var length = paths.length,
7959 start = length ? paths[0] : 0,
7960 value = this.__wrapped__,
7961 interceptor = function(object) { return baseAt(object, paths); };
7963 if (length > 1 || this.__actions__.length ||
7964 !(value instanceof LazyWrapper) || !isIndex(start)) {
7965 return this.thru(interceptor);
7967 value = value.slice(start, +start + (length ? 1 : 0));
7968 value.__actions__.push({
7970 'args': [interceptor],
7971 'thisArg': undefined
7973 return new LodashWrapper(value, this.__chain__).thru(function(array) {
7974 if (length && !array.length) {
7975 array.push(undefined);
7982 * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
7988 * @returns {Object} Returns the new `lodash` wrapper instance.
7992 * { 'user': 'barney', 'age': 36 },
7993 * { 'user': 'fred', 'age': 40 }
7996 * // A sequence without explicit chaining.
7998 * // => { 'user': 'barney', 'age': 36 }
8000 * // A sequence with explicit chaining.
8006 * // => { 'user': 'barney' }
8008 function wrapperChain() {
8013 * Executes the chain sequence and returns the wrapped result.
8019 * @returns {Object} Returns the new `lodash` wrapper instance.
8022 * var array = [1, 2];
8023 * var wrapped = _(array).push(3);
8025 * console.log(array);
8028 * wrapped = wrapped.commit();
8029 * console.log(array);
8035 * console.log(array);
8038 function wrapperCommit() {
8039 return new LodashWrapper(this.value(), this.__chain__);
8043 * Gets the next value on a wrapped object following the
8044 * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
8050 * @returns {Object} Returns the next iterator value.
8053 * var wrapped = _([1, 2]);
8056 * // => { 'done': false, 'value': 1 }
8059 * // => { 'done': false, 'value': 2 }
8062 * // => { 'done': true, 'value': undefined }
8064 function wrapperNext() {
8065 if (this.__values__ === undefined) {
8066 this.__values__ = toArray(this.value());
8068 var done = this.__index__ >= this.__values__.length,
8069 value = done ? undefined : this.__values__[this.__index__++];
8071 return { 'done': done, 'value': value };
8075 * Enables the wrapper to be iterable.
8077 * @name Symbol.iterator
8081 * @returns {Object} Returns the wrapper object.
8084 * var wrapped = _([1, 2]);
8086 * wrapped[Symbol.iterator]() === wrapped;
8089 * Array.from(wrapped);
8092 function wrapperToIterator() {
8097 * Creates a clone of the chain sequence planting `value` as the wrapped value.
8103 * @param {*} value The value to plant.
8104 * @returns {Object} Returns the new `lodash` wrapper instance.
8107 * function square(n) {
8111 * var wrapped = _([1, 2]).map(square);
8112 * var other = wrapped.plant([3, 4]);
8120 function wrapperPlant(value) {
8124 while (parent instanceof baseLodash) {
8125 var clone = wrapperClone(parent);
8126 clone.__index__ = 0;
8127 clone.__values__ = undefined;
8129 previous.__wrapped__ = clone;
8133 var previous = clone;
8134 parent = parent.__wrapped__;
8136 previous.__wrapped__ = value;
8141 * This method is the wrapper version of `_.reverse`.
8143 * **Note:** This method mutates the wrapped array.
8149 * @returns {Object} Returns the new `lodash` wrapper instance.
8152 * var array = [1, 2, 3];
8154 * _(array).reverse().value()
8157 * console.log(array);
8160 function wrapperReverse() {
8161 var value = this.__wrapped__;
8162 if (value instanceof LazyWrapper) {
8163 var wrapped = value;
8164 if (this.__actions__.length) {
8165 wrapped = new LazyWrapper(this);
8167 wrapped = wrapped.reverse();
8168 wrapped.__actions__.push({
8171 'thisArg': undefined
8173 return new LodashWrapper(wrapped, this.__chain__);
8175 return this.thru(reverse);
8179 * Executes the chain sequence to resolve the unwrapped value.
8184 * @alias toJSON, valueOf
8186 * @returns {*} Returns the resolved unwrapped value.
8189 * _([1, 2, 3]).value();
8192 function wrapperValue() {
8193 return baseWrapperValue(this.__wrapped__, this.__actions__);
8196 /*------------------------------------------------------------------------*/
8199 * Creates an object composed of keys generated from the results of running
8200 * each element of `collection` thru `iteratee`. The corresponding value of
8201 * each key is the number of times the key was returned by `iteratee`. The
8202 * iteratee is invoked with one argument: (value).
8207 * @category Collection
8208 * @param {Array|Object} collection The collection to iterate over.
8209 * @param {Array|Function|Object|string} [iteratee=_.identity]
8210 * The iteratee to transform keys.
8211 * @returns {Object} Returns the composed aggregate object.
8214 * _.countBy([6.1, 4.2, 6.3], Math.floor);
8215 * // => { '4': 1, '6': 2 }
8217 * _.countBy(['one', 'two', 'three'], 'length');
8218 * // => { '3': 2, '5': 1 }
8220 var countBy = createAggregator(function(result, value, key) {
8221 hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
8225 * Checks if `predicate` returns truthy for **all** elements of `collection`.
8226 * Iteration is stopped once `predicate` returns falsey. The predicate is
8227 * invoked with three arguments: (value, index|key, collection).
8232 * @category Collection
8233 * @param {Array|Object} collection The collection to iterate over.
8234 * @param {Array|Function|Object|string} [predicate=_.identity]
8235 * The function invoked per iteration.
8236 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
8237 * @returns {boolean} Returns `true` if all elements pass the predicate check,
8241 * _.every([true, 1, null, 'yes'], Boolean);
8245 * { 'user': 'barney', 'age': 36, 'active': false },
8246 * { 'user': 'fred', 'age': 40, 'active': false }
8249 * // The `_.matches` iteratee shorthand.
8250 * _.every(users, { 'user': 'barney', 'active': false });
8253 * // The `_.matchesProperty` iteratee shorthand.
8254 * _.every(users, ['active', false]);
8257 * // The `_.property` iteratee shorthand.
8258 * _.every(users, 'active');
8261 function every(collection, predicate, guard) {
8262 var func = isArray(collection) ? arrayEvery : baseEvery;
8263 if (guard && isIterateeCall(collection, predicate, guard)) {
8264 predicate = undefined;
8266 return func(collection, getIteratee(predicate, 3));
8270 * Iterates over elements of `collection`, returning an array of all elements
8271 * `predicate` returns truthy for. The predicate is invoked with three
8272 * arguments: (value, index|key, collection).
8277 * @category Collection
8278 * @param {Array|Object} collection The collection to iterate over.
8279 * @param {Array|Function|Object|string} [predicate=_.identity]
8280 * The function invoked per iteration.
8281 * @returns {Array} Returns the new filtered array.
8286 * { 'user': 'barney', 'age': 36, 'active': true },
8287 * { 'user': 'fred', 'age': 40, 'active': false }
8290 * _.filter(users, function(o) { return !o.active; });
8291 * // => objects for ['fred']
8293 * // The `_.matches` iteratee shorthand.
8294 * _.filter(users, { 'age': 36, 'active': true });
8295 * // => objects for ['barney']
8297 * // The `_.matchesProperty` iteratee shorthand.
8298 * _.filter(users, ['active', false]);
8299 * // => objects for ['fred']
8301 * // The `_.property` iteratee shorthand.
8302 * _.filter(users, 'active');
8303 * // => objects for ['barney']
8305 function filter(collection, predicate) {
8306 var func = isArray(collection) ? arrayFilter : baseFilter;
8307 return func(collection, getIteratee(predicate, 3));
8311 * Iterates over elements of `collection`, returning the first element
8312 * `predicate` returns truthy for. The predicate is invoked with three
8313 * arguments: (value, index|key, collection).
8318 * @category Collection
8319 * @param {Array|Object} collection The collection to search.
8320 * @param {Array|Function|Object|string} [predicate=_.identity]
8321 * The function invoked per iteration.
8322 * @returns {*} Returns the matched element, else `undefined`.
8326 * { 'user': 'barney', 'age': 36, 'active': true },
8327 * { 'user': 'fred', 'age': 40, 'active': false },
8328 * { 'user': 'pebbles', 'age': 1, 'active': true }
8331 * _.find(users, function(o) { return o.age < 40; });
8332 * // => object for 'barney'
8334 * // The `_.matches` iteratee shorthand.
8335 * _.find(users, { 'age': 1, 'active': true });
8336 * // => object for 'pebbles'
8338 * // The `_.matchesProperty` iteratee shorthand.
8339 * _.find(users, ['active', false]);
8340 * // => object for 'fred'
8342 * // The `_.property` iteratee shorthand.
8343 * _.find(users, 'active');
8344 * // => object for 'barney'
8346 function find(collection, predicate) {
8347 predicate = getIteratee(predicate, 3);
8348 if (isArray(collection)) {
8349 var index = baseFindIndex(collection, predicate);
8350 return index > -1 ? collection[index] : undefined;
8352 return baseFind(collection, predicate, baseEach);
8356 * This method is like `_.find` except that it iterates over elements of
8357 * `collection` from right to left.
8362 * @category Collection
8363 * @param {Array|Object} collection The collection to search.
8364 * @param {Array|Function|Object|string} [predicate=_.identity]
8365 * The function invoked per iteration.
8366 * @returns {*} Returns the matched element, else `undefined`.
8369 * _.findLast([1, 2, 3, 4], function(n) {
8370 * return n % 2 == 1;
8374 function findLast(collection, predicate) {
8375 predicate = getIteratee(predicate, 3);
8376 if (isArray(collection)) {
8377 var index = baseFindIndex(collection, predicate, true);
8378 return index > -1 ? collection[index] : undefined;
8380 return baseFind(collection, predicate, baseEachRight);
8384 * Creates a flattened array of values by running each element in `collection`
8385 * thru `iteratee` and flattening the mapped results. The iteratee is invoked
8386 * with three arguments: (value, index|key, collection).
8391 * @category Collection
8392 * @param {Array|Object} collection The collection to iterate over.
8393 * @param {Array|Function|Object|string} [iteratee=_.identity]
8394 * The function invoked per iteration.
8395 * @returns {Array} Returns the new flattened array.
8398 * function duplicate(n) {
8402 * _.flatMap([1, 2], duplicate);
8403 * // => [1, 1, 2, 2]
8405 function flatMap(collection, iteratee) {
8406 return baseFlatten(map(collection, iteratee), 1);
8410 * This method is like `_.flatMap` except that it recursively flattens the
8416 * @category Collection
8417 * @param {Array|Object} collection The collection to iterate over.
8418 * @param {Array|Function|Object|string} [iteratee=_.identity]
8419 * The function invoked per iteration.
8420 * @returns {Array} Returns the new flattened array.
8423 * function duplicate(n) {
8424 * return [[[n, n]]];
8427 * _.flatMapDeep([1, 2], duplicate);
8428 * // => [1, 1, 2, 2]
8430 function flatMapDeep(collection, iteratee) {
8431 return baseFlatten(map(collection, iteratee), INFINITY);
8435 * This method is like `_.flatMap` except that it recursively flattens the
8436 * mapped results up to `depth` times.
8441 * @category Collection
8442 * @param {Array|Object} collection The collection to iterate over.
8443 * @param {Array|Function|Object|string} [iteratee=_.identity]
8444 * The function invoked per iteration.
8445 * @param {number} [depth=1] The maximum recursion depth.
8446 * @returns {Array} Returns the new flattened array.
8449 * function duplicate(n) {
8450 * return [[[n, n]]];
8453 * _.flatMapDepth([1, 2], duplicate, 2);
8454 * // => [[1, 1], [2, 2]]
8456 function flatMapDepth(collection, iteratee, depth) {
8457 depth = depth === undefined ? 1 : toInteger(depth);
8458 return baseFlatten(map(collection, iteratee), depth);
8462 * Iterates over elements of `collection` and invokes `iteratee` for each element.
8463 * The iteratee is invoked with three arguments: (value, index|key, collection).
8464 * Iteratee functions may exit iteration early by explicitly returning `false`.
8466 * **Note:** As with other "Collections" methods, objects with a "length"
8467 * property are iterated like arrays. To avoid this behavior use `_.forIn`
8468 * or `_.forOwn` for object iteration.
8474 * @category Collection
8475 * @param {Array|Object} collection The collection to iterate over.
8476 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
8477 * @returns {Array|Object} Returns `collection`.
8478 * @see _.forEachRight
8481 * _([1, 2]).forEach(function(value) {
8482 * console.log(value);
8484 * // => Logs `1` then `2`.
8486 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
8489 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
8491 function forEach(collection, iteratee) {
8492 return (typeof iteratee == 'function' && isArray(collection))
8493 ? arrayEach(collection, iteratee)
8494 : baseEach(collection, getIteratee(iteratee));
8498 * This method is like `_.forEach` except that it iterates over elements of
8499 * `collection` from right to left.
8505 * @category Collection
8506 * @param {Array|Object} collection The collection to iterate over.
8507 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
8508 * @returns {Array|Object} Returns `collection`.
8512 * _.forEachRight([1, 2], function(value) {
8513 * console.log(value);
8515 * // => Logs `2` then `1`.
8517 function forEachRight(collection, iteratee) {
8518 return (typeof iteratee == 'function' && isArray(collection))
8519 ? arrayEachRight(collection, iteratee)
8520 : baseEachRight(collection, getIteratee(iteratee));
8524 * Creates an object composed of keys generated from the results of running
8525 * each element of `collection` thru `iteratee`. The order of grouped values
8526 * is determined by the order they occur in `collection`. The corresponding
8527 * value of each key is an array of elements responsible for generating the
8528 * key. The iteratee is invoked with one argument: (value).
8533 * @category Collection
8534 * @param {Array|Object} collection The collection to iterate over.
8535 * @param {Array|Function|Object|string} [iteratee=_.identity]
8536 * The iteratee to transform keys.
8537 * @returns {Object} Returns the composed aggregate object.
8540 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
8541 * // => { '4': [4.2], '6': [6.1, 6.3] }
8543 * // The `_.property` iteratee shorthand.
8544 * _.groupBy(['one', 'two', 'three'], 'length');
8545 * // => { '3': ['one', 'two'], '5': ['three'] }
8547 var groupBy = createAggregator(function(result, value, key) {
8548 if (hasOwnProperty.call(result, key)) {
8549 result[key].push(value);
8551 result[key] = [value];
8556 * Checks if `value` is in `collection`. If `collection` is a string, it's
8557 * checked for a substring of `value`, otherwise
8558 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
8559 * is used for equality comparisons. If `fromIndex` is negative, it's used as
8560 * the offset from the end of `collection`.
8565 * @category Collection
8566 * @param {Array|Object|string} collection The collection to search.
8567 * @param {*} value The value to search for.
8568 * @param {number} [fromIndex=0] The index to search from.
8569 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
8570 * @returns {boolean} Returns `true` if `value` is found, else `false`.
8573 * _.includes([1, 2, 3], 1);
8576 * _.includes([1, 2, 3], 1, 2);
8579 * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
8582 * _.includes('pebbles', 'eb');
8585 function includes(collection, value, fromIndex, guard) {
8586 collection = isArrayLike(collection) ? collection : values(collection);
8587 fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
8589 var length = collection.length;
8590 if (fromIndex < 0) {
8591 fromIndex = nativeMax(length + fromIndex, 0);
8593 return isString(collection)
8594 ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
8595 : (!!length && baseIndexOf(collection, value, fromIndex) > -1);
8599 * Invokes the method at `path` of each element in `collection`, returning
8600 * an array of the results of each invoked method. Any additional arguments
8601 * are provided to each invoked method. If `methodName` is a function, it's
8602 * invoked for and `this` bound to, each element in `collection`.
8607 * @category Collection
8608 * @param {Array|Object} collection The collection to iterate over.
8609 * @param {Array|Function|string} path The path of the method to invoke or
8610 * the function invoked per iteration.
8611 * @param {...*} [args] The arguments to invoke each method with.
8612 * @returns {Array} Returns the array of results.
8615 * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
8616 * // => [[1, 5, 7], [1, 2, 3]]
8618 * _.invokeMap([123, 456], String.prototype.split, '');
8619 * // => [['1', '2', '3'], ['4', '5', '6']]
8621 var invokeMap = rest(function(collection, path, args) {
8623 isFunc = typeof path == 'function',
8624 isProp = isKey(path),
8625 result = isArrayLike(collection) ? Array(collection.length) : [];
8627 baseEach(collection, function(value) {
8628 var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
8629 result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args);
8635 * Creates an object composed of keys generated from the results of running
8636 * each element of `collection` thru `iteratee`. The corresponding value of
8637 * each key is the last element responsible for generating the key. The
8638 * iteratee is invoked with one argument: (value).
8643 * @category Collection
8644 * @param {Array|Object} collection The collection to iterate over.
8645 * @param {Array|Function|Object|string} [iteratee=_.identity]
8646 * The iteratee to transform keys.
8647 * @returns {Object} Returns the composed aggregate object.
8651 * { 'dir': 'left', 'code': 97 },
8652 * { 'dir': 'right', 'code': 100 }
8655 * _.keyBy(array, function(o) {
8656 * return String.fromCharCode(o.code);
8658 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
8660 * _.keyBy(array, 'dir');
8661 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
8663 var keyBy = createAggregator(function(result, value, key) {
8664 result[key] = value;
8668 * Creates an array of values by running each element in `collection` thru
8669 * `iteratee`. The iteratee is invoked with three arguments:
8670 * (value, index|key, collection).
8672 * Many lodash methods are guarded to work as iteratees for methods like
8673 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
8675 * The guarded methods are:
8676 * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
8677 * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
8678 * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
8679 * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
8684 * @category Collection
8685 * @param {Array|Object} collection The collection to iterate over.
8686 * @param {Array|Function|Object|string} [iteratee=_.identity]
8687 * The function invoked per iteration.
8688 * @returns {Array} Returns the new mapped array.
8691 * function square(n) {
8695 * _.map([4, 8], square);
8698 * _.map({ 'a': 4, 'b': 8 }, square);
8699 * // => [16, 64] (iteration order is not guaranteed)
8702 * { 'user': 'barney' },
8703 * { 'user': 'fred' }
8706 * // The `_.property` iteratee shorthand.
8707 * _.map(users, 'user');
8708 * // => ['barney', 'fred']
8710 function map(collection, iteratee) {
8711 var func = isArray(collection) ? arrayMap : baseMap;
8712 return func(collection, getIteratee(iteratee, 3));
8716 * This method is like `_.sortBy` except that it allows specifying the sort
8717 * orders of the iteratees to sort by. If `orders` is unspecified, all values
8718 * are sorted in ascending order. Otherwise, specify an order of "desc" for
8719 * descending or "asc" for ascending sort order of corresponding values.
8724 * @category Collection
8725 * @param {Array|Object} collection The collection to iterate over.
8726 * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
8727 * The iteratees to sort by.
8728 * @param {string[]} [orders] The sort orders of `iteratees`.
8729 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
8730 * @returns {Array} Returns the new sorted array.
8734 * { 'user': 'fred', 'age': 48 },
8735 * { 'user': 'barney', 'age': 34 },
8736 * { 'user': 'fred', 'age': 40 },
8737 * { 'user': 'barney', 'age': 36 }
8740 * // Sort by `user` in ascending order and by `age` in descending order.
8741 * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
8742 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
8744 function orderBy(collection, iteratees, orders, guard) {
8745 if (collection == null) {
8748 if (!isArray(iteratees)) {
8749 iteratees = iteratees == null ? [] : [iteratees];
8751 orders = guard ? undefined : orders;
8752 if (!isArray(orders)) {
8753 orders = orders == null ? [] : [orders];
8755 return baseOrderBy(collection, iteratees, orders);
8759 * Creates an array of elements split into two groups, the first of which
8760 * contains elements `predicate` returns truthy for, the second of which
8761 * contains elements `predicate` returns falsey for. The predicate is
8762 * invoked with one argument: (value).
8767 * @category Collection
8768 * @param {Array|Object} collection The collection to iterate over.
8769 * @param {Array|Function|Object|string} [predicate=_.identity]
8770 * The function invoked per iteration.
8771 * @returns {Array} Returns the array of grouped elements.
8775 * { 'user': 'barney', 'age': 36, 'active': false },
8776 * { 'user': 'fred', 'age': 40, 'active': true },
8777 * { 'user': 'pebbles', 'age': 1, 'active': false }
8780 * _.partition(users, function(o) { return o.active; });
8781 * // => objects for [['fred'], ['barney', 'pebbles']]
8783 * // The `_.matches` iteratee shorthand.
8784 * _.partition(users, { 'age': 1, 'active': false });
8785 * // => objects for [['pebbles'], ['barney', 'fred']]
8787 * // The `_.matchesProperty` iteratee shorthand.
8788 * _.partition(users, ['active', false]);
8789 * // => objects for [['barney', 'pebbles'], ['fred']]
8791 * // The `_.property` iteratee shorthand.
8792 * _.partition(users, 'active');
8793 * // => objects for [['fred'], ['barney', 'pebbles']]
8795 var partition = createAggregator(function(result, value, key) {
8796 result[key ? 0 : 1].push(value);
8797 }, function() { return [[], []]; });
8800 * Reduces `collection` to a value which is the accumulated result of running
8801 * each element in `collection` thru `iteratee`, where each successive
8802 * invocation is supplied the return value of the previous. If `accumulator`
8803 * is not given, the first element of `collection` is used as the initial
8804 * value. The iteratee is invoked with four arguments:
8805 * (accumulator, value, index|key, collection).
8807 * Many lodash methods are guarded to work as iteratees for methods like
8808 * `_.reduce`, `_.reduceRight`, and `_.transform`.
8810 * The guarded methods are:
8811 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
8817 * @category Collection
8818 * @param {Array|Object} collection The collection to iterate over.
8819 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
8820 * @param {*} [accumulator] The initial value.
8821 * @returns {*} Returns the accumulated value.
8822 * @see _.reduceRight
8825 * _.reduce([1, 2], function(sum, n) {
8830 * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
8831 * (result[value] || (result[value] = [])).push(key);
8834 * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
8836 function reduce(collection, iteratee, accumulator) {
8837 var func = isArray(collection) ? arrayReduce : baseReduce,
8838 initAccum = arguments.length < 3;
8840 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
8844 * This method is like `_.reduce` except that it iterates over elements of
8845 * `collection` from right to left.
8850 * @category Collection
8851 * @param {Array|Object} collection The collection to iterate over.
8852 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
8853 * @param {*} [accumulator] The initial value.
8854 * @returns {*} Returns the accumulated value.
8858 * var array = [[0, 1], [2, 3], [4, 5]];
8860 * _.reduceRight(array, function(flattened, other) {
8861 * return flattened.concat(other);
8863 * // => [4, 5, 2, 3, 0, 1]
8865 function reduceRight(collection, iteratee, accumulator) {
8866 var func = isArray(collection) ? arrayReduceRight : baseReduce,
8867 initAccum = arguments.length < 3;
8869 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
8873 * The opposite of `_.filter`; this method returns the elements of `collection`
8874 * that `predicate` does **not** return truthy for.
8879 * @category Collection
8880 * @param {Array|Object} collection The collection to iterate over.
8881 * @param {Array|Function|Object|string} [predicate=_.identity]
8882 * The function invoked per iteration.
8883 * @returns {Array} Returns the new filtered array.
8888 * { 'user': 'barney', 'age': 36, 'active': false },
8889 * { 'user': 'fred', 'age': 40, 'active': true }
8892 * _.reject(users, function(o) { return !o.active; });
8893 * // => objects for ['fred']
8895 * // The `_.matches` iteratee shorthand.
8896 * _.reject(users, { 'age': 40, 'active': true });
8897 * // => objects for ['barney']
8899 * // The `_.matchesProperty` iteratee shorthand.
8900 * _.reject(users, ['active', false]);
8901 * // => objects for ['fred']
8903 * // The `_.property` iteratee shorthand.
8904 * _.reject(users, 'active');
8905 * // => objects for ['barney']
8907 function reject(collection, predicate) {
8908 var func = isArray(collection) ? arrayFilter : baseFilter;
8909 predicate = getIteratee(predicate, 3);
8910 return func(collection, function(value, index, collection) {
8911 return !predicate(value, index, collection);
8916 * Gets a random element from `collection`.
8921 * @category Collection
8922 * @param {Array|Object} collection The collection to sample.
8923 * @returns {*} Returns the random element.
8926 * _.sample([1, 2, 3, 4]);
8929 function sample(collection) {
8930 var array = isArrayLike(collection) ? collection : values(collection),
8931 length = array.length;
8933 return length > 0 ? array[baseRandom(0, length - 1)] : undefined;
8937 * Gets `n` random elements at unique keys from `collection` up to the
8938 * size of `collection`.
8943 * @category Collection
8944 * @param {Array|Object} collection The collection to sample.
8945 * @param {number} [n=1] The number of elements to sample.
8946 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
8947 * @returns {Array} Returns the random elements.
8950 * _.sampleSize([1, 2, 3], 2);
8953 * _.sampleSize([1, 2, 3], 4);
8956 function sampleSize(collection, n, guard) {
8958 result = toArray(collection),
8959 length = result.length,
8960 lastIndex = length - 1;
8962 if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
8965 n = baseClamp(toInteger(n), 0, length);
8967 while (++index < n) {
8968 var rand = baseRandom(index, lastIndex),
8969 value = result[rand];
8971 result[rand] = result[index];
8972 result[index] = value;
8979 * Creates an array of shuffled values, using a version of the
8980 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
8985 * @category Collection
8986 * @param {Array|Object} collection The collection to shuffle.
8987 * @returns {Array} Returns the new shuffled array.
8990 * _.shuffle([1, 2, 3, 4]);
8991 * // => [4, 1, 3, 2]
8993 function shuffle(collection) {
8994 return sampleSize(collection, MAX_ARRAY_LENGTH);
8998 * Gets the size of `collection` by returning its length for array-like
8999 * values or the number of own enumerable string keyed properties for objects.
9004 * @category Collection
9005 * @param {Array|Object} collection The collection to inspect.
9006 * @returns {number} Returns the collection size.
9009 * _.size([1, 2, 3]);
9012 * _.size({ 'a': 1, 'b': 2 });
9015 * _.size('pebbles');
9018 function size(collection) {
9019 if (collection == null) {
9022 if (isArrayLike(collection)) {
9023 var result = collection.length;
9024 return (result && isString(collection)) ? stringSize(collection) : result;
9026 if (isObjectLike(collection)) {
9027 var tag = getTag(collection);
9028 if (tag == mapTag || tag == setTag) {
9029 return collection.size;
9032 return keys(collection).length;
9036 * Checks if `predicate` returns truthy for **any** element of `collection`.
9037 * Iteration is stopped once `predicate` returns truthy. The predicate is
9038 * invoked with three arguments: (value, index|key, collection).
9043 * @category Collection
9044 * @param {Array|Object} collection The collection to iterate over.
9045 * @param {Array|Function|Object|string} [predicate=_.identity]
9046 * The function invoked per iteration.
9047 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
9048 * @returns {boolean} Returns `true` if any element passes the predicate check,
9052 * _.some([null, 0, 'yes', false], Boolean);
9056 * { 'user': 'barney', 'active': true },
9057 * { 'user': 'fred', 'active': false }
9060 * // The `_.matches` iteratee shorthand.
9061 * _.some(users, { 'user': 'barney', 'active': false });
9064 * // The `_.matchesProperty` iteratee shorthand.
9065 * _.some(users, ['active', false]);
9068 * // The `_.property` iteratee shorthand.
9069 * _.some(users, 'active');
9072 function some(collection, predicate, guard) {
9073 var func = isArray(collection) ? arraySome : baseSome;
9074 if (guard && isIterateeCall(collection, predicate, guard)) {
9075 predicate = undefined;
9077 return func(collection, getIteratee(predicate, 3));
9081 * Creates an array of elements, sorted in ascending order by the results of
9082 * running each element in a collection thru each iteratee. This method
9083 * performs a stable sort, that is, it preserves the original sort order of
9084 * equal elements. The iteratees are invoked with one argument: (value).
9089 * @category Collection
9090 * @param {Array|Object} collection The collection to iterate over.
9091 * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])}
9092 * [iteratees=[_.identity]] The iteratees to sort by.
9093 * @returns {Array} Returns the new sorted array.
9097 * { 'user': 'fred', 'age': 48 },
9098 * { 'user': 'barney', 'age': 36 },
9099 * { 'user': 'fred', 'age': 40 },
9100 * { 'user': 'barney', 'age': 34 }
9103 * _.sortBy(users, function(o) { return o.user; });
9104 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
9106 * _.sortBy(users, ['user', 'age']);
9107 * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
9109 * _.sortBy(users, 'user', function(o) {
9110 * return Math.floor(o.age / 10);
9112 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
9114 var sortBy = rest(function(collection, iteratees) {
9115 if (collection == null) {
9118 var length = iteratees.length;
9119 if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
9121 } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
9122 iteratees = [iteratees[0]];
9124 iteratees = (iteratees.length == 1 && isArray(iteratees[0]))
9126 : baseFlatten(iteratees, 1, isFlattenableIteratee);
9128 return baseOrderBy(collection, iteratees, []);
9131 /*------------------------------------------------------------------------*/
9134 * Gets the timestamp of the number of milliseconds that have elapsed since
9135 * the Unix epoch (1 January 1970 00:00:00 UTC).
9142 * @returns {number} Returns the timestamp.
9145 * _.defer(function(stamp) {
9146 * console.log(_.now() - stamp);
9148 * // => Logs the number of milliseconds it took for the deferred function to be invoked.
9152 /*------------------------------------------------------------------------*/
9155 * The opposite of `_.before`; this method creates a function that invokes
9156 * `func` once it's called `n` or more times.
9161 * @category Function
9162 * @param {number} n The number of calls before `func` is invoked.
9163 * @param {Function} func The function to restrict.
9164 * @returns {Function} Returns the new restricted function.
9167 * var saves = ['profile', 'settings'];
9169 * var done = _.after(saves.length, function() {
9170 * console.log('done saving!');
9173 * _.forEach(saves, function(type) {
9174 * asyncSave({ 'type': type, 'complete': done });
9176 * // => Logs 'done saving!' after the two async saves have completed.
9178 function after(n, func) {
9179 if (typeof func != 'function') {
9180 throw new TypeError(FUNC_ERROR_TEXT);
9185 return func.apply(this, arguments);
9191 * Creates a function that invokes `func`, with up to `n` arguments,
9192 * ignoring any additional arguments.
9197 * @category Function
9198 * @param {Function} func The function to cap arguments for.
9199 * @param {number} [n=func.length] The arity cap.
9200 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
9201 * @returns {Function} Returns the new function.
9204 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
9207 function ary(func, n, guard) {
9208 n = guard ? undefined : n;
9209 n = (func && n == null) ? func.length : n;
9210 return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
9214 * Creates a function that invokes `func`, with the `this` binding and arguments
9215 * of the created function, while it's called less than `n` times. Subsequent
9216 * calls to the created function return the result of the last `func` invocation.
9221 * @category Function
9222 * @param {number} n The number of calls at which `func` is no longer invoked.
9223 * @param {Function} func The function to restrict.
9224 * @returns {Function} Returns the new restricted function.
9227 * jQuery(element).on('click', _.before(5, addContactToList));
9228 * // => allows adding up to 4 contacts to the list
9230 function before(n, func) {
9232 if (typeof func != 'function') {
9233 throw new TypeError(FUNC_ERROR_TEXT);
9238 result = func.apply(this, arguments);
9248 * Creates a function that invokes `func` with the `this` binding of `thisArg`
9249 * and `partials` prepended to the arguments it receives.
9251 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
9252 * may be used as a placeholder for partially applied arguments.
9254 * **Note:** Unlike native `Function#bind` this method doesn't set the "length"
9255 * property of bound functions.
9260 * @category Function
9261 * @param {Function} func The function to bind.
9262 * @param {*} thisArg The `this` binding of `func`.
9263 * @param {...*} [partials] The arguments to be partially applied.
9264 * @returns {Function} Returns the new bound function.
9267 * var greet = function(greeting, punctuation) {
9268 * return greeting + ' ' + this.user + punctuation;
9271 * var object = { 'user': 'fred' };
9273 * var bound = _.bind(greet, object, 'hi');
9277 * // Bound with placeholders.
9278 * var bound = _.bind(greet, object, _, '!');
9282 var bind = rest(function(func, thisArg, partials) {
9283 var bitmask = BIND_FLAG;
9284 if (partials.length) {
9285 var holders = replaceHolders(partials, getPlaceholder(bind));
9286 bitmask |= PARTIAL_FLAG;
9288 return createWrapper(func, bitmask, thisArg, partials, holders);
9292 * Creates a function that invokes the method at `object[key]` with `partials`
9293 * prepended to the arguments it receives.
9295 * This method differs from `_.bind` by allowing bound functions to reference
9296 * methods that may be redefined or don't yet exist. See
9297 * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
9300 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
9301 * builds, may be used as a placeholder for partially applied arguments.
9306 * @category Function
9307 * @param {Object} object The object to invoke the method on.
9308 * @param {string} key The key of the method.
9309 * @param {...*} [partials] The arguments to be partially applied.
9310 * @returns {Function} Returns the new bound function.
9315 * 'greet': function(greeting, punctuation) {
9316 * return greeting + ' ' + this.user + punctuation;
9320 * var bound = _.bindKey(object, 'greet', 'hi');
9324 * object.greet = function(greeting, punctuation) {
9325 * return greeting + 'ya ' + this.user + punctuation;
9329 * // => 'hiya fred!'
9331 * // Bound with placeholders.
9332 * var bound = _.bindKey(object, 'greet', _, '!');
9334 * // => 'hiya fred!'
9336 var bindKey = rest(function(object, key, partials) {
9337 var bitmask = BIND_FLAG | BIND_KEY_FLAG;
9338 if (partials.length) {
9339 var holders = replaceHolders(partials, getPlaceholder(bindKey));
9340 bitmask |= PARTIAL_FLAG;
9342 return createWrapper(key, bitmask, object, partials, holders);
9346 * Creates a function that accepts arguments of `func` and either invokes
9347 * `func` returning its result, if at least `arity` number of arguments have
9348 * been provided, or returns a function that accepts the remaining `func`
9349 * arguments, and so on. The arity of `func` may be specified if `func.length`
9350 * is not sufficient.
9352 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
9353 * may be used as a placeholder for provided arguments.
9355 * **Note:** This method doesn't set the "length" property of curried functions.
9360 * @category Function
9361 * @param {Function} func The function to curry.
9362 * @param {number} [arity=func.length] The arity of `func`.
9363 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
9364 * @returns {Function} Returns the new curried function.
9367 * var abc = function(a, b, c) {
9371 * var curried = _.curry(abc);
9382 * // Curried with placeholders.
9383 * curried(1)(_, 3)(2);
9386 function curry(func, arity, guard) {
9387 arity = guard ? undefined : arity;
9388 var result = createWrapper(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
9389 result.placeholder = curry.placeholder;
9394 * This method is like `_.curry` except that arguments are applied to `func`
9395 * in the manner of `_.partialRight` instead of `_.partial`.
9397 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
9398 * builds, may be used as a placeholder for provided arguments.
9400 * **Note:** This method doesn't set the "length" property of curried functions.
9405 * @category Function
9406 * @param {Function} func The function to curry.
9407 * @param {number} [arity=func.length] The arity of `func`.
9408 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
9409 * @returns {Function} Returns the new curried function.
9412 * var abc = function(a, b, c) {
9416 * var curried = _.curryRight(abc);
9427 * // Curried with placeholders.
9428 * curried(3)(1, _)(2);
9431 function curryRight(func, arity, guard) {
9432 arity = guard ? undefined : arity;
9433 var result = createWrapper(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
9434 result.placeholder = curryRight.placeholder;
9439 * Creates a debounced function that delays invoking `func` until after `wait`
9440 * milliseconds have elapsed since the last time the debounced function was
9441 * invoked. The debounced function comes with a `cancel` method to cancel
9442 * delayed `func` invocations and a `flush` method to immediately invoke them.
9443 * Provide an options object to indicate whether `func` should be invoked on
9444 * the leading and/or trailing edge of the `wait` timeout. The `func` is invoked
9445 * with the last arguments provided to the debounced function. Subsequent calls
9446 * to the debounced function return the result of the last `func` invocation.
9448 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
9449 * on the trailing edge of the timeout only if the debounced function is
9450 * invoked more than once during the `wait` timeout.
9452 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
9453 * for details over the differences between `_.debounce` and `_.throttle`.
9458 * @category Function
9459 * @param {Function} func The function to debounce.
9460 * @param {number} [wait=0] The number of milliseconds to delay.
9461 * @param {Object} [options={}] The options object.
9462 * @param {boolean} [options.leading=false]
9463 * Specify invoking on the leading edge of the timeout.
9464 * @param {number} [options.maxWait]
9465 * The maximum time `func` is allowed to be delayed before it's invoked.
9466 * @param {boolean} [options.trailing=true]
9467 * Specify invoking on the trailing edge of the timeout.
9468 * @returns {Function} Returns the new debounced function.
9471 * // Avoid costly calculations while the window size is in flux.
9472 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
9474 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
9475 * jQuery(element).on('click', _.debounce(sendMail, 300, {
9480 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
9481 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
9482 * var source = new EventSource('/stream');
9483 * jQuery(source).on('message', debounced);
9485 * // Cancel the trailing debounced invocation.
9486 * jQuery(window).on('popstate', debounced.cancel);
9488 function debounce(func, wait, options) {
9500 if (typeof func != 'function') {
9501 throw new TypeError(FUNC_ERROR_TEXT);
9503 wait = toNumber(wait) || 0;
9504 if (isObject(options)) {
9505 leading = !!options.leading;
9506 maxing = 'maxWait' in options;
9507 maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
9508 trailing = 'trailing' in options ? !!options.trailing : trailing;
9511 function invokeFunc(time) {
9512 var args = lastArgs,
9515 lastArgs = lastThis = undefined;
9516 lastInvokeTime = time;
9517 result = func.apply(thisArg, args);
9521 function leadingEdge(time) {
9522 // Reset any `maxWait` timer.
9523 lastInvokeTime = time;
9524 // Start the timer for the trailing edge.
9525 timerId = setTimeout(timerExpired, wait);
9526 // Invoke the leading edge.
9527 return leading ? invokeFunc(time) : result;
9530 function remainingWait(time) {
9531 var timeSinceLastCall = time - lastCallTime,
9532 timeSinceLastInvoke = time - lastInvokeTime,
9533 result = wait - timeSinceLastCall;
9535 return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
9538 function shouldInvoke(time) {
9539 var timeSinceLastCall = time - lastCallTime,
9540 timeSinceLastInvoke = time - lastInvokeTime;
9542 // Either this is the first call, activity has stopped and we're at the
9543 // trailing edge, the system time has gone backwards and we're treating
9544 // it as the trailing edge, or we've hit the `maxWait` limit.
9545 return (!lastCallTime || (timeSinceLastCall >= wait) ||
9546 (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
9549 function timerExpired() {
9551 if (shouldInvoke(time)) {
9552 return trailingEdge(time);
9554 // Restart the timer.
9555 timerId = setTimeout(timerExpired, remainingWait(time));
9558 function trailingEdge(time) {
9559 clearTimeout(timerId);
9560 timerId = undefined;
9562 // Only invoke if we have `lastArgs` which means `func` has been
9563 // debounced at least once.
9564 if (trailing && lastArgs) {
9565 return invokeFunc(time);
9567 lastArgs = lastThis = undefined;
9572 if (timerId !== undefined) {
9573 clearTimeout(timerId);
9575 lastCallTime = lastInvokeTime = 0;
9576 lastArgs = lastThis = timerId = undefined;
9580 return timerId === undefined ? result : trailingEdge(now());
9583 function debounced() {
9585 isInvoking = shouldInvoke(time);
9587 lastArgs = arguments;
9589 lastCallTime = time;
9592 if (timerId === undefined) {
9593 return leadingEdge(lastCallTime);
9596 // Handle invocations in a tight loop.
9597 clearTimeout(timerId);
9598 timerId = setTimeout(timerExpired, wait);
9599 return invokeFunc(lastCallTime);
9602 if (timerId === undefined) {
9603 timerId = setTimeout(timerExpired, wait);
9607 debounced.cancel = cancel;
9608 debounced.flush = flush;
9613 * Defers invoking the `func` until the current call stack has cleared. Any
9614 * additional arguments are provided to `func` when it's invoked.
9619 * @category Function
9620 * @param {Function} func The function to defer.
9621 * @param {...*} [args] The arguments to invoke `func` with.
9622 * @returns {number} Returns the timer id.
9625 * _.defer(function(text) {
9626 * console.log(text);
9628 * // => Logs 'deferred' after one or more milliseconds.
9630 var defer = rest(function(func, args) {
9631 return baseDelay(func, 1, args);
9635 * Invokes `func` after `wait` milliseconds. Any additional arguments are
9636 * provided to `func` when it's invoked.
9641 * @category Function
9642 * @param {Function} func The function to delay.
9643 * @param {number} wait The number of milliseconds to delay invocation.
9644 * @param {...*} [args] The arguments to invoke `func` with.
9645 * @returns {number} Returns the timer id.
9648 * _.delay(function(text) {
9649 * console.log(text);
9650 * }, 1000, 'later');
9651 * // => Logs 'later' after one second.
9653 var delay = rest(function(func, wait, args) {
9654 return baseDelay(func, toNumber(wait) || 0, args);
9658 * Creates a function that invokes `func` with arguments reversed.
9663 * @category Function
9664 * @param {Function} func The function to flip arguments for.
9665 * @returns {Function} Returns the new function.
9668 * var flipped = _.flip(function() {
9669 * return _.toArray(arguments);
9672 * flipped('a', 'b', 'c', 'd');
9673 * // => ['d', 'c', 'b', 'a']
9675 function flip(func) {
9676 return createWrapper(func, FLIP_FLAG);
9680 * Creates a function that memoizes the result of `func`. If `resolver` is
9681 * provided, it determines the cache key for storing the result based on the
9682 * arguments provided to the memoized function. By default, the first argument
9683 * provided to the memoized function is used as the map cache key. The `func`
9684 * is invoked with the `this` binding of the memoized function.
9686 * **Note:** The cache is exposed as the `cache` property on the memoized
9687 * function. Its creation may be customized by replacing the `_.memoize.Cache`
9688 * constructor with one whose instances implement the
9689 * [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
9690 * method interface of `delete`, `get`, `has`, and `set`.
9695 * @category Function
9696 * @param {Function} func The function to have its output memoized.
9697 * @param {Function} [resolver] The function to resolve the cache key.
9698 * @returns {Function} Returns the new memoizing function.
9701 * var object = { 'a': 1, 'b': 2 };
9702 * var other = { 'c': 3, 'd': 4 };
9704 * var values = _.memoize(_.values);
9715 * // Modify the result cache.
9716 * values.cache.set(object, ['a', 'b']);
9720 * // Replace `_.memoize.Cache`.
9721 * _.memoize.Cache = WeakMap;
9723 function memoize(func, resolver) {
9724 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
9725 throw new TypeError(FUNC_ERROR_TEXT);
9727 var memoized = function() {
9728 var args = arguments,
9729 key = resolver ? resolver.apply(this, args) : args[0],
9730 cache = memoized.cache;
9732 if (cache.has(key)) {
9733 return cache.get(key);
9735 var result = func.apply(this, args);
9736 memoized.cache = cache.set(key, result);
9739 memoized.cache = new (memoize.Cache || MapCache);
9743 // Assign cache to `_.memoize`.
9744 memoize.Cache = MapCache;
9747 * Creates a function that negates the result of the predicate `func`. The
9748 * `func` predicate is invoked with the `this` binding and arguments of the
9754 * @category Function
9755 * @param {Function} predicate The predicate to negate.
9756 * @returns {Function} Returns the new function.
9759 * function isEven(n) {
9760 * return n % 2 == 0;
9763 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
9766 function negate(predicate) {
9767 if (typeof predicate != 'function') {
9768 throw new TypeError(FUNC_ERROR_TEXT);
9771 return !predicate.apply(this, arguments);
9776 * Creates a function that is restricted to invoking `func` once. Repeat calls
9777 * to the function return the value of the first invocation. The `func` is
9778 * invoked with the `this` binding and arguments of the created function.
9783 * @category Function
9784 * @param {Function} func The function to restrict.
9785 * @returns {Function} Returns the new restricted function.
9788 * var initialize = _.once(createApplication);
9791 * // `initialize` invokes `createApplication` once
9793 function once(func) {
9794 return before(2, func);
9798 * Creates a function that invokes `func` with arguments transformed by
9799 * corresponding `transforms`.
9804 * @category Function
9805 * @param {Function} func The function to wrap.
9806 * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])}
9807 * [transforms[_.identity]] The functions to transform.
9808 * @returns {Function} Returns the new function.
9811 * function doubled(n) {
9815 * function square(n) {
9819 * var func = _.overArgs(function(x, y) {
9821 * }, square, doubled);
9829 var overArgs = rest(function(func, transforms) {
9830 transforms = (transforms.length == 1 && isArray(transforms[0]))
9831 ? arrayMap(transforms[0], baseUnary(getIteratee()))
9832 : arrayMap(baseFlatten(transforms, 1, isFlattenableIteratee), baseUnary(getIteratee()));
9834 var funcsLength = transforms.length;
9835 return rest(function(args) {
9837 length = nativeMin(args.length, funcsLength);
9839 while (++index < length) {
9840 args[index] = transforms[index].call(this, args[index]);
9842 return apply(func, this, args);
9847 * Creates a function that invokes `func` with `partials` prepended to the
9848 * arguments it receives. This method is like `_.bind` except it does **not**
9849 * alter the `this` binding.
9851 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
9852 * builds, may be used as a placeholder for partially applied arguments.
9854 * **Note:** This method doesn't set the "length" property of partially
9855 * applied functions.
9860 * @category Function
9861 * @param {Function} func The function to partially apply arguments to.
9862 * @param {...*} [partials] The arguments to be partially applied.
9863 * @returns {Function} Returns the new partially applied function.
9866 * var greet = function(greeting, name) {
9867 * return greeting + ' ' + name;
9870 * var sayHelloTo = _.partial(greet, 'hello');
9871 * sayHelloTo('fred');
9872 * // => 'hello fred'
9874 * // Partially applied with placeholders.
9875 * var greetFred = _.partial(greet, _, 'fred');
9879 var partial = rest(function(func, partials) {
9880 var holders = replaceHolders(partials, getPlaceholder(partial));
9881 return createWrapper(func, PARTIAL_FLAG, undefined, partials, holders);
9885 * This method is like `_.partial` except that partially applied arguments
9886 * are appended to the arguments it receives.
9888 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
9889 * builds, may be used as a placeholder for partially applied arguments.
9891 * **Note:** This method doesn't set the "length" property of partially
9892 * applied functions.
9897 * @category Function
9898 * @param {Function} func The function to partially apply arguments to.
9899 * @param {...*} [partials] The arguments to be partially applied.
9900 * @returns {Function} Returns the new partially applied function.
9903 * var greet = function(greeting, name) {
9904 * return greeting + ' ' + name;
9907 * var greetFred = _.partialRight(greet, 'fred');
9911 * // Partially applied with placeholders.
9912 * var sayHelloTo = _.partialRight(greet, 'hello', _);
9913 * sayHelloTo('fred');
9914 * // => 'hello fred'
9916 var partialRight = rest(function(func, partials) {
9917 var holders = replaceHolders(partials, getPlaceholder(partialRight));
9918 return createWrapper(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders);
9922 * Creates a function that invokes `func` with arguments arranged according
9923 * to the specified `indexes` where the argument value at the first index is
9924 * provided as the first argument, the argument value at the second index is
9925 * provided as the second argument, and so on.
9930 * @category Function
9931 * @param {Function} func The function to rearrange arguments for.
9932 * @param {...(number|number[])} indexes The arranged argument indexes.
9933 * @returns {Function} Returns the new function.
9936 * var rearged = _.rearg(function(a, b, c) {
9940 * rearged('b', 'c', 'a')
9941 * // => ['a', 'b', 'c']
9943 var rearg = rest(function(func, indexes) {
9944 return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes, 1));
9948 * Creates a function that invokes `func` with the `this` binding of the
9949 * created function and arguments from `start` and beyond provided as
9952 * **Note:** This method is based on the
9953 * [rest parameter](https://mdn.io/rest_parameters).
9958 * @category Function
9959 * @param {Function} func The function to apply a rest parameter to.
9960 * @param {number} [start=func.length-1] The start position of the rest parameter.
9961 * @returns {Function} Returns the new function.
9964 * var say = _.rest(function(what, names) {
9965 * return what + ' ' + _.initial(names).join(', ') +
9966 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
9969 * say('hello', 'fred', 'barney', 'pebbles');
9970 * // => 'hello fred, barney, & pebbles'
9972 function rest(func, start) {
9973 if (typeof func != 'function') {
9974 throw new TypeError(FUNC_ERROR_TEXT);
9976 start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0);
9978 var args = arguments,
9980 length = nativeMax(args.length - start, 0),
9981 array = Array(length);
9983 while (++index < length) {
9984 array[index] = args[start + index];
9987 case 0: return func.call(this, array);
9988 case 1: return func.call(this, args[0], array);
9989 case 2: return func.call(this, args[0], args[1], array);
9991 var otherArgs = Array(start + 1);
9993 while (++index < start) {
9994 otherArgs[index] = args[index];
9996 otherArgs[start] = array;
9997 return apply(func, this, otherArgs);
10002 * Creates a function that invokes `func` with the `this` binding of the
10003 * create function and an array of arguments much like
10004 * [`Function#apply`](http://www.ecma-international.org/ecma-262/6.0/#sec-function.prototype.apply).
10006 * **Note:** This method is based on the
10007 * [spread operator](https://mdn.io/spread_operator).
10012 * @category Function
10013 * @param {Function} func The function to spread arguments over.
10014 * @param {number} [start=0] The start position of the spread.
10015 * @returns {Function} Returns the new function.
10018 * var say = _.spread(function(who, what) {
10019 * return who + ' says ' + what;
10022 * say(['fred', 'hello']);
10023 * // => 'fred says hello'
10025 * var numbers = Promise.all([
10026 * Promise.resolve(40),
10027 * Promise.resolve(36)
10030 * numbers.then(_.spread(function(x, y) {
10033 * // => a Promise of 76
10035 function spread(func, start) {
10036 if (typeof func != 'function') {
10037 throw new TypeError(FUNC_ERROR_TEXT);
10039 start = start === undefined ? 0 : nativeMax(toInteger(start), 0);
10040 return rest(function(args) {
10041 var array = args[start],
10042 otherArgs = castSlice(args, 0, start);
10045 arrayPush(otherArgs, array);
10047 return apply(func, this, otherArgs);
10052 * Creates a throttled function that only invokes `func` at most once per
10053 * every `wait` milliseconds. The throttled function comes with a `cancel`
10054 * method to cancel delayed `func` invocations and a `flush` method to
10055 * immediately invoke them. Provide an options object to indicate whether
10056 * `func` should be invoked on the leading and/or trailing edge of the `wait`
10057 * timeout. The `func` is invoked with the last arguments provided to the
10058 * throttled function. Subsequent calls to the throttled function return the
10059 * result of the last `func` invocation.
10061 * **Note:** If `leading` and `trailing` options are `true`, `func` is
10062 * invoked on the trailing edge of the timeout only if the throttled function
10063 * is invoked more than once during the `wait` timeout.
10065 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
10066 * for details over the differences between `_.throttle` and `_.debounce`.
10071 * @category Function
10072 * @param {Function} func The function to throttle.
10073 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
10074 * @param {Object} [options={}] The options object.
10075 * @param {boolean} [options.leading=true]
10076 * Specify invoking on the leading edge of the timeout.
10077 * @param {boolean} [options.trailing=true]
10078 * Specify invoking on the trailing edge of the timeout.
10079 * @returns {Function} Returns the new throttled function.
10082 * // Avoid excessively updating the position while scrolling.
10083 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
10085 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
10086 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
10087 * jQuery(element).on('click', throttled);
10089 * // Cancel the trailing throttled invocation.
10090 * jQuery(window).on('popstate', throttled.cancel);
10092 function throttle(func, wait, options) {
10093 var leading = true,
10096 if (typeof func != 'function') {
10097 throw new TypeError(FUNC_ERROR_TEXT);
10099 if (isObject(options)) {
10100 leading = 'leading' in options ? !!options.leading : leading;
10101 trailing = 'trailing' in options ? !!options.trailing : trailing;
10103 return debounce(func, wait, {
10104 'leading': leading,
10106 'trailing': trailing
10111 * Creates a function that accepts up to one argument, ignoring any
10112 * additional arguments.
10117 * @category Function
10118 * @param {Function} func The function to cap arguments for.
10119 * @returns {Function} Returns the new function.
10122 * _.map(['6', '8', '10'], _.unary(parseInt));
10125 function unary(func) {
10126 return ary(func, 1);
10130 * Creates a function that provides `value` to the wrapper function as its
10131 * first argument. Any additional arguments provided to the function are
10132 * appended to those provided to the wrapper function. The wrapper is invoked
10133 * with the `this` binding of the created function.
10138 * @category Function
10139 * @param {*} value The value to wrap.
10140 * @param {Function} [wrapper=identity] The wrapper function.
10141 * @returns {Function} Returns the new function.
10144 * var p = _.wrap(_.escape, function(func, text) {
10145 * return '<p>' + func(text) + '</p>';
10148 * p('fred, barney, & pebbles');
10149 * // => '<p>fred, barney, & pebbles</p>'
10151 function wrap(value, wrapper) {
10152 wrapper = wrapper == null ? identity : wrapper;
10153 return partial(wrapper, value);
10156 /*------------------------------------------------------------------------*/
10159 * Casts `value` as an array if it's not one.
10165 * @param {*} value The value to inspect.
10166 * @returns {Array} Returns the cast array.
10172 * _.castArray({ 'a': 1 });
10173 * // => [{ 'a': 1 }]
10175 * _.castArray('abc');
10178 * _.castArray(null);
10181 * _.castArray(undefined);
10182 * // => [undefined]
10187 * var array = [1, 2, 3];
10188 * console.log(_.castArray(array) === array);
10191 function castArray() {
10192 if (!arguments.length) {
10195 var value = arguments[0];
10196 return isArray(value) ? value : [value];
10200 * Creates a shallow clone of `value`.
10202 * **Note:** This method is loosely based on the
10203 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
10204 * and supports cloning arrays, array buffers, booleans, date objects, maps,
10205 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
10206 * arrays. The own enumerable properties of `arguments` objects are cloned
10207 * as plain objects. An empty object is returned for uncloneable values such
10208 * as error objects, functions, DOM nodes, and WeakMaps.
10214 * @param {*} value The value to clone.
10215 * @returns {*} Returns the cloned value.
10219 * var objects = [{ 'a': 1 }, { 'b': 2 }];
10221 * var shallow = _.clone(objects);
10222 * console.log(shallow[0] === objects[0]);
10225 function clone(value) {
10226 return baseClone(value, false, true);
10230 * This method is like `_.clone` except that it accepts `customizer` which
10231 * is invoked to produce the cloned value. If `customizer` returns `undefined`,
10232 * cloning is handled by the method instead. The `customizer` is invoked with
10233 * up to four arguments; (value [, index|key, object, stack]).
10239 * @param {*} value The value to clone.
10240 * @param {Function} [customizer] The function to customize cloning.
10241 * @returns {*} Returns the cloned value.
10242 * @see _.cloneDeepWith
10245 * function customizer(value) {
10246 * if (_.isElement(value)) {
10247 * return value.cloneNode(false);
10251 * var el = _.cloneWith(document.body, customizer);
10253 * console.log(el === document.body);
10255 * console.log(el.nodeName);
10257 * console.log(el.childNodes.length);
10260 function cloneWith(value, customizer) {
10261 return baseClone(value, false, true, customizer);
10265 * This method is like `_.clone` except that it recursively clones `value`.
10271 * @param {*} value The value to recursively clone.
10272 * @returns {*} Returns the deep cloned value.
10276 * var objects = [{ 'a': 1 }, { 'b': 2 }];
10278 * var deep = _.cloneDeep(objects);
10279 * console.log(deep[0] === objects[0]);
10282 function cloneDeep(value) {
10283 return baseClone(value, true, true);
10287 * This method is like `_.cloneWith` except that it recursively clones `value`.
10293 * @param {*} value The value to recursively clone.
10294 * @param {Function} [customizer] The function to customize cloning.
10295 * @returns {*} Returns the deep cloned value.
10299 * function customizer(value) {
10300 * if (_.isElement(value)) {
10301 * return value.cloneNode(true);
10305 * var el = _.cloneDeepWith(document.body, customizer);
10307 * console.log(el === document.body);
10309 * console.log(el.nodeName);
10311 * console.log(el.childNodes.length);
10314 function cloneDeepWith(value, customizer) {
10315 return baseClone(value, true, true, customizer);
10320 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
10321 * comparison between two values to determine if they are equivalent.
10327 * @param {*} value The value to compare.
10328 * @param {*} other The other value to compare.
10329 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
10332 * var object = { 'user': 'fred' };
10333 * var other = { 'user': 'fred' };
10335 * _.eq(object, object);
10338 * _.eq(object, other);
10344 * _.eq('a', Object('a'));
10350 function eq(value, other) {
10351 return value === other || (value !== value && other !== other);
10355 * Checks if `value` is greater than `other`.
10361 * @param {*} value The value to compare.
10362 * @param {*} other The other value to compare.
10363 * @returns {boolean} Returns `true` if `value` is greater than `other`,
10377 var gt = createRelationalOperation(baseGt);
10380 * Checks if `value` is greater than or equal to `other`.
10386 * @param {*} value The value to compare.
10387 * @param {*} other The other value to compare.
10388 * @returns {boolean} Returns `true` if `value` is greater than or equal to
10389 * `other`, else `false`.
10402 var gte = createRelationalOperation(function(value, other) {
10403 return value >= other;
10407 * Checks if `value` is likely an `arguments` object.
10413 * @param {*} value The value to check.
10414 * @returns {boolean} Returns `true` if `value` is correctly classified,
10418 * _.isArguments(function() { return arguments; }());
10421 * _.isArguments([1, 2, 3]);
10424 function isArguments(value) {
10425 // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
10426 return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
10427 (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
10431 * Checks if `value` is classified as an `Array` object.
10438 * @param {*} value The value to check.
10439 * @returns {boolean} Returns `true` if `value` is correctly classified,
10443 * _.isArray([1, 2, 3]);
10446 * _.isArray(document.body.children);
10449 * _.isArray('abc');
10452 * _.isArray(_.noop);
10455 var isArray = Array.isArray;
10458 * Checks if `value` is classified as an `ArrayBuffer` object.
10464 * @param {*} value The value to check.
10465 * @returns {boolean} Returns `true` if `value` is correctly classified,
10469 * _.isArrayBuffer(new ArrayBuffer(2));
10472 * _.isArrayBuffer(new Array(2));
10475 function isArrayBuffer(value) {
10476 return isObjectLike(value) && objectToString.call(value) == arrayBufferTag;
10480 * Checks if `value` is array-like. A value is considered array-like if it's
10481 * not a function and has a `value.length` that's an integer greater than or
10482 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
10488 * @param {*} value The value to check.
10489 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
10492 * _.isArrayLike([1, 2, 3]);
10495 * _.isArrayLike(document.body.children);
10498 * _.isArrayLike('abc');
10501 * _.isArrayLike(_.noop);
10504 function isArrayLike(value) {
10505 return value != null && isLength(getLength(value)) && !isFunction(value);
10509 * This method is like `_.isArrayLike` except that it also checks if `value`
10516 * @param {*} value The value to check.
10517 * @returns {boolean} Returns `true` if `value` is an array-like object,
10521 * _.isArrayLikeObject([1, 2, 3]);
10524 * _.isArrayLikeObject(document.body.children);
10527 * _.isArrayLikeObject('abc');
10530 * _.isArrayLikeObject(_.noop);
10533 function isArrayLikeObject(value) {
10534 return isObjectLike(value) && isArrayLike(value);
10538 * Checks if `value` is classified as a boolean primitive or object.
10544 * @param {*} value The value to check.
10545 * @returns {boolean} Returns `true` if `value` is correctly classified,
10549 * _.isBoolean(false);
10552 * _.isBoolean(null);
10555 function isBoolean(value) {
10556 return value === true || value === false ||
10557 (isObjectLike(value) && objectToString.call(value) == boolTag);
10561 * Checks if `value` is a buffer.
10567 * @param {*} value The value to check.
10568 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
10571 * _.isBuffer(new Buffer(2));
10574 * _.isBuffer(new Uint8Array(2));
10577 var isBuffer = !Buffer ? constant(false) : function(value) {
10578 return value instanceof Buffer;
10582 * Checks if `value` is classified as a `Date` object.
10588 * @param {*} value The value to check.
10589 * @returns {boolean} Returns `true` if `value` is correctly classified,
10593 * _.isDate(new Date);
10596 * _.isDate('Mon April 23 2012');
10599 function isDate(value) {
10600 return isObjectLike(value) && objectToString.call(value) == dateTag;
10604 * Checks if `value` is likely a DOM element.
10610 * @param {*} value The value to check.
10611 * @returns {boolean} Returns `true` if `value` is a DOM element,
10615 * _.isElement(document.body);
10618 * _.isElement('<body>');
10621 function isElement(value) {
10622 return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
10626 * Checks if `value` is an empty object, collection, map, or set.
10628 * Objects are considered empty if they have no own enumerable string keyed
10631 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
10632 * jQuery-like collections are considered empty if they have a `length` of `0`.
10633 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
10639 * @param {*} value The value to check.
10640 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
10652 * _.isEmpty([1, 2, 3]);
10655 * _.isEmpty({ 'a': 1 });
10658 function isEmpty(value) {
10659 if (isArrayLike(value) &&
10660 (isArray(value) || isString(value) || isFunction(value.splice) ||
10661 isArguments(value) || isBuffer(value))) {
10662 return !value.length;
10664 if (isObjectLike(value)) {
10665 var tag = getTag(value);
10666 if (tag == mapTag || tag == setTag) {
10667 return !value.size;
10670 for (var key in value) {
10671 if (hasOwnProperty.call(value, key)) {
10675 return !(nonEnumShadows && keys(value).length);
10679 * Performs a deep comparison between two values to determine if they are
10682 * **Note:** This method supports comparing arrays, array buffers, booleans,
10683 * date objects, error objects, maps, numbers, `Object` objects, regexes,
10684 * sets, strings, symbols, and typed arrays. `Object` objects are compared
10685 * by their own, not inherited, enumerable properties. Functions and DOM
10686 * nodes are **not** supported.
10692 * @param {*} value The value to compare.
10693 * @param {*} other The other value to compare.
10694 * @returns {boolean} Returns `true` if the values are equivalent,
10698 * var object = { 'user': 'fred' };
10699 * var other = { 'user': 'fred' };
10701 * _.isEqual(object, other);
10704 * object === other;
10707 function isEqual(value, other) {
10708 return baseIsEqual(value, other);
10712 * This method is like `_.isEqual` except that it accepts `customizer` which
10713 * is invoked to compare values. If `customizer` returns `undefined`, comparisons
10714 * are handled by the method instead. The `customizer` is invoked with up to
10715 * six arguments: (objValue, othValue [, index|key, object, other, stack]).
10721 * @param {*} value The value to compare.
10722 * @param {*} other The other value to compare.
10723 * @param {Function} [customizer] The function to customize comparisons.
10724 * @returns {boolean} Returns `true` if the values are equivalent,
10728 * function isGreeting(value) {
10729 * return /^h(?:i|ello)$/.test(value);
10732 * function customizer(objValue, othValue) {
10733 * if (isGreeting(objValue) && isGreeting(othValue)) {
10738 * var array = ['hello', 'goodbye'];
10739 * var other = ['hi', 'goodbye'];
10741 * _.isEqualWith(array, other, customizer);
10744 function isEqualWith(value, other, customizer) {
10745 customizer = typeof customizer == 'function' ? customizer : undefined;
10746 var result = customizer ? customizer(value, other) : undefined;
10747 return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
10751 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
10752 * `SyntaxError`, `TypeError`, or `URIError` object.
10758 * @param {*} value The value to check.
10759 * @returns {boolean} Returns `true` if `value` is an error object,
10763 * _.isError(new Error);
10766 * _.isError(Error);
10769 function isError(value) {
10770 if (!isObjectLike(value)) {
10773 return (objectToString.call(value) == errorTag) ||
10774 (typeof value.message == 'string' && typeof value.name == 'string');
10778 * Checks if `value` is a finite primitive number.
10780 * **Note:** This method is based on
10781 * [`Number.isFinite`](https://mdn.io/Number/isFinite).
10787 * @param {*} value The value to check.
10788 * @returns {boolean} Returns `true` if `value` is a finite number,
10795 * _.isFinite(Number.MAX_VALUE);
10798 * _.isFinite(3.14);
10801 * _.isFinite(Infinity);
10804 function isFinite(value) {
10805 return typeof value == 'number' && nativeIsFinite(value);
10809 * Checks if `value` is classified as a `Function` object.
10815 * @param {*} value The value to check.
10816 * @returns {boolean} Returns `true` if `value` is correctly classified,
10823 * _.isFunction(/abc/);
10826 function isFunction(value) {
10827 // The use of `Object#toString` avoids issues with the `typeof` operator
10828 // in Safari 8 which returns 'object' for typed array and weak map constructors,
10829 // and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
10830 var tag = isObject(value) ? objectToString.call(value) : '';
10831 return tag == funcTag || tag == genTag;
10835 * Checks if `value` is an integer.
10837 * **Note:** This method is based on
10838 * [`Number.isInteger`](https://mdn.io/Number/isInteger).
10844 * @param {*} value The value to check.
10845 * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
10851 * _.isInteger(Number.MIN_VALUE);
10854 * _.isInteger(Infinity);
10857 * _.isInteger('3');
10860 function isInteger(value) {
10861 return typeof value == 'number' && value == toInteger(value);
10865 * Checks if `value` is a valid array-like length.
10867 * **Note:** This function is loosely based on
10868 * [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
10874 * @param {*} value The value to check.
10875 * @returns {boolean} Returns `true` if `value` is a valid length,
10882 * _.isLength(Number.MIN_VALUE);
10885 * _.isLength(Infinity);
10891 function isLength(value) {
10892 return typeof value == 'number' &&
10893 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
10897 * Checks if `value` is the
10898 * [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types)
10899 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
10905 * @param {*} value The value to check.
10906 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
10912 * _.isObject([1, 2, 3]);
10915 * _.isObject(_.noop);
10918 * _.isObject(null);
10921 function isObject(value) {
10922 var type = typeof value;
10923 return !!value && (type == 'object' || type == 'function');
10927 * Checks if `value` is object-like. A value is object-like if it's not `null`
10928 * and has a `typeof` result of "object".
10934 * @param {*} value The value to check.
10935 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
10938 * _.isObjectLike({});
10941 * _.isObjectLike([1, 2, 3]);
10944 * _.isObjectLike(_.noop);
10947 * _.isObjectLike(null);
10950 function isObjectLike(value) {
10951 return !!value && typeof value == 'object';
10955 * Checks if `value` is classified as a `Map` object.
10961 * @param {*} value The value to check.
10962 * @returns {boolean} Returns `true` if `value` is correctly classified,
10966 * _.isMap(new Map);
10969 * _.isMap(new WeakMap);
10972 function isMap(value) {
10973 return isObjectLike(value) && getTag(value) == mapTag;
10977 * Performs a partial deep comparison between `object` and `source` to
10978 * determine if `object` contains equivalent property values. This method is
10979 * equivalent to a `_.matches` function when `source` is partially applied.
10981 * **Note:** This method supports comparing the same values as `_.isEqual`.
10987 * @param {Object} object The object to inspect.
10988 * @param {Object} source The object of property values to match.
10989 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
10992 * var object = { 'user': 'fred', 'age': 40 };
10994 * _.isMatch(object, { 'age': 40 });
10997 * _.isMatch(object, { 'age': 36 });
11000 function isMatch(object, source) {
11001 return object === source || baseIsMatch(object, source, getMatchData(source));
11005 * This method is like `_.isMatch` except that it accepts `customizer` which
11006 * is invoked to compare values. If `customizer` returns `undefined`, comparisons
11007 * are handled by the method instead. The `customizer` is invoked with five
11008 * arguments: (objValue, srcValue, index|key, object, source).
11014 * @param {Object} object The object to inspect.
11015 * @param {Object} source The object of property values to match.
11016 * @param {Function} [customizer] The function to customize comparisons.
11017 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
11020 * function isGreeting(value) {
11021 * return /^h(?:i|ello)$/.test(value);
11024 * function customizer(objValue, srcValue) {
11025 * if (isGreeting(objValue) && isGreeting(srcValue)) {
11030 * var object = { 'greeting': 'hello' };
11031 * var source = { 'greeting': 'hi' };
11033 * _.isMatchWith(object, source, customizer);
11036 function isMatchWith(object, source, customizer) {
11037 customizer = typeof customizer == 'function' ? customizer : undefined;
11038 return baseIsMatch(object, source, getMatchData(source), customizer);
11042 * Checks if `value` is `NaN`.
11044 * **Note:** This method is based on
11045 * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
11046 * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
11047 * `undefined` and other non-number values.
11053 * @param {*} value The value to check.
11054 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
11060 * _.isNaN(new Number(NaN));
11063 * isNaN(undefined);
11066 * _.isNaN(undefined);
11069 function isNaN(value) {
11070 // An `NaN` primitive is the only value that is not equal to itself.
11071 // Perform the `toStringTag` check first to avoid errors with some
11072 // ActiveX objects in IE.
11073 return isNumber(value) && value != +value;
11077 * Checks if `value` is a native function.
11083 * @param {*} value The value to check.
11084 * @returns {boolean} Returns `true` if `value` is a native function,
11088 * _.isNative(Array.prototype.push);
11094 function isNative(value) {
11095 if (!isObject(value)) {
11098 var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
11099 return pattern.test(toSource(value));
11103 * Checks if `value` is `null`.
11109 * @param {*} value The value to check.
11110 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
11116 * _.isNull(void 0);
11119 function isNull(value) {
11120 return value === null;
11124 * Checks if `value` is `null` or `undefined`.
11130 * @param {*} value The value to check.
11131 * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
11143 function isNil(value) {
11144 return value == null;
11148 * Checks if `value` is classified as a `Number` primitive or object.
11150 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
11151 * classified as numbers, use the `_.isFinite` method.
11157 * @param {*} value The value to check.
11158 * @returns {boolean} Returns `true` if `value` is correctly classified,
11165 * _.isNumber(Number.MIN_VALUE);
11168 * _.isNumber(Infinity);
11174 function isNumber(value) {
11175 return typeof value == 'number' ||
11176 (isObjectLike(value) && objectToString.call(value) == numberTag);
11180 * Checks if `value` is a plain object, that is, an object created by the
11181 * `Object` constructor or one with a `[[Prototype]]` of `null`.
11187 * @param {*} value The value to check.
11188 * @returns {boolean} Returns `true` if `value` is a plain object,
11196 * _.isPlainObject(new Foo);
11199 * _.isPlainObject([1, 2, 3]);
11202 * _.isPlainObject({ 'x': 0, 'y': 0 });
11205 * _.isPlainObject(Object.create(null));
11208 function isPlainObject(value) {
11209 if (!isObjectLike(value) ||
11210 objectToString.call(value) != objectTag || isHostObject(value)) {
11213 var proto = getPrototype(value);
11214 if (proto === null) {
11217 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
11218 return (typeof Ctor == 'function' &&
11219 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
11223 * Checks if `value` is classified as a `RegExp` object.
11229 * @param {*} value The value to check.
11230 * @returns {boolean} Returns `true` if `value` is correctly classified,
11234 * _.isRegExp(/abc/);
11237 * _.isRegExp('/abc/');
11240 function isRegExp(value) {
11241 return isObject(value) && objectToString.call(value) == regexpTag;
11245 * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
11246 * double precision number which isn't the result of a rounded unsafe integer.
11248 * **Note:** This method is based on
11249 * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
11255 * @param {*} value The value to check.
11256 * @returns {boolean} Returns `true` if `value` is a safe integer,
11260 * _.isSafeInteger(3);
11263 * _.isSafeInteger(Number.MIN_VALUE);
11266 * _.isSafeInteger(Infinity);
11269 * _.isSafeInteger('3');
11272 function isSafeInteger(value) {
11273 return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
11277 * Checks if `value` is classified as a `Set` object.
11283 * @param {*} value The value to check.
11284 * @returns {boolean} Returns `true` if `value` is correctly classified,
11288 * _.isSet(new Set);
11291 * _.isSet(new WeakSet);
11294 function isSet(value) {
11295 return isObjectLike(value) && getTag(value) == setTag;
11299 * Checks if `value` is classified as a `String` primitive or object.
11305 * @param {*} value The value to check.
11306 * @returns {boolean} Returns `true` if `value` is correctly classified,
11310 * _.isString('abc');
11316 function isString(value) {
11317 return typeof value == 'string' ||
11318 (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
11322 * Checks if `value` is classified as a `Symbol` primitive or object.
11328 * @param {*} value The value to check.
11329 * @returns {boolean} Returns `true` if `value` is correctly classified,
11333 * _.isSymbol(Symbol.iterator);
11336 * _.isSymbol('abc');
11339 function isSymbol(value) {
11340 return typeof value == 'symbol' ||
11341 (isObjectLike(value) && objectToString.call(value) == symbolTag);
11345 * Checks if `value` is classified as a typed array.
11351 * @param {*} value The value to check.
11352 * @returns {boolean} Returns `true` if `value` is correctly classified,
11356 * _.isTypedArray(new Uint8Array);
11359 * _.isTypedArray([]);
11362 function isTypedArray(value) {
11363 return isObjectLike(value) &&
11364 isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
11368 * Checks if `value` is `undefined`.
11374 * @param {*} value The value to check.
11375 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
11378 * _.isUndefined(void 0);
11381 * _.isUndefined(null);
11384 function isUndefined(value) {
11385 return value === undefined;
11389 * Checks if `value` is classified as a `WeakMap` object.
11395 * @param {*} value The value to check.
11396 * @returns {boolean} Returns `true` if `value` is correctly classified,
11400 * _.isWeakMap(new WeakMap);
11403 * _.isWeakMap(new Map);
11406 function isWeakMap(value) {
11407 return isObjectLike(value) && getTag(value) == weakMapTag;
11411 * Checks if `value` is classified as a `WeakSet` object.
11417 * @param {*} value The value to check.
11418 * @returns {boolean} Returns `true` if `value` is correctly classified,
11422 * _.isWeakSet(new WeakSet);
11425 * _.isWeakSet(new Set);
11428 function isWeakSet(value) {
11429 return isObjectLike(value) && objectToString.call(value) == weakSetTag;
11433 * Checks if `value` is less than `other`.
11439 * @param {*} value The value to compare.
11440 * @param {*} other The other value to compare.
11441 * @returns {boolean} Returns `true` if `value` is less than `other`,
11455 var lt = createRelationalOperation(baseLt);
11458 * Checks if `value` is less than or equal to `other`.
11464 * @param {*} value The value to compare.
11465 * @param {*} other The other value to compare.
11466 * @returns {boolean} Returns `true` if `value` is less than or equal to
11467 * `other`, else `false`.
11480 var lte = createRelationalOperation(function(value, other) {
11481 return value <= other;
11485 * Converts `value` to an array.
11491 * @param {*} value The value to convert.
11492 * @returns {Array} Returns the converted array.
11495 * _.toArray({ 'a': 1, 'b': 2 });
11498 * _.toArray('abc');
11499 * // => ['a', 'b', 'c']
11507 function toArray(value) {
11511 if (isArrayLike(value)) {
11512 return isString(value) ? stringToArray(value) : copyArray(value);
11514 if (iteratorSymbol && value[iteratorSymbol]) {
11515 return iteratorToArray(value[iteratorSymbol]());
11517 var tag = getTag(value),
11518 func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
11520 return func(value);
11524 * Converts `value` to an integer.
11526 * **Note:** This function is loosely based on
11527 * [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger).
11533 * @param {*} value The value to convert.
11534 * @returns {number} Returns the converted integer.
11540 * _.toInteger(Number.MIN_VALUE);
11543 * _.toInteger(Infinity);
11544 * // => 1.7976931348623157e+308
11546 * _.toInteger('3');
11549 function toInteger(value) {
11551 return value === 0 ? value : 0;
11553 value = toNumber(value);
11554 if (value === INFINITY || value === -INFINITY) {
11555 var sign = (value < 0 ? -1 : 1);
11556 return sign * MAX_INTEGER;
11558 var remainder = value % 1;
11559 return value === value ? (remainder ? value - remainder : value) : 0;
11563 * Converts `value` to an integer suitable for use as the length of an
11564 * array-like object.
11566 * **Note:** This method is based on
11567 * [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
11573 * @param {*} value The value to convert.
11574 * @returns {number} Returns the converted integer.
11580 * _.toLength(Number.MIN_VALUE);
11583 * _.toLength(Infinity);
11589 function toLength(value) {
11590 return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
11594 * Converts `value` to a number.
11600 * @param {*} value The value to process.
11601 * @returns {number} Returns the number.
11607 * _.toNumber(Number.MIN_VALUE);
11610 * _.toNumber(Infinity);
11616 function toNumber(value) {
11617 if (typeof value == 'number') {
11620 if (isSymbol(value)) {
11623 if (isObject(value)) {
11624 var other = isFunction(value.valueOf) ? value.valueOf() : value;
11625 value = isObject(other) ? (other + '') : other;
11627 if (typeof value != 'string') {
11628 return value === 0 ? value : +value;
11630 value = value.replace(reTrim, '');
11631 var isBinary = reIsBinary.test(value);
11632 return (isBinary || reIsOctal.test(value))
11633 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
11634 : (reIsBadHex.test(value) ? NAN : +value);
11638 * Converts `value` to a plain object flattening inherited enumerable string
11639 * keyed properties of `value` to own properties of the plain object.
11645 * @param {*} value The value to convert.
11646 * @returns {Object} Returns the converted plain object.
11653 * Foo.prototype.c = 3;
11655 * _.assign({ 'a': 1 }, new Foo);
11656 * // => { 'a': 1, 'b': 2 }
11658 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
11659 * // => { 'a': 1, 'b': 2, 'c': 3 }
11661 function toPlainObject(value) {
11662 return copyObject(value, keysIn(value));
11666 * Converts `value` to a safe integer. A safe integer can be compared and
11667 * represented correctly.
11673 * @param {*} value The value to convert.
11674 * @returns {number} Returns the converted integer.
11677 * _.toSafeInteger(3);
11680 * _.toSafeInteger(Number.MIN_VALUE);
11683 * _.toSafeInteger(Infinity);
11684 * // => 9007199254740991
11686 * _.toSafeInteger('3');
11689 function toSafeInteger(value) {
11690 return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
11694 * Converts `value` to a string. An empty string is returned for `null`
11695 * and `undefined` values. The sign of `-0` is preserved.
11701 * @param {*} value The value to process.
11702 * @returns {string} Returns the string.
11705 * _.toString(null);
11711 * _.toString([1, 2, 3]);
11714 function toString(value) {
11715 return value == null ? '' : baseToString(value);
11718 /*------------------------------------------------------------------------*/
11721 * Assigns own enumerable string keyed properties of source objects to the
11722 * destination object. Source objects are applied from left to right.
11723 * Subsequent sources overwrite property assignments of previous sources.
11725 * **Note:** This method mutates `object` and is loosely based on
11726 * [`Object.assign`](https://mdn.io/Object/assign).
11732 * @param {Object} object The destination object.
11733 * @param {...Object} [sources] The source objects.
11734 * @returns {Object} Returns `object`.
11746 * Foo.prototype.d = 4;
11747 * Bar.prototype.f = 6;
11749 * _.assign({ 'a': 1 }, new Foo, new Bar);
11750 * // => { 'a': 1, 'c': 3, 'e': 5 }
11752 var assign = createAssigner(function(object, source) {
11753 if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) {
11754 copyObject(source, keys(source), object);
11757 for (var key in source) {
11758 if (hasOwnProperty.call(source, key)) {
11759 assignValue(object, key, source[key]);
11765 * This method is like `_.assign` except that it iterates over own and
11766 * inherited source properties.
11768 * **Note:** This method mutates `object`.
11775 * @param {Object} object The destination object.
11776 * @param {...Object} [sources] The source objects.
11777 * @returns {Object} Returns `object`.
11789 * Foo.prototype.c = 3;
11790 * Bar.prototype.e = 5;
11792 * _.assignIn({ 'a': 1 }, new Foo, new Bar);
11793 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }
11795 var assignIn = createAssigner(function(object, source) {
11796 if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) {
11797 copyObject(source, keysIn(source), object);
11800 for (var key in source) {
11801 assignValue(object, key, source[key]);
11806 * This method is like `_.assignIn` except that it accepts `customizer`
11807 * which is invoked to produce the assigned values. If `customizer` returns
11808 * `undefined`, assignment is handled by the method instead. The `customizer`
11809 * is invoked with five arguments: (objValue, srcValue, key, object, source).
11811 * **Note:** This method mutates `object`.
11816 * @alias extendWith
11818 * @param {Object} object The destination object.
11819 * @param {...Object} sources The source objects.
11820 * @param {Function} [customizer] The function to customize assigned values.
11821 * @returns {Object} Returns `object`.
11822 * @see _.assignWith
11825 * function customizer(objValue, srcValue) {
11826 * return _.isUndefined(objValue) ? srcValue : objValue;
11829 * var defaults = _.partialRight(_.assignInWith, customizer);
11831 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
11832 * // => { 'a': 1, 'b': 2 }
11834 var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
11835 copyObject(source, keysIn(source), object, customizer);
11839 * This method is like `_.assign` except that it accepts `customizer`
11840 * which is invoked to produce the assigned values. If `customizer` returns
11841 * `undefined`, assignment is handled by the method instead. The `customizer`
11842 * is invoked with five arguments: (objValue, srcValue, key, object, source).
11844 * **Note:** This method mutates `object`.
11850 * @param {Object} object The destination object.
11851 * @param {...Object} sources The source objects.
11852 * @param {Function} [customizer] The function to customize assigned values.
11853 * @returns {Object} Returns `object`.
11854 * @see _.assignInWith
11857 * function customizer(objValue, srcValue) {
11858 * return _.isUndefined(objValue) ? srcValue : objValue;
11861 * var defaults = _.partialRight(_.assignWith, customizer);
11863 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
11864 * // => { 'a': 1, 'b': 2 }
11866 var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
11867 copyObject(source, keys(source), object, customizer);
11871 * Creates an array of values corresponding to `paths` of `object`.
11877 * @param {Object} object The object to iterate over.
11878 * @param {...(string|string[])} [paths] The property paths of elements to pick.
11879 * @returns {Array} Returns the new array of picked elements.
11882 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
11884 * _.at(object, ['a[0].b.c', 'a[1]']);
11887 * _.at(['a', 'b', 'c'], 0, 2);
11890 var at = rest(function(object, paths) {
11891 return baseAt(object, baseFlatten(paths, 1));
11895 * Creates an object that inherits from the `prototype` object. If a
11896 * `properties` object is given, its own enumerable string keyed properties
11897 * are assigned to the created object.
11903 * @param {Object} prototype The object to inherit from.
11904 * @param {Object} [properties] The properties to assign to the object.
11905 * @returns {Object} Returns the new object.
11908 * function Shape() {
11913 * function Circle() {
11914 * Shape.call(this);
11917 * Circle.prototype = _.create(Shape.prototype, {
11918 * 'constructor': Circle
11921 * var circle = new Circle;
11922 * circle instanceof Circle;
11925 * circle instanceof Shape;
11928 function create(prototype, properties) {
11929 var result = baseCreate(prototype);
11930 return properties ? baseAssign(result, properties) : result;
11934 * Assigns own and inherited enumerable string keyed properties of source
11935 * objects to the destination object for all destination properties that
11936 * resolve to `undefined`. Source objects are applied from left to right.
11937 * Once a property is set, additional values of the same property are ignored.
11939 * **Note:** This method mutates `object`.
11945 * @param {Object} object The destination object.
11946 * @param {...Object} [sources] The source objects.
11947 * @returns {Object} Returns `object`.
11948 * @see _.defaultsDeep
11951 * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
11952 * // => { 'user': 'barney', 'age': 36 }
11954 var defaults = rest(function(args) {
11955 args.push(undefined, assignInDefaults);
11956 return apply(assignInWith, undefined, args);
11960 * This method is like `_.defaults` except that it recursively assigns
11961 * default properties.
11963 * **Note:** This method mutates `object`.
11969 * @param {Object} object The destination object.
11970 * @param {...Object} [sources] The source objects.
11971 * @returns {Object} Returns `object`.
11975 * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
11976 * // => { 'user': { 'name': 'barney', 'age': 36 } }
11979 var defaultsDeep = rest(function(args) {
11980 args.push(undefined, mergeDefaults);
11981 return apply(mergeWith, undefined, args);
11985 * This method is like `_.find` except that it returns the key of the first
11986 * element `predicate` returns truthy for instead of the element itself.
11992 * @param {Object} object The object to search.
11993 * @param {Array|Function|Object|string} [predicate=_.identity]
11994 * The function invoked per iteration.
11995 * @returns {string|undefined} Returns the key of the matched element,
11996 * else `undefined`.
12000 * 'barney': { 'age': 36, 'active': true },
12001 * 'fred': { 'age': 40, 'active': false },
12002 * 'pebbles': { 'age': 1, 'active': true }
12005 * _.findKey(users, function(o) { return o.age < 40; });
12006 * // => 'barney' (iteration order is not guaranteed)
12008 * // The `_.matches` iteratee shorthand.
12009 * _.findKey(users, { 'age': 1, 'active': true });
12012 * // The `_.matchesProperty` iteratee shorthand.
12013 * _.findKey(users, ['active', false]);
12016 * // The `_.property` iteratee shorthand.
12017 * _.findKey(users, 'active');
12020 function findKey(object, predicate) {
12021 return baseFind(object, getIteratee(predicate, 3), baseForOwn, true);
12025 * This method is like `_.findKey` except that it iterates over elements of
12026 * a collection in the opposite order.
12032 * @param {Object} object The object to search.
12033 * @param {Array|Function|Object|string} [predicate=_.identity]
12034 * The function invoked per iteration.
12035 * @returns {string|undefined} Returns the key of the matched element,
12036 * else `undefined`.
12040 * 'barney': { 'age': 36, 'active': true },
12041 * 'fred': { 'age': 40, 'active': false },
12042 * 'pebbles': { 'age': 1, 'active': true }
12045 * _.findLastKey(users, function(o) { return o.age < 40; });
12046 * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
12048 * // The `_.matches` iteratee shorthand.
12049 * _.findLastKey(users, { 'age': 36, 'active': true });
12052 * // The `_.matchesProperty` iteratee shorthand.
12053 * _.findLastKey(users, ['active', false]);
12056 * // The `_.property` iteratee shorthand.
12057 * _.findLastKey(users, 'active');
12060 function findLastKey(object, predicate) {
12061 return baseFind(object, getIteratee(predicate, 3), baseForOwnRight, true);
12065 * Iterates over own and inherited enumerable string keyed properties of an
12066 * object and invokes `iteratee` for each property. The iteratee is invoked
12067 * with three arguments: (value, key, object). Iteratee functions may exit
12068 * iteration early by explicitly returning `false`.
12074 * @param {Object} object The object to iterate over.
12075 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
12076 * @returns {Object} Returns `object`.
12077 * @see _.forInRight
12085 * Foo.prototype.c = 3;
12087 * _.forIn(new Foo, function(value, key) {
12088 * console.log(key);
12090 * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
12092 function forIn(object, iteratee) {
12093 return object == null
12095 : baseFor(object, getIteratee(iteratee), keysIn);
12099 * This method is like `_.forIn` except that it iterates over properties of
12100 * `object` in the opposite order.
12106 * @param {Object} object The object to iterate over.
12107 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
12108 * @returns {Object} Returns `object`.
12117 * Foo.prototype.c = 3;
12119 * _.forInRight(new Foo, function(value, key) {
12120 * console.log(key);
12122 * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
12124 function forInRight(object, iteratee) {
12125 return object == null
12127 : baseForRight(object, getIteratee(iteratee), keysIn);
12131 * Iterates over own enumerable string keyed properties of an object and
12132 * invokes `iteratee` for each property. The iteratee is invoked with three
12133 * arguments: (value, key, object). Iteratee functions may exit iteration
12134 * early by explicitly returning `false`.
12140 * @param {Object} object The object to iterate over.
12141 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
12142 * @returns {Object} Returns `object`.
12143 * @see _.forOwnRight
12151 * Foo.prototype.c = 3;
12153 * _.forOwn(new Foo, function(value, key) {
12154 * console.log(key);
12156 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
12158 function forOwn(object, iteratee) {
12159 return object && baseForOwn(object, getIteratee(iteratee));
12163 * This method is like `_.forOwn` except that it iterates over properties of
12164 * `object` in the opposite order.
12170 * @param {Object} object The object to iterate over.
12171 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
12172 * @returns {Object} Returns `object`.
12181 * Foo.prototype.c = 3;
12183 * _.forOwnRight(new Foo, function(value, key) {
12184 * console.log(key);
12186 * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
12188 function forOwnRight(object, iteratee) {
12189 return object && baseForOwnRight(object, getIteratee(iteratee));
12193 * Creates an array of function property names from own enumerable properties
12200 * @param {Object} object The object to inspect.
12201 * @returns {Array} Returns the new array of property names.
12202 * @see _.functionsIn
12206 * this.a = _.constant('a');
12207 * this.b = _.constant('b');
12210 * Foo.prototype.c = _.constant('c');
12212 * _.functions(new Foo);
12215 function functions(object) {
12216 return object == null ? [] : baseFunctions(object, keys(object));
12220 * Creates an array of function property names from own and inherited
12221 * enumerable properties of `object`.
12227 * @param {Object} object The object to inspect.
12228 * @returns {Array} Returns the new array of property names.
12233 * this.a = _.constant('a');
12234 * this.b = _.constant('b');
12237 * Foo.prototype.c = _.constant('c');
12239 * _.functionsIn(new Foo);
12240 * // => ['a', 'b', 'c']
12242 function functionsIn(object) {
12243 return object == null ? [] : baseFunctions(object, keysIn(object));
12247 * Gets the value at `path` of `object`. If the resolved value is
12248 * `undefined`, the `defaultValue` is used in its place.
12254 * @param {Object} object The object to query.
12255 * @param {Array|string} path The path of the property to get.
12256 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
12257 * @returns {*} Returns the resolved value.
12260 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
12262 * _.get(object, 'a[0].b.c');
12265 * _.get(object, ['a', '0', 'b', 'c']);
12268 * _.get(object, 'a.b.c', 'default');
12271 function get(object, path, defaultValue) {
12272 var result = object == null ? undefined : baseGet(object, path);
12273 return result === undefined ? defaultValue : result;
12277 * Checks if `path` is a direct property of `object`.
12283 * @param {Object} object The object to query.
12284 * @param {Array|string} path The path to check.
12285 * @returns {boolean} Returns `true` if `path` exists, else `false`.
12288 * var object = { 'a': { 'b': 2 } };
12289 * var other = _.create({ 'a': _.create({ 'b': 2 }) });
12291 * _.has(object, 'a');
12294 * _.has(object, 'a.b');
12297 * _.has(object, ['a', 'b']);
12300 * _.has(other, 'a');
12303 function has(object, path) {
12304 return object != null && hasPath(object, path, baseHas);
12308 * Checks if `path` is a direct or inherited property of `object`.
12314 * @param {Object} object The object to query.
12315 * @param {Array|string} path The path to check.
12316 * @returns {boolean} Returns `true` if `path` exists, else `false`.
12319 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
12321 * _.hasIn(object, 'a');
12324 * _.hasIn(object, 'a.b');
12327 * _.hasIn(object, ['a', 'b']);
12330 * _.hasIn(object, 'b');
12333 function hasIn(object, path) {
12334 return object != null && hasPath(object, path, baseHasIn);
12338 * Creates an object composed of the inverted keys and values of `object`.
12339 * If `object` contains duplicate values, subsequent values overwrite
12340 * property assignments of previous values.
12346 * @param {Object} object The object to invert.
12347 * @returns {Object} Returns the new inverted object.
12350 * var object = { 'a': 1, 'b': 2, 'c': 1 };
12352 * _.invert(object);
12353 * // => { '1': 'c', '2': 'b' }
12355 var invert = createInverter(function(result, value, key) {
12356 result[value] = key;
12357 }, constant(identity));
12360 * This method is like `_.invert` except that the inverted object is generated
12361 * from the results of running each element of `object` thru `iteratee`. The
12362 * corresponding inverted value of each inverted key is an array of keys
12363 * responsible for generating the inverted value. The iteratee is invoked
12364 * with one argument: (value).
12370 * @param {Object} object The object to invert.
12371 * @param {Array|Function|Object|string} [iteratee=_.identity]
12372 * The iteratee invoked per element.
12373 * @returns {Object} Returns the new inverted object.
12376 * var object = { 'a': 1, 'b': 2, 'c': 1 };
12378 * _.invertBy(object);
12379 * // => { '1': ['a', 'c'], '2': ['b'] }
12381 * _.invertBy(object, function(value) {
12382 * return 'group' + value;
12384 * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
12386 var invertBy = createInverter(function(result, value, key) {
12387 if (hasOwnProperty.call(result, value)) {
12388 result[value].push(key);
12390 result[value] = [key];
12395 * Invokes the method at `path` of `object`.
12401 * @param {Object} object The object to query.
12402 * @param {Array|string} path The path of the method to invoke.
12403 * @param {...*} [args] The arguments to invoke the method with.
12404 * @returns {*} Returns the result of the invoked method.
12407 * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
12409 * _.invoke(object, 'a[0].b.c.slice', 1, 3);
12412 var invoke = rest(baseInvoke);
12415 * Creates an array of the own enumerable property names of `object`.
12417 * **Note:** Non-object values are coerced to objects. See the
12418 * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
12419 * for more details.
12425 * @param {Object} object The object to query.
12426 * @returns {Array} Returns the array of property names.
12434 * Foo.prototype.c = 3;
12437 * // => ['a', 'b'] (iteration order is not guaranteed)
12442 function keys(object) {
12443 var isProto = isPrototype(object);
12444 if (!(isProto || isArrayLike(object))) {
12445 return baseKeys(object);
12447 var indexes = indexKeys(object),
12448 skipIndexes = !!indexes,
12449 result = indexes || [],
12450 length = result.length;
12452 for (var key in object) {
12453 if (baseHas(object, key) &&
12454 !(skipIndexes && (key == 'length' || isIndex(key, length))) &&
12455 !(isProto && key == 'constructor')) {
12463 * Creates an array of the own and inherited enumerable property names of `object`.
12465 * **Note:** Non-object values are coerced to objects.
12471 * @param {Object} object The object to query.
12472 * @returns {Array} Returns the array of property names.
12480 * Foo.prototype.c = 3;
12482 * _.keysIn(new Foo);
12483 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
12485 function keysIn(object) {
12487 isProto = isPrototype(object),
12488 props = baseKeysIn(object),
12489 propsLength = props.length,
12490 indexes = indexKeys(object),
12491 skipIndexes = !!indexes,
12492 result = indexes || [],
12493 length = result.length;
12495 while (++index < propsLength) {
12496 var key = props[index];
12497 if (!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
12498 !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
12506 * The opposite of `_.mapValues`; this method creates an object with the
12507 * same values as `object` and keys generated by running each own enumerable
12508 * string keyed property of `object` thru `iteratee`. The iteratee is invoked
12509 * with three arguments: (value, key, object).
12515 * @param {Object} object The object to iterate over.
12516 * @param {Array|Function|Object|string} [iteratee=_.identity]
12517 * The function invoked per iteration.
12518 * @returns {Object} Returns the new mapped object.
12522 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
12523 * return key + value;
12525 * // => { 'a1': 1, 'b2': 2 }
12527 function mapKeys(object, iteratee) {
12529 iteratee = getIteratee(iteratee, 3);
12531 baseForOwn(object, function(value, key, object) {
12532 result[iteratee(value, key, object)] = value;
12538 * Creates an object with the same keys as `object` and values generated
12539 * by running each own enumerable string keyed property of `object` thru
12540 * `iteratee`. The iteratee is invoked with three arguments:
12541 * (value, key, object).
12547 * @param {Object} object The object to iterate over.
12548 * @param {Array|Function|Object|string} [iteratee=_.identity]
12549 * The function invoked per iteration.
12550 * @returns {Object} Returns the new mapped object.
12555 * 'fred': { 'user': 'fred', 'age': 40 },
12556 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
12559 * _.mapValues(users, function(o) { return o.age; });
12560 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
12562 * // The `_.property` iteratee shorthand.
12563 * _.mapValues(users, 'age');
12564 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
12566 function mapValues(object, iteratee) {
12568 iteratee = getIteratee(iteratee, 3);
12570 baseForOwn(object, function(value, key, object) {
12571 result[key] = iteratee(value, key, object);
12577 * This method is like `_.assign` except that it recursively merges own and
12578 * inherited enumerable string keyed properties of source objects into the
12579 * destination object. Source properties that resolve to `undefined` are
12580 * skipped if a destination value exists. Array and plain object properties
12581 * are merged recursively.Other objects and value types are overridden by
12582 * assignment. Source objects are applied from left to right. Subsequent
12583 * sources overwrite property assignments of previous sources.
12585 * **Note:** This method mutates `object`.
12591 * @param {Object} object The destination object.
12592 * @param {...Object} [sources] The source objects.
12593 * @returns {Object} Returns `object`.
12597 * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
12601 * 'data': [{ 'age': 36 }, { 'age': 40 }]
12604 * _.merge(users, ages);
12605 * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
12607 var merge = createAssigner(function(object, source, srcIndex) {
12608 baseMerge(object, source, srcIndex);
12612 * This method is like `_.merge` except that it accepts `customizer` which
12613 * is invoked to produce the merged values of the destination and source
12614 * properties. If `customizer` returns `undefined`, merging is handled by the
12615 * method instead. The `customizer` is invoked with seven arguments:
12616 * (objValue, srcValue, key, object, source, stack).
12618 * **Note:** This method mutates `object`.
12624 * @param {Object} object The destination object.
12625 * @param {...Object} sources The source objects.
12626 * @param {Function} customizer The function to customize assigned values.
12627 * @returns {Object} Returns `object`.
12630 * function customizer(objValue, srcValue) {
12631 * if (_.isArray(objValue)) {
12632 * return objValue.concat(srcValue);
12637 * 'fruits': ['apple'],
12638 * 'vegetables': ['beet']
12642 * 'fruits': ['banana'],
12643 * 'vegetables': ['carrot']
12646 * _.mergeWith(object, other, customizer);
12647 * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
12649 var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
12650 baseMerge(object, source, srcIndex, customizer);
12654 * The opposite of `_.pick`; this method creates an object composed of the
12655 * own and inherited enumerable string keyed properties of `object` that are
12662 * @param {Object} object The source object.
12663 * @param {...(string|string[])} [props] The property identifiers to omit.
12664 * @returns {Object} Returns the new object.
12667 * var object = { 'a': 1, 'b': '2', 'c': 3 };
12669 * _.omit(object, ['a', 'c']);
12670 * // => { 'b': '2' }
12672 var omit = rest(function(object, props) {
12673 if (object == null) {
12676 props = arrayMap(baseFlatten(props, 1), toKey);
12677 return basePick(object, baseDifference(getAllKeysIn(object), props));
12681 * The opposite of `_.pickBy`; this method creates an object composed of
12682 * the own and inherited enumerable string keyed properties of `object` that
12683 * `predicate` doesn't return truthy for. The predicate is invoked with two
12684 * arguments: (value, key).
12690 * @param {Object} object The source object.
12691 * @param {Array|Function|Object|string} [predicate=_.identity]
12692 * The function invoked per property.
12693 * @returns {Object} Returns the new object.
12696 * var object = { 'a': 1, 'b': '2', 'c': 3 };
12698 * _.omitBy(object, _.isNumber);
12699 * // => { 'b': '2' }
12701 function omitBy(object, predicate) {
12702 predicate = getIteratee(predicate);
12703 return basePickBy(object, function(value, key) {
12704 return !predicate(value, key);
12709 * Creates an object composed of the picked `object` properties.
12715 * @param {Object} object The source object.
12716 * @param {...(string|string[])} [props] The property identifiers to pick.
12717 * @returns {Object} Returns the new object.
12720 * var object = { 'a': 1, 'b': '2', 'c': 3 };
12722 * _.pick(object, ['a', 'c']);
12723 * // => { 'a': 1, 'c': 3 }
12725 var pick = rest(function(object, props) {
12726 return object == null ? {} : basePick(object, arrayMap(baseFlatten(props, 1), toKey));
12730 * Creates an object composed of the `object` properties `predicate` returns
12731 * truthy for. The predicate is invoked with two arguments: (value, key).
12737 * @param {Object} object The source object.
12738 * @param {Array|Function|Object|string} [predicate=_.identity]
12739 * The function invoked per property.
12740 * @returns {Object} Returns the new object.
12743 * var object = { 'a': 1, 'b': '2', 'c': 3 };
12745 * _.pickBy(object, _.isNumber);
12746 * // => { 'a': 1, 'c': 3 }
12748 function pickBy(object, predicate) {
12749 return object == null ? {} : basePickBy(object, getIteratee(predicate));
12753 * This method is like `_.get` except that if the resolved value is a
12754 * function it's invoked with the `this` binding of its parent object and
12755 * its result is returned.
12761 * @param {Object} object The object to query.
12762 * @param {Array|string} path The path of the property to resolve.
12763 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
12764 * @returns {*} Returns the resolved value.
12767 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
12769 * _.result(object, 'a[0].b.c1');
12772 * _.result(object, 'a[0].b.c2');
12775 * _.result(object, 'a[0].b.c3', 'default');
12778 * _.result(object, 'a[0].b.c3', _.constant('default'));
12781 function result(object, path, defaultValue) {
12782 path = isKey(path, object) ? [path] : castPath(path);
12785 length = path.length;
12787 // Ensure the loop is entered when path is empty.
12789 object = undefined;
12792 while (++index < length) {
12793 var value = object == null ? undefined : object[toKey(path[index])];
12794 if (value === undefined) {
12796 value = defaultValue;
12798 object = isFunction(value) ? value.call(object) : value;
12804 * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
12805 * it's created. Arrays are created for missing index properties while objects
12806 * are created for all other missing properties. Use `_.setWith` to customize
12809 * **Note:** This method mutates `object`.
12815 * @param {Object} object The object to modify.
12816 * @param {Array|string} path The path of the property to set.
12817 * @param {*} value The value to set.
12818 * @returns {Object} Returns `object`.
12821 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
12823 * _.set(object, 'a[0].b.c', 4);
12824 * console.log(object.a[0].b.c);
12827 * _.set(object, ['x', '0', 'y', 'z'], 5);
12828 * console.log(object.x[0].y.z);
12831 function set(object, path, value) {
12832 return object == null ? object : baseSet(object, path, value);
12836 * This method is like `_.set` except that it accepts `customizer` which is
12837 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
12838 * path creation is handled by the method instead. The `customizer` is invoked
12839 * with three arguments: (nsValue, key, nsObject).
12841 * **Note:** This method mutates `object`.
12847 * @param {Object} object The object to modify.
12848 * @param {Array|string} path The path of the property to set.
12849 * @param {*} value The value to set.
12850 * @param {Function} [customizer] The function to customize assigned values.
12851 * @returns {Object} Returns `object`.
12856 * _.setWith(object, '[0][1]', 'a', Object);
12857 * // => { '0': { '1': 'a' } }
12859 function setWith(object, path, value, customizer) {
12860 customizer = typeof customizer == 'function' ? customizer : undefined;
12861 return object == null ? object : baseSet(object, path, value, customizer);
12865 * Creates an array of own enumerable string keyed-value pairs for `object`
12866 * which can be consumed by `_.fromPairs`.
12873 * @param {Object} object The object to query.
12874 * @returns {Array} Returns the new array of key-value pairs.
12882 * Foo.prototype.c = 3;
12884 * _.toPairs(new Foo);
12885 * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
12887 function toPairs(object) {
12888 return baseToPairs(object, keys(object));
12892 * Creates an array of own and inherited enumerable string keyed-value pairs
12893 * for `object` which can be consumed by `_.fromPairs`.
12900 * @param {Object} object The object to query.
12901 * @returns {Array} Returns the new array of key-value pairs.
12909 * Foo.prototype.c = 3;
12911 * _.toPairsIn(new Foo);
12912 * // => [['a', 1], ['b', 2], ['c', 1]] (iteration order is not guaranteed)
12914 function toPairsIn(object) {
12915 return baseToPairs(object, keysIn(object));
12919 * An alternative to `_.reduce`; this method transforms `object` to a new
12920 * `accumulator` object which is the result of running each of its own
12921 * enumerable string keyed properties thru `iteratee`, with each invocation
12922 * potentially mutating the `accumulator` object. The iteratee is invoked
12923 * with four arguments: (accumulator, value, key, object). Iteratee functions
12924 * may exit iteration early by explicitly returning `false`.
12930 * @param {Array|Object} object The object to iterate over.
12931 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
12932 * @param {*} [accumulator] The custom accumulator value.
12933 * @returns {*} Returns the accumulated value.
12936 * _.transform([2, 3, 4], function(result, n) {
12937 * result.push(n *= n);
12938 * return n % 2 == 0;
12942 * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
12943 * (result[value] || (result[value] = [])).push(key);
12945 * // => { '1': ['a', 'c'], '2': ['b'] }
12947 function transform(object, iteratee, accumulator) {
12948 var isArr = isArray(object) || isTypedArray(object);
12949 iteratee = getIteratee(iteratee, 4);
12951 if (accumulator == null) {
12952 if (isArr || isObject(object)) {
12953 var Ctor = object.constructor;
12955 accumulator = isArray(object) ? new Ctor : [];
12957 accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
12963 (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
12964 return iteratee(accumulator, value, index, object);
12966 return accumulator;
12970 * Removes the property at `path` of `object`.
12972 * **Note:** This method mutates `object`.
12978 * @param {Object} object The object to modify.
12979 * @param {Array|string} path The path of the property to unset.
12980 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
12983 * var object = { 'a': [{ 'b': { 'c': 7 } }] };
12984 * _.unset(object, 'a[0].b.c');
12987 * console.log(object);
12988 * // => { 'a': [{ 'b': {} }] };
12990 * _.unset(object, ['a', '0', 'b', 'c']);
12993 * console.log(object);
12994 * // => { 'a': [{ 'b': {} }] };
12996 function unset(object, path) {
12997 return object == null ? true : baseUnset(object, path);
13001 * This method is like `_.set` except that accepts `updater` to produce the
13002 * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
13003 * is invoked with one argument: (value).
13005 * **Note:** This method mutates `object`.
13011 * @param {Object} object The object to modify.
13012 * @param {Array|string} path The path of the property to set.
13013 * @param {Function} updater The function to produce the updated value.
13014 * @returns {Object} Returns `object`.
13017 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
13019 * _.update(object, 'a[0].b.c', function(n) { return n * n; });
13020 * console.log(object.a[0].b.c);
13023 * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
13024 * console.log(object.x[0].y.z);
13027 function update(object, path, updater) {
13028 return object == null ? object : baseUpdate(object, path, castFunction(updater));
13032 * This method is like `_.update` except that it accepts `customizer` which is
13033 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
13034 * path creation is handled by the method instead. The `customizer` is invoked
13035 * with three arguments: (nsValue, key, nsObject).
13037 * **Note:** This method mutates `object`.
13043 * @param {Object} object The object to modify.
13044 * @param {Array|string} path The path of the property to set.
13045 * @param {Function} updater The function to produce the updated value.
13046 * @param {Function} [customizer] The function to customize assigned values.
13047 * @returns {Object} Returns `object`.
13052 * _.updateWith(object, '[0][1]', _.constant('a'), Object);
13053 * // => { '0': { '1': 'a' } }
13055 function updateWith(object, path, updater, customizer) {
13056 customizer = typeof customizer == 'function' ? customizer : undefined;
13057 return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
13061 * Creates an array of the own enumerable string keyed property values of `object`.
13063 * **Note:** Non-object values are coerced to objects.
13069 * @param {Object} object The object to query.
13070 * @returns {Array} Returns the array of property values.
13078 * Foo.prototype.c = 3;
13080 * _.values(new Foo);
13081 * // => [1, 2] (iteration order is not guaranteed)
13086 function values(object) {
13087 return object ? baseValues(object, keys(object)) : [];
13091 * Creates an array of the own and inherited enumerable string keyed property
13092 * values of `object`.
13094 * **Note:** Non-object values are coerced to objects.
13100 * @param {Object} object The object to query.
13101 * @returns {Array} Returns the array of property values.
13109 * Foo.prototype.c = 3;
13111 * _.valuesIn(new Foo);
13112 * // => [1, 2, 3] (iteration order is not guaranteed)
13114 function valuesIn(object) {
13115 return object == null ? [] : baseValues(object, keysIn(object));
13118 /*------------------------------------------------------------------------*/
13121 * Clamps `number` within the inclusive `lower` and `upper` bounds.
13127 * @param {number} number The number to clamp.
13128 * @param {number} [lower] The lower bound.
13129 * @param {number} upper The upper bound.
13130 * @returns {number} Returns the clamped number.
13133 * _.clamp(-10, -5, 5);
13136 * _.clamp(10, -5, 5);
13139 function clamp(number, lower, upper) {
13140 if (upper === undefined) {
13144 if (upper !== undefined) {
13145 upper = toNumber(upper);
13146 upper = upper === upper ? upper : 0;
13148 if (lower !== undefined) {
13149 lower = toNumber(lower);
13150 lower = lower === lower ? lower : 0;
13152 return baseClamp(toNumber(number), lower, upper);
13156 * Checks if `n` is between `start` and up to, but not including, `end`. If
13157 * `end` is not specified, it's set to `start` with `start` then set to `0`.
13158 * If `start` is greater than `end` the params are swapped to support
13165 * @param {number} number The number to check.
13166 * @param {number} [start=0] The start of the range.
13167 * @param {number} end The end of the range.
13168 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
13169 * @see _.range, _.rangeRight
13172 * _.inRange(3, 2, 4);
13184 * _.inRange(1.2, 2);
13187 * _.inRange(5.2, 4);
13190 * _.inRange(-3, -2, -6);
13193 function inRange(number, start, end) {
13194 start = toNumber(start) || 0;
13195 if (end === undefined) {
13199 end = toNumber(end) || 0;
13201 number = toNumber(number);
13202 return baseInRange(number, start, end);
13206 * Produces a random number between the inclusive `lower` and `upper` bounds.
13207 * If only one argument is provided a number between `0` and the given number
13208 * is returned. If `floating` is `true`, or either `lower` or `upper` are
13209 * floats, a floating-point number is returned instead of an integer.
13211 * **Note:** JavaScript follows the IEEE-754 standard for resolving
13212 * floating-point values which can produce unexpected results.
13218 * @param {number} [lower=0] The lower bound.
13219 * @param {number} [upper=1] The upper bound.
13220 * @param {boolean} [floating] Specify returning a floating-point number.
13221 * @returns {number} Returns the random number.
13225 * // => an integer between 0 and 5
13228 * // => also an integer between 0 and 5
13230 * _.random(5, true);
13231 * // => a floating-point number between 0 and 5
13233 * _.random(1.2, 5.2);
13234 * // => a floating-point number between 1.2 and 5.2
13236 function random(lower, upper, floating) {
13237 if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
13238 upper = floating = undefined;
13240 if (floating === undefined) {
13241 if (typeof upper == 'boolean') {
13245 else if (typeof lower == 'boolean') {
13250 if (lower === undefined && upper === undefined) {
13255 lower = toNumber(lower) || 0;
13256 if (upper === undefined) {
13260 upper = toNumber(upper) || 0;
13263 if (lower > upper) {
13268 if (floating || lower % 1 || upper % 1) {
13269 var rand = nativeRandom();
13270 return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
13272 return baseRandom(lower, upper);
13275 /*------------------------------------------------------------------------*/
13278 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
13284 * @param {string} [string=''] The string to convert.
13285 * @returns {string} Returns the camel cased string.
13288 * _.camelCase('Foo Bar');
13291 * _.camelCase('--foo-bar--');
13294 * _.camelCase('__FOO_BAR__');
13297 var camelCase = createCompounder(function(result, word, index) {
13298 word = word.toLowerCase();
13299 return result + (index ? capitalize(word) : word);
13303 * Converts the first character of `string` to upper case and the remaining
13310 * @param {string} [string=''] The string to capitalize.
13311 * @returns {string} Returns the capitalized string.
13314 * _.capitalize('FRED');
13317 function capitalize(string) {
13318 return upperFirst(toString(string).toLowerCase());
13322 * Deburrs `string` by converting
13323 * [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
13324 * to basic latin letters and removing
13325 * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
13331 * @param {string} [string=''] The string to deburr.
13332 * @returns {string} Returns the deburred string.
13335 * _.deburr('déjà vu');
13338 function deburr(string) {
13339 string = toString(string);
13340 return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
13344 * Checks if `string` ends with the given target string.
13350 * @param {string} [string=''] The string to search.
13351 * @param {string} [target] The string to search for.
13352 * @param {number} [position=string.length] The position to search from.
13353 * @returns {boolean} Returns `true` if `string` ends with `target`,
13357 * _.endsWith('abc', 'c');
13360 * _.endsWith('abc', 'b');
13363 * _.endsWith('abc', 'b', 2);
13366 function endsWith(string, target, position) {
13367 string = toString(string);
13368 target = baseToString(target);
13370 var length = string.length;
13371 position = position === undefined
13373 : baseClamp(toInteger(position), 0, length);
13375 position -= target.length;
13376 return position >= 0 && string.indexOf(target, position) == position;
13380 * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to
13381 * their corresponding HTML entities.
13383 * **Note:** No other characters are escaped. To escape additional
13384 * characters use a third-party library like [_he_](https://mths.be/he).
13386 * Though the ">" character is escaped for symmetry, characters like
13387 * ">" and "/" don't need escaping in HTML and have no special meaning
13388 * unless they're part of a tag or unquoted attribute value. See
13389 * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
13390 * (under "semi-related fun fact") for more details.
13392 * Backticks are escaped because in IE < 9, they can break out of
13393 * attribute values or HTML comments. See [#59](https://html5sec.org/#59),
13394 * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
13395 * [#133](https://html5sec.org/#133) of the
13396 * [HTML5 Security Cheatsheet](https://html5sec.org/) for more details.
13398 * When working with HTML you should always
13399 * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
13406 * @param {string} [string=''] The string to escape.
13407 * @returns {string} Returns the escaped string.
13410 * _.escape('fred, barney, & pebbles');
13411 * // => 'fred, barney, & pebbles'
13413 function escape(string) {
13414 string = toString(string);
13415 return (string && reHasUnescapedHtml.test(string))
13416 ? string.replace(reUnescapedHtml, escapeHtmlChar)
13421 * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
13422 * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
13428 * @param {string} [string=''] The string to escape.
13429 * @returns {string} Returns the escaped string.
13432 * _.escapeRegExp('[lodash](https://lodash.com/)');
13433 * // => '\[lodash\]\(https://lodash\.com/\)'
13435 function escapeRegExp(string) {
13436 string = toString(string);
13437 return (string && reHasRegExpChar.test(string))
13438 ? string.replace(reRegExpChar, '\\$&')
13443 * Converts `string` to
13444 * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
13450 * @param {string} [string=''] The string to convert.
13451 * @returns {string} Returns the kebab cased string.
13454 * _.kebabCase('Foo Bar');
13457 * _.kebabCase('fooBar');
13460 * _.kebabCase('__FOO_BAR__');
13463 var kebabCase = createCompounder(function(result, word, index) {
13464 return result + (index ? '-' : '') + word.toLowerCase();
13468 * Converts `string`, as space separated words, to lower case.
13474 * @param {string} [string=''] The string to convert.
13475 * @returns {string} Returns the lower cased string.
13478 * _.lowerCase('--Foo-Bar--');
13481 * _.lowerCase('fooBar');
13484 * _.lowerCase('__FOO_BAR__');
13487 var lowerCase = createCompounder(function(result, word, index) {
13488 return result + (index ? ' ' : '') + word.toLowerCase();
13492 * Converts the first character of `string` to lower case.
13498 * @param {string} [string=''] The string to convert.
13499 * @returns {string} Returns the converted string.
13502 * _.lowerFirst('Fred');
13505 * _.lowerFirst('FRED');
13508 var lowerFirst = createCaseFirst('toLowerCase');
13511 * Pads `string` on the left and right sides if it's shorter than `length`.
13512 * Padding characters are truncated if they can't be evenly divided by `length`.
13518 * @param {string} [string=''] The string to pad.
13519 * @param {number} [length=0] The padding length.
13520 * @param {string} [chars=' '] The string used as padding.
13521 * @returns {string} Returns the padded string.
13527 * _.pad('abc', 8, '_-');
13533 function pad(string, length, chars) {
13534 string = toString(string);
13535 length = toInteger(length);
13537 var strLength = length ? stringSize(string) : 0;
13538 if (!length || strLength >= length) {
13541 var mid = (length - strLength) / 2;
13543 createPadding(nativeFloor(mid), chars) +
13545 createPadding(nativeCeil(mid), chars)
13550 * Pads `string` on the right side if it's shorter than `length`. Padding
13551 * characters are truncated if they exceed `length`.
13557 * @param {string} [string=''] The string to pad.
13558 * @param {number} [length=0] The padding length.
13559 * @param {string} [chars=' '] The string used as padding.
13560 * @returns {string} Returns the padded string.
13563 * _.padEnd('abc', 6);
13566 * _.padEnd('abc', 6, '_-');
13569 * _.padEnd('abc', 3);
13572 function padEnd(string, length, chars) {
13573 string = toString(string);
13574 length = toInteger(length);
13576 var strLength = length ? stringSize(string) : 0;
13577 return (length && strLength < length)
13578 ? (string + createPadding(length - strLength, chars))
13583 * Pads `string` on the left side if it's shorter than `length`. Padding
13584 * characters are truncated if they exceed `length`.
13590 * @param {string} [string=''] The string to pad.
13591 * @param {number} [length=0] The padding length.
13592 * @param {string} [chars=' '] The string used as padding.
13593 * @returns {string} Returns the padded string.
13596 * _.padStart('abc', 6);
13599 * _.padStart('abc', 6, '_-');
13602 * _.padStart('abc', 3);
13605 function padStart(string, length, chars) {
13606 string = toString(string);
13607 length = toInteger(length);
13609 var strLength = length ? stringSize(string) : 0;
13610 return (length && strLength < length)
13611 ? (createPadding(length - strLength, chars) + string)
13616 * Converts `string` to an integer of the specified radix. If `radix` is
13617 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
13618 * hexadecimal, in which case a `radix` of `16` is used.
13620 * **Note:** This method aligns with the
13621 * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
13627 * @param {string} string The string to convert.
13628 * @param {number} [radix=10] The radix to interpret `value` by.
13629 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
13630 * @returns {number} Returns the converted integer.
13633 * _.parseInt('08');
13636 * _.map(['6', '08', '10'], _.parseInt);
13639 function parseInt(string, radix, guard) {
13640 // Chrome fails to trim leading <BOM> whitespace characters.
13641 // See https://bugs.chromium.org/p/v8/issues/detail?id=3109 for more details.
13642 if (guard || radix == null) {
13644 } else if (radix) {
13647 string = toString(string).replace(reTrim, '');
13648 return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
13652 * Repeats the given string `n` times.
13658 * @param {string} [string=''] The string to repeat.
13659 * @param {number} [n=1] The number of times to repeat the string.
13660 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
13661 * @returns {string} Returns the repeated string.
13664 * _.repeat('*', 3);
13667 * _.repeat('abc', 2);
13670 * _.repeat('abc', 0);
13673 function repeat(string, n, guard) {
13674 if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
13679 return baseRepeat(toString(string), n);
13683 * Replaces matches for `pattern` in `string` with `replacement`.
13685 * **Note:** This method is based on
13686 * [`String#replace`](https://mdn.io/String/replace).
13692 * @param {string} [string=''] The string to modify.
13693 * @param {RegExp|string} pattern The pattern to replace.
13694 * @param {Function|string} replacement The match replacement.
13695 * @returns {string} Returns the modified string.
13698 * _.replace('Hi Fred', 'Fred', 'Barney');
13699 * // => 'Hi Barney'
13701 function replace() {
13702 var args = arguments,
13703 string = toString(args[0]);
13705 return args.length < 3 ? string : nativeReplace.call(string, args[1], args[2]);
13709 * Converts `string` to
13710 * [snake case](https://en.wikipedia.org/wiki/Snake_case).
13716 * @param {string} [string=''] The string to convert.
13717 * @returns {string} Returns the snake cased string.
13720 * _.snakeCase('Foo Bar');
13723 * _.snakeCase('fooBar');
13726 * _.snakeCase('--FOO-BAR--');
13729 var snakeCase = createCompounder(function(result, word, index) {
13730 return result + (index ? '_' : '') + word.toLowerCase();
13734 * Splits `string` by `separator`.
13736 * **Note:** This method is based on
13737 * [`String#split`](https://mdn.io/String/split).
13743 * @param {string} [string=''] The string to split.
13744 * @param {RegExp|string} separator The separator pattern to split by.
13745 * @param {number} [limit] The length to truncate results to.
13746 * @returns {Array} Returns the new array of string segments.
13749 * _.split('a-b-c', '-', 2);
13752 function split(string, separator, limit) {
13753 if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
13754 separator = limit = undefined;
13756 limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
13760 string = toString(string);
13762 typeof separator == 'string' ||
13763 (separator != null && !isRegExp(separator))
13765 separator = baseToString(separator);
13766 if (separator == '' && reHasComplexSymbol.test(string)) {
13767 return castSlice(stringToArray(string), 0, limit);
13770 return nativeSplit.call(string, separator, limit);
13774 * Converts `string` to
13775 * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
13781 * @param {string} [string=''] The string to convert.
13782 * @returns {string} Returns the start cased string.
13785 * _.startCase('--foo-bar--');
13788 * _.startCase('fooBar');
13791 * _.startCase('__FOO_BAR__');
13794 var startCase = createCompounder(function(result, word, index) {
13795 return result + (index ? ' ' : '') + upperFirst(word);
13799 * Checks if `string` starts with the given target string.
13805 * @param {string} [string=''] The string to search.
13806 * @param {string} [target] The string to search for.
13807 * @param {number} [position=0] The position to search from.
13808 * @returns {boolean} Returns `true` if `string` starts with `target`,
13812 * _.startsWith('abc', 'a');
13815 * _.startsWith('abc', 'b');
13818 * _.startsWith('abc', 'b', 1);
13821 function startsWith(string, target, position) {
13822 string = toString(string);
13823 position = baseClamp(toInteger(position), 0, string.length);
13824 return string.lastIndexOf(baseToString(target), position) == position;
13828 * Creates a compiled template function that can interpolate data properties
13829 * in "interpolate" delimiters, HTML-escape interpolated data properties in
13830 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
13831 * properties may be accessed as free variables in the template. If a setting
13832 * object is given, it takes precedence over `_.templateSettings` values.
13834 * **Note:** In the development build `_.template` utilizes
13835 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
13836 * for easier debugging.
13838 * For more information on precompiling templates see
13839 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
13841 * For more information on Chrome extension sandboxes see
13842 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
13848 * @param {string} [string=''] The template string.
13849 * @param {Object} [options={}] The options object.
13850 * @param {RegExp} [options.escape=_.templateSettings.escape]
13851 * The HTML "escape" delimiter.
13852 * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
13853 * The "evaluate" delimiter.
13854 * @param {Object} [options.imports=_.templateSettings.imports]
13855 * An object to import into the template as free variables.
13856 * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
13857 * The "interpolate" delimiter.
13858 * @param {string} [options.sourceURL='lodash.templateSources[n]']
13859 * The sourceURL of the compiled template.
13860 * @param {string} [options.variable='obj']
13861 * The data object variable name.
13862 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
13863 * @returns {Function} Returns the compiled template function.
13866 * // Use the "interpolate" delimiter to create a compiled template.
13867 * var compiled = _.template('hello <%= user %>!');
13868 * compiled({ 'user': 'fred' });
13869 * // => 'hello fred!'
13871 * // Use the HTML "escape" delimiter to escape data property values.
13872 * var compiled = _.template('<b><%- value %></b>');
13873 * compiled({ 'value': '<script>' });
13874 * // => '<b><script></b>'
13876 * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
13877 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
13878 * compiled({ 'users': ['fred', 'barney'] });
13879 * // => '<li>fred</li><li>barney</li>'
13881 * // Use the internal `print` function in "evaluate" delimiters.
13882 * var compiled = _.template('<% print("hello " + user); %>!');
13883 * compiled({ 'user': 'barney' });
13884 * // => 'hello barney!'
13886 * // Use the ES delimiter as an alternative to the default "interpolate" delimiter.
13887 * var compiled = _.template('hello ${ user }!');
13888 * compiled({ 'user': 'pebbles' });
13889 * // => 'hello pebbles!'
13891 * // Use custom template delimiters.
13892 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
13893 * var compiled = _.template('hello {{ user }}!');
13894 * compiled({ 'user': 'mustache' });
13895 * // => 'hello mustache!'
13897 * // Use backslashes to treat delimiters as plain text.
13898 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
13899 * compiled({ 'value': 'ignored' });
13900 * // => '<%- value %>'
13902 * // Use the `imports` option to import `jQuery` as `jq`.
13903 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
13904 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
13905 * compiled({ 'users': ['fred', 'barney'] });
13906 * // => '<li>fred</li><li>barney</li>'
13908 * // Use the `sourceURL` option to specify a custom sourceURL for the template.
13909 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
13911 * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
13913 * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
13914 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
13916 * // => function(data) {
13917 * // var __t, __p = '';
13918 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
13922 * // Use the `source` property to inline compiled templates for meaningful
13923 * // line numbers in error messages and stack traces.
13924 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
13926 * "main": ' + _.template(mainText).source + '\
13930 function template(string, options, guard) {
13931 // Based on John Resig's `tmpl` implementation
13932 // (http://ejohn.org/blog/javascript-micro-templating/)
13933 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
13934 var settings = lodash.templateSettings;
13936 if (guard && isIterateeCall(string, options, guard)) {
13937 options = undefined;
13939 string = toString(string);
13940 options = assignInWith({}, options, settings, assignInDefaults);
13942 var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults),
13943 importsKeys = keys(imports),
13944 importsValues = baseValues(imports, importsKeys);
13949 interpolate = options.interpolate || reNoMatch,
13950 source = "__p += '";
13952 // Compile the regexp to match each delimiter.
13953 var reDelimiters = RegExp(
13954 (options.escape || reNoMatch).source + '|' +
13955 interpolate.source + '|' +
13956 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
13957 (options.evaluate || reNoMatch).source + '|$'
13960 // Use a sourceURL for easier debugging.
13961 var sourceURL = '//# sourceURL=' +
13962 ('sourceURL' in options
13963 ? options.sourceURL
13964 : ('lodash.templateSources[' + (++templateCounter) + ']')
13967 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
13968 interpolateValue || (interpolateValue = esTemplateValue);
13970 // Escape characters that can't be included in string literals.
13971 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
13973 // Replace delimiters with snippets.
13976 source += "' +\n__e(" + escapeValue + ") +\n'";
13978 if (evaluateValue) {
13979 isEvaluating = true;
13980 source += "';\n" + evaluateValue + ";\n__p += '";
13982 if (interpolateValue) {
13983 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
13985 index = offset + match.length;
13987 // The JS engine embedded in Adobe products needs `match` returned in
13988 // order to produce the correct `offset` value.
13994 // If `variable` is not specified wrap a with-statement around the generated
13995 // code to add the data object to the top of the scope chain.
13996 var variable = options.variable;
13998 source = 'with (obj) {\n' + source + '\n}\n';
14000 // Cleanup code by stripping empty strings.
14001 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
14002 .replace(reEmptyStringMiddle, '$1')
14003 .replace(reEmptyStringTrailing, '$1;');
14005 // Frame code as the function body.
14006 source = 'function(' + (variable || 'obj') + ') {\n' +
14009 : 'obj || (obj = {});\n'
14011 "var __t, __p = ''" +
14013 ? ', __e = _.escape'
14017 ? ', __j = Array.prototype.join;\n' +
14018 "function print() { __p += __j.call(arguments, '') }\n"
14024 var result = attempt(function() {
14025 return Function(importsKeys, sourceURL + 'return ' + source)
14026 .apply(undefined, importsValues);
14029 // Provide the compiled function's source by its `toString` method or
14030 // the `source` property as a convenience for inlining compiled templates.
14031 result.source = source;
14032 if (isError(result)) {
14039 * Converts `string`, as a whole, to lower case just like
14040 * [String#toLowerCase](https://mdn.io/toLowerCase).
14046 * @param {string} [string=''] The string to convert.
14047 * @returns {string} Returns the lower cased string.
14050 * _.toLower('--Foo-Bar--');
14051 * // => '--foo-bar--'
14053 * _.toLower('fooBar');
14056 * _.toLower('__FOO_BAR__');
14057 * // => '__foo_bar__'
14059 function toLower(value) {
14060 return toString(value).toLowerCase();
14064 * Converts `string`, as a whole, to upper case just like
14065 * [String#toUpperCase](https://mdn.io/toUpperCase).
14071 * @param {string} [string=''] The string to convert.
14072 * @returns {string} Returns the upper cased string.
14075 * _.toUpper('--foo-bar--');
14076 * // => '--FOO-BAR--'
14078 * _.toUpper('fooBar');
14081 * _.toUpper('__foo_bar__');
14082 * // => '__FOO_BAR__'
14084 function toUpper(value) {
14085 return toString(value).toUpperCase();
14089 * Removes leading and trailing whitespace or specified characters from `string`.
14095 * @param {string} [string=''] The string to trim.
14096 * @param {string} [chars=whitespace] The characters to trim.
14097 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
14098 * @returns {string} Returns the trimmed string.
14104 * _.trim('-_-abc-_-', '_-');
14107 * _.map([' foo ', ' bar '], _.trim);
14108 * // => ['foo', 'bar']
14110 function trim(string, chars, guard) {
14111 string = toString(string);
14112 if (string && (guard || chars === undefined)) {
14113 return string.replace(reTrim, '');
14115 if (!string || !(chars = baseToString(chars))) {
14118 var strSymbols = stringToArray(string),
14119 chrSymbols = stringToArray(chars),
14120 start = charsStartIndex(strSymbols, chrSymbols),
14121 end = charsEndIndex(strSymbols, chrSymbols) + 1;
14123 return castSlice(strSymbols, start, end).join('');
14127 * Removes trailing whitespace or specified characters from `string`.
14133 * @param {string} [string=''] The string to trim.
14134 * @param {string} [chars=whitespace] The characters to trim.
14135 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
14136 * @returns {string} Returns the trimmed string.
14139 * _.trimEnd(' abc ');
14142 * _.trimEnd('-_-abc-_-', '_-');
14145 function trimEnd(string, chars, guard) {
14146 string = toString(string);
14147 if (string && (guard || chars === undefined)) {
14148 return string.replace(reTrimEnd, '');
14150 if (!string || !(chars = baseToString(chars))) {
14153 var strSymbols = stringToArray(string),
14154 end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
14156 return castSlice(strSymbols, 0, end).join('');
14160 * Removes leading whitespace or specified characters from `string`.
14166 * @param {string} [string=''] The string to trim.
14167 * @param {string} [chars=whitespace] The characters to trim.
14168 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
14169 * @returns {string} Returns the trimmed string.
14172 * _.trimStart(' abc ');
14175 * _.trimStart('-_-abc-_-', '_-');
14178 function trimStart(string, chars, guard) {
14179 string = toString(string);
14180 if (string && (guard || chars === undefined)) {
14181 return string.replace(reTrimStart, '');
14183 if (!string || !(chars = baseToString(chars))) {
14186 var strSymbols = stringToArray(string),
14187 start = charsStartIndex(strSymbols, stringToArray(chars));
14189 return castSlice(strSymbols, start).join('');
14193 * Truncates `string` if it's longer than the given maximum string length.
14194 * The last characters of the truncated string are replaced with the omission
14195 * string which defaults to "...".
14201 * @param {string} [string=''] The string to truncate.
14202 * @param {Object} [options={}] The options object.
14203 * @param {number} [options.length=30] The maximum string length.
14204 * @param {string} [options.omission='...'] The string to indicate text is omitted.
14205 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
14206 * @returns {string} Returns the truncated string.
14209 * _.truncate('hi-diddly-ho there, neighborino');
14210 * // => 'hi-diddly-ho there, neighbo...'
14212 * _.truncate('hi-diddly-ho there, neighborino', {
14216 * // => 'hi-diddly-ho there,...'
14218 * _.truncate('hi-diddly-ho there, neighborino', {
14220 * 'separator': /,? +/
14222 * // => 'hi-diddly-ho there...'
14224 * _.truncate('hi-diddly-ho there, neighborino', {
14225 * 'omission': ' [...]'
14227 * // => 'hi-diddly-ho there, neig [...]'
14229 function truncate(string, options) {
14230 var length = DEFAULT_TRUNC_LENGTH,
14231 omission = DEFAULT_TRUNC_OMISSION;
14233 if (isObject(options)) {
14234 var separator = 'separator' in options ? options.separator : separator;
14235 length = 'length' in options ? toInteger(options.length) : length;
14236 omission = 'omission' in options ? baseToString(options.omission) : omission;
14238 string = toString(string);
14240 var strLength = string.length;
14241 if (reHasComplexSymbol.test(string)) {
14242 var strSymbols = stringToArray(string);
14243 strLength = strSymbols.length;
14245 if (length >= strLength) {
14248 var end = length - stringSize(omission);
14252 var result = strSymbols
14253 ? castSlice(strSymbols, 0, end).join('')
14254 : string.slice(0, end);
14256 if (separator === undefined) {
14257 return result + omission;
14260 end += (result.length - end);
14262 if (isRegExp(separator)) {
14263 if (string.slice(end).search(separator)) {
14265 substring = result;
14267 if (!separator.global) {
14268 separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
14270 separator.lastIndex = 0;
14271 while ((match = separator.exec(substring))) {
14272 var newEnd = match.index;
14274 result = result.slice(0, newEnd === undefined ? end : newEnd);
14276 } else if (string.indexOf(baseToString(separator), end) != end) {
14277 var index = result.lastIndexOf(separator);
14279 result = result.slice(0, index);
14282 return result + omission;
14286 * The inverse of `_.escape`; this method converts the HTML entities
14287 * `&`, `<`, `>`, `"`, `'`, and ``` in `string` to
14288 * their corresponding characters.
14290 * **Note:** No other HTML entities are unescaped. To unescape additional
14291 * HTML entities use a third-party library like [_he_](https://mths.be/he).
14297 * @param {string} [string=''] The string to unescape.
14298 * @returns {string} Returns the unescaped string.
14301 * _.unescape('fred, barney, & pebbles');
14302 * // => 'fred, barney, & pebbles'
14304 function unescape(string) {
14305 string = toString(string);
14306 return (string && reHasEscapedHtml.test(string))
14307 ? string.replace(reEscapedHtml, unescapeHtmlChar)
14312 * Converts `string`, as space separated words, to upper case.
14318 * @param {string} [string=''] The string to convert.
14319 * @returns {string} Returns the upper cased string.
14322 * _.upperCase('--foo-bar');
14325 * _.upperCase('fooBar');
14328 * _.upperCase('__foo_bar__');
14331 var upperCase = createCompounder(function(result, word, index) {
14332 return result + (index ? ' ' : '') + word.toUpperCase();
14336 * Converts the first character of `string` to upper case.
14342 * @param {string} [string=''] The string to convert.
14343 * @returns {string} Returns the converted string.
14346 * _.upperFirst('fred');
14349 * _.upperFirst('FRED');
14352 var upperFirst = createCaseFirst('toUpperCase');
14355 * Splits `string` into an array of its words.
14361 * @param {string} [string=''] The string to inspect.
14362 * @param {RegExp|string} [pattern] The pattern to match words.
14363 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
14364 * @returns {Array} Returns the words of `string`.
14367 * _.words('fred, barney, & pebbles');
14368 * // => ['fred', 'barney', 'pebbles']
14370 * _.words('fred, barney, & pebbles', /[^, ]+/g);
14371 * // => ['fred', 'barney', '&', 'pebbles']
14373 function words(string, pattern, guard) {
14374 string = toString(string);
14375 pattern = guard ? undefined : pattern;
14377 if (pattern === undefined) {
14378 pattern = reHasComplexWord.test(string) ? reComplexWord : reBasicWord;
14380 return string.match(pattern) || [];
14383 /*------------------------------------------------------------------------*/
14386 * Attempts to invoke `func`, returning either the result or the caught error
14387 * object. Any additional arguments are provided to `func` when it's invoked.
14393 * @param {Function} func The function to attempt.
14394 * @param {...*} [args] The arguments to invoke `func` with.
14395 * @returns {*} Returns the `func` result or error object.
14398 * // Avoid throwing errors for invalid selectors.
14399 * var elements = _.attempt(function(selector) {
14400 * return document.querySelectorAll(selector);
14403 * if (_.isError(elements)) {
14407 var attempt = rest(function(func, args) {
14409 return apply(func, undefined, args);
14411 return isError(e) ? e : new Error(e);
14416 * Binds methods of an object to the object itself, overwriting the existing
14419 * **Note:** This method doesn't set the "length" property of bound functions.
14425 * @param {Object} object The object to bind and assign the bound methods to.
14426 * @param {...(string|string[])} methodNames The object method names to bind.
14427 * @returns {Object} Returns `object`.
14432 * 'onClick': function() {
14433 * console.log('clicked ' + this.label);
14437 * _.bindAll(view, 'onClick');
14438 * jQuery(element).on('click', view.onClick);
14439 * // => Logs 'clicked docs' when clicked.
14441 var bindAll = rest(function(object, methodNames) {
14442 arrayEach(baseFlatten(methodNames, 1), function(key) {
14444 object[key] = bind(object[key], object);
14450 * Creates a function that iterates over `pairs` and invokes the corresponding
14451 * function of the first predicate to return truthy. The predicate-function
14452 * pairs are invoked with the `this` binding and arguments of the created
14459 * @param {Array} pairs The predicate-function pairs.
14460 * @returns {Function} Returns the new function.
14463 * var func = _.cond([
14464 * [_.matches({ 'a': 1 }), _.constant('matches A')],
14465 * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
14466 * [_.constant(true), _.constant('no match')]
14469 * func({ 'a': 1, 'b': 2 });
14470 * // => 'matches A'
14472 * func({ 'a': 0, 'b': 1 });
14473 * // => 'matches B'
14475 * func({ 'a': '1', 'b': '2' });
14478 function cond(pairs) {
14479 var length = pairs ? pairs.length : 0,
14480 toIteratee = getIteratee();
14482 pairs = !length ? [] : arrayMap(pairs, function(pair) {
14483 if (typeof pair[1] != 'function') {
14484 throw new TypeError(FUNC_ERROR_TEXT);
14486 return [toIteratee(pair[0]), pair[1]];
14489 return rest(function(args) {
14491 while (++index < length) {
14492 var pair = pairs[index];
14493 if (apply(pair[0], this, args)) {
14494 return apply(pair[1], this, args);
14501 * Creates a function that invokes the predicate properties of `source` with
14502 * the corresponding property values of a given object, returning `true` if
14503 * all predicates return truthy, else `false`.
14509 * @param {Object} source The object of property predicates to conform to.
14510 * @returns {Function} Returns the new function.
14514 * { 'user': 'barney', 'age': 36 },
14515 * { 'user': 'fred', 'age': 40 }
14518 * _.filter(users, _.conforms({ 'age': _.partial(_.gt, _, 38) }));
14519 * // => [{ 'user': 'fred', 'age': 40 }]
14521 function conforms(source) {
14522 return baseConforms(baseClone(source, true));
14526 * Creates a function that returns `value`.
14532 * @param {*} value The value to return from the new function.
14533 * @returns {Function} Returns the new function.
14536 * var object = { 'user': 'fred' };
14537 * var getter = _.constant(object);
14539 * getter() === object;
14542 function constant(value) {
14543 return function() {
14549 * Creates a function that returns the result of invoking the given functions
14550 * with the `this` binding of the created function, where each successive
14551 * invocation is supplied the return value of the previous.
14557 * @param {...(Function|Function[])} [funcs] Functions to invoke.
14558 * @returns {Function} Returns the new function.
14562 * function square(n) {
14566 * var addSquare = _.flow(_.add, square);
14570 var flow = createFlow();
14573 * This method is like `_.flow` except that it creates a function that
14574 * invokes the given functions from right to left.
14580 * @param {...(Function|Function[])} [funcs] Functions to invoke.
14581 * @returns {Function} Returns the new function.
14585 * function square(n) {
14589 * var addSquare = _.flowRight(square, _.add);
14593 var flowRight = createFlow(true);
14596 * This method returns the first argument given to it.
14602 * @param {*} value Any value.
14603 * @returns {*} Returns `value`.
14606 * var object = { 'user': 'fred' };
14608 * _.identity(object) === object;
14611 function identity(value) {
14616 * Creates a function that invokes `func` with the arguments of the created
14617 * function. If `func` is a property name, the created function returns the
14618 * property value for a given element. If `func` is an array or object, the
14619 * created function returns `true` for elements that contain the equivalent
14620 * source properties, otherwise it returns `false`.
14626 * @param {*} [func=_.identity] The value to convert to a callback.
14627 * @returns {Function} Returns the callback.
14631 * { 'user': 'barney', 'age': 36, 'active': true },
14632 * { 'user': 'fred', 'age': 40, 'active': false }
14635 * // The `_.matches` iteratee shorthand.
14636 * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
14637 * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
14639 * // The `_.matchesProperty` iteratee shorthand.
14640 * _.filter(users, _.iteratee(['user', 'fred']));
14641 * // => [{ 'user': 'fred', 'age': 40 }]
14643 * // The `_.property` iteratee shorthand.
14644 * _.map(users, _.iteratee('user'));
14645 * // => ['barney', 'fred']
14647 * // Create custom iteratee shorthands.
14648 * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
14649 * return !_.isRegExp(func) ? iteratee(func) : function(string) {
14650 * return func.test(string);
14654 * _.filter(['abc', 'def'], /ef/);
14657 function iteratee(func) {
14658 return baseIteratee(typeof func == 'function' ? func : baseClone(func, true));
14662 * Creates a function that performs a partial deep comparison between a given
14663 * object and `source`, returning `true` if the given object has equivalent
14664 * property values, else `false`. The created function is equivalent to
14665 * `_.isMatch` with a `source` partially applied.
14667 * **Note:** This method supports comparing the same values as `_.isEqual`.
14673 * @param {Object} source The object of property values to match.
14674 * @returns {Function} Returns the new function.
14678 * { 'user': 'barney', 'age': 36, 'active': true },
14679 * { 'user': 'fred', 'age': 40, 'active': false }
14682 * _.filter(users, _.matches({ 'age': 40, 'active': false }));
14683 * // => [{ 'user': 'fred', 'age': 40, 'active': false }]
14685 function matches(source) {
14686 return baseMatches(baseClone(source, true));
14690 * Creates a function that performs a partial deep comparison between the
14691 * value at `path` of a given object to `srcValue`, returning `true` if the
14692 * object value is equivalent, else `false`.
14694 * **Note:** This method supports comparing the same values as `_.isEqual`.
14700 * @param {Array|string} path The path of the property to get.
14701 * @param {*} srcValue The value to match.
14702 * @returns {Function} Returns the new function.
14706 * { 'user': 'barney' },
14707 * { 'user': 'fred' }
14710 * _.find(users, _.matchesProperty('user', 'fred'));
14711 * // => { 'user': 'fred' }
14713 function matchesProperty(path, srcValue) {
14714 return baseMatchesProperty(path, baseClone(srcValue, true));
14718 * Creates a function that invokes the method at `path` of a given object.
14719 * Any additional arguments are provided to the invoked method.
14725 * @param {Array|string} path The path of the method to invoke.
14726 * @param {...*} [args] The arguments to invoke the method with.
14727 * @returns {Function} Returns the new function.
14731 * { 'a': { 'b': _.constant(2) } },
14732 * { 'a': { 'b': _.constant(1) } }
14735 * _.map(objects, _.method('a.b'));
14738 * _.map(objects, _.method(['a', 'b']));
14741 var method = rest(function(path, args) {
14742 return function(object) {
14743 return baseInvoke(object, path, args);
14748 * The opposite of `_.method`; this method creates a function that invokes
14749 * the method at a given path of `object`. Any additional arguments are
14750 * provided to the invoked method.
14756 * @param {Object} object The object to query.
14757 * @param {...*} [args] The arguments to invoke the method with.
14758 * @returns {Function} Returns the new function.
14761 * var array = _.times(3, _.constant),
14762 * object = { 'a': array, 'b': array, 'c': array };
14764 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
14767 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
14770 var methodOf = rest(function(object, args) {
14771 return function(path) {
14772 return baseInvoke(object, path, args);
14777 * Adds all own enumerable string keyed function properties of a source
14778 * object to the destination object. If `object` is a function, then methods
14779 * are added to its prototype as well.
14781 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
14782 * avoid conflicts caused by modifying the original.
14788 * @param {Function|Object} [object=lodash] The destination object.
14789 * @param {Object} source The object of functions to add.
14790 * @param {Object} [options={}] The options object.
14791 * @param {boolean} [options.chain=true] Specify whether mixins are chainable.
14792 * @returns {Function|Object} Returns `object`.
14795 * function vowels(string) {
14796 * return _.filter(string, function(v) {
14797 * return /[aeiou]/i.test(v);
14801 * _.mixin({ 'vowels': vowels });
14802 * _.vowels('fred');
14805 * _('fred').vowels().value();
14808 * _.mixin({ 'vowels': vowels }, { 'chain': false });
14809 * _('fred').vowels();
14812 function mixin(object, source, options) {
14813 var props = keys(source),
14814 methodNames = baseFunctions(source, props);
14816 if (options == null &&
14817 !(isObject(source) && (methodNames.length || !props.length))) {
14821 methodNames = baseFunctions(source, keys(source));
14823 var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
14824 isFunc = isFunction(object);
14826 arrayEach(methodNames, function(methodName) {
14827 var func = source[methodName];
14828 object[methodName] = func;
14830 object.prototype[methodName] = function() {
14831 var chainAll = this.__chain__;
14832 if (chain || chainAll) {
14833 var result = object(this.__wrapped__),
14834 actions = result.__actions__ = copyArray(this.__actions__);
14836 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
14837 result.__chain__ = chainAll;
14840 return func.apply(object, arrayPush([this.value()], arguments));
14849 * Reverts the `_` variable to its previous value and returns a reference to
14850 * the `lodash` function.
14856 * @returns {Function} Returns the `lodash` function.
14859 * var lodash = _.noConflict();
14861 function noConflict() {
14862 if (root._ === this) {
14869 * A no-operation function that returns `undefined` regardless of the
14870 * arguments it receives.
14878 * var object = { 'user': 'fred' };
14880 * _.noop(object) === undefined;
14884 // No operation performed.
14888 * Creates a function that returns its nth argument. If `n` is negative,
14889 * the nth argument from the end is returned.
14895 * @param {number} [n=0] The index of the argument to return.
14896 * @returns {Function} Returns the new function.
14899 * var func = _.nthArg(1);
14900 * func('a', 'b', 'c', 'd');
14903 * var func = _.nthArg(-2);
14904 * func('a', 'b', 'c', 'd');
14907 function nthArg(n) {
14909 return rest(function(args) {
14910 return baseNth(args, n);
14915 * Creates a function that invokes `iteratees` with the arguments it receives
14916 * and returns their results.
14922 * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])}
14923 * [iteratees=[_.identity]] The iteratees to invoke.
14924 * @returns {Function} Returns the new function.
14927 * var func = _.over(Math.max, Math.min);
14929 * func(1, 2, 3, 4);
14932 var over = createOver(arrayMap);
14935 * Creates a function that checks if **all** of the `predicates` return
14936 * truthy when invoked with the arguments it receives.
14942 * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])}
14943 * [predicates=[_.identity]] The predicates to check.
14944 * @returns {Function} Returns the new function.
14947 * var func = _.overEvery(Boolean, isFinite);
14958 var overEvery = createOver(arrayEvery);
14961 * Creates a function that checks if **any** of the `predicates` return
14962 * truthy when invoked with the arguments it receives.
14968 * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])}
14969 * [predicates=[_.identity]] The predicates to check.
14970 * @returns {Function} Returns the new function.
14973 * var func = _.overSome(Boolean, isFinite);
14984 var overSome = createOver(arraySome);
14987 * Creates a function that returns the value at `path` of a given object.
14993 * @param {Array|string} path The path of the property to get.
14994 * @returns {Function} Returns the new function.
14998 * { 'a': { 'b': 2 } },
14999 * { 'a': { 'b': 1 } }
15002 * _.map(objects, _.property('a.b'));
15005 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
15008 function property(path) {
15009 return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
15013 * The opposite of `_.property`; this method creates a function that returns
15014 * the value at a given path of `object`.
15020 * @param {Object} object The object to query.
15021 * @returns {Function} Returns the new function.
15024 * var array = [0, 1, 2],
15025 * object = { 'a': array, 'b': array, 'c': array };
15027 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
15030 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
15033 function propertyOf(object) {
15034 return function(path) {
15035 return object == null ? undefined : baseGet(object, path);
15040 * Creates an array of numbers (positive and/or negative) progressing from
15041 * `start` up to, but not including, `end`. A step of `-1` is used if a negative
15042 * `start` is specified without an `end` or `step`. If `end` is not specified,
15043 * it's set to `start` with `start` then set to `0`.
15045 * **Note:** JavaScript follows the IEEE-754 standard for resolving
15046 * floating-point values which can produce unexpected results.
15052 * @param {number} [start=0] The start of the range.
15053 * @param {number} end The end of the range.
15054 * @param {number} [step=1] The value to increment or decrement by.
15055 * @returns {Array} Returns the new array of numbers.
15056 * @see _.inRange, _.rangeRight
15060 * // => [0, 1, 2, 3]
15063 * // => [0, -1, -2, -3]
15066 * // => [1, 2, 3, 4]
15068 * _.range(0, 20, 5);
15069 * // => [0, 5, 10, 15]
15071 * _.range(0, -4, -1);
15072 * // => [0, -1, -2, -3]
15074 * _.range(1, 4, 0);
15080 var range = createRange();
15083 * This method is like `_.range` except that it populates values in
15084 * descending order.
15090 * @param {number} [start=0] The start of the range.
15091 * @param {number} end The end of the range.
15092 * @param {number} [step=1] The value to increment or decrement by.
15093 * @returns {Array} Returns the new array of numbers.
15094 * @see _.inRange, _.range
15098 * // => [3, 2, 1, 0]
15100 * _.rangeRight(-4);
15101 * // => [-3, -2, -1, 0]
15103 * _.rangeRight(1, 5);
15104 * // => [4, 3, 2, 1]
15106 * _.rangeRight(0, 20, 5);
15107 * // => [15, 10, 5, 0]
15109 * _.rangeRight(0, -4, -1);
15110 * // => [-3, -2, -1, 0]
15112 * _.rangeRight(1, 4, 0);
15118 var rangeRight = createRange(true);
15121 * Invokes the iteratee `n` times, returning an array of the results of
15122 * each invocation. The iteratee is invoked with one argument; (index).
15128 * @param {number} n The number of times to invoke `iteratee`.
15129 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
15130 * @returns {Array} Returns the array of results.
15133 * _.times(3, String);
15134 * // => ['0', '1', '2']
15136 * _.times(4, _.constant(true));
15137 * // => [true, true, true, true]
15139 function times(n, iteratee) {
15141 if (n < 1 || n > MAX_SAFE_INTEGER) {
15144 var index = MAX_ARRAY_LENGTH,
15145 length = nativeMin(n, MAX_ARRAY_LENGTH);
15147 iteratee = getIteratee(iteratee);
15148 n -= MAX_ARRAY_LENGTH;
15150 var result = baseTimes(length, iteratee);
15151 while (++index < n) {
15158 * Converts `value` to a property path array.
15164 * @param {*} value The value to convert.
15165 * @returns {Array} Returns the new property path array.
15168 * _.toPath('a.b.c');
15169 * // => ['a', 'b', 'c']
15171 * _.toPath('a[0].b.c');
15172 * // => ['a', '0', 'b', 'c']
15174 * var path = ['a', 'b', 'c'],
15175 * newPath = _.toPath(path);
15177 * console.log(newPath);
15178 * // => ['a', 'b', 'c']
15180 * console.log(path === newPath);
15183 function toPath(value) {
15184 if (isArray(value)) {
15185 return arrayMap(value, toKey);
15187 return isSymbol(value) ? [value] : copyArray(stringToPath(value));
15191 * Generates a unique ID. If `prefix` is given, the ID is appended to it.
15197 * @param {string} [prefix=''] The value to prefix the ID with.
15198 * @returns {string} Returns the unique ID.
15201 * _.uniqueId('contact_');
15202 * // => 'contact_104'
15207 function uniqueId(prefix) {
15208 var id = ++idCounter;
15209 return toString(prefix) + id;
15212 /*------------------------------------------------------------------------*/
15215 * Adds two numbers.
15221 * @param {number} augend The first number in an addition.
15222 * @param {number} addend The second number in an addition.
15223 * @returns {number} Returns the total.
15229 var add = createMathOperation(function(augend, addend) {
15230 return augend + addend;
15234 * Computes `number` rounded up to `precision`.
15240 * @param {number} number The number to round up.
15241 * @param {number} [precision=0] The precision to round up to.
15242 * @returns {number} Returns the rounded up number.
15248 * _.ceil(6.004, 2);
15251 * _.ceil(6040, -2);
15254 var ceil = createRound('ceil');
15257 * Divide two numbers.
15263 * @param {number} dividend The first number in a division.
15264 * @param {number} divisor The second number in a division.
15265 * @returns {number} Returns the quotient.
15271 var divide = createMathOperation(function(dividend, divisor) {
15272 return dividend / divisor;
15276 * Computes `number` rounded down to `precision`.
15282 * @param {number} number The number to round down.
15283 * @param {number} [precision=0] The precision to round down to.
15284 * @returns {number} Returns the rounded down number.
15290 * _.floor(0.046, 2);
15293 * _.floor(4060, -2);
15296 var floor = createRound('floor');
15299 * Computes the maximum value of `array`. If `array` is empty or falsey,
15300 * `undefined` is returned.
15306 * @param {Array} array The array to iterate over.
15307 * @returns {*} Returns the maximum value.
15310 * _.max([4, 2, 8, 6]);
15316 function max(array) {
15317 return (array && array.length)
15318 ? baseExtremum(array, identity, baseGt)
15323 * This method is like `_.max` except that it accepts `iteratee` which is
15324 * invoked for each element in `array` to generate the criterion by which
15325 * the value is ranked. The iteratee is invoked with one argument: (value).
15331 * @param {Array} array The array to iterate over.
15332 * @param {Array|Function|Object|string} [iteratee=_.identity]
15333 * The iteratee invoked per element.
15334 * @returns {*} Returns the maximum value.
15337 * var objects = [{ 'n': 1 }, { 'n': 2 }];
15339 * _.maxBy(objects, function(o) { return o.n; });
15342 * // The `_.property` iteratee shorthand.
15343 * _.maxBy(objects, 'n');
15346 function maxBy(array, iteratee) {
15347 return (array && array.length)
15348 ? baseExtremum(array, getIteratee(iteratee), baseGt)
15353 * Computes the mean of the values in `array`.
15359 * @param {Array} array The array to iterate over.
15360 * @returns {number} Returns the mean.
15363 * _.mean([4, 2, 8, 6]);
15366 function mean(array) {
15367 return baseMean(array, identity);
15371 * This method is like `_.mean` except that it accepts `iteratee` which is
15372 * invoked for each element in `array` to generate the value to be averaged.
15373 * The iteratee is invoked with one argument: (value).
15379 * @param {Array} array The array to iterate over.
15380 * @param {Array|Function|Object|string} [iteratee=_.identity]
15381 * The iteratee invoked per element.
15382 * @returns {number} Returns the mean.
15385 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
15387 * _.meanBy(objects, function(o) { return o.n; });
15390 * // The `_.property` iteratee shorthand.
15391 * _.meanBy(objects, 'n');
15394 function meanBy(array, iteratee) {
15395 return baseMean(array, getIteratee(iteratee));
15399 * Computes the minimum value of `array`. If `array` is empty or falsey,
15400 * `undefined` is returned.
15406 * @param {Array} array The array to iterate over.
15407 * @returns {*} Returns the minimum value.
15410 * _.min([4, 2, 8, 6]);
15416 function min(array) {
15417 return (array && array.length)
15418 ? baseExtremum(array, identity, baseLt)
15423 * This method is like `_.min` except that it accepts `iteratee` which is
15424 * invoked for each element in `array` to generate the criterion by which
15425 * the value is ranked. The iteratee is invoked with one argument: (value).
15431 * @param {Array} array The array to iterate over.
15432 * @param {Array|Function|Object|string} [iteratee=_.identity]
15433 * The iteratee invoked per element.
15434 * @returns {*} Returns the minimum value.
15437 * var objects = [{ 'n': 1 }, { 'n': 2 }];
15439 * _.minBy(objects, function(o) { return o.n; });
15442 * // The `_.property` iteratee shorthand.
15443 * _.minBy(objects, 'n');
15446 function minBy(array, iteratee) {
15447 return (array && array.length)
15448 ? baseExtremum(array, getIteratee(iteratee), baseLt)
15453 * Multiply two numbers.
15459 * @param {number} multiplier The first number in a multiplication.
15460 * @param {number} multiplicand The second number in a multiplication.
15461 * @returns {number} Returns the product.
15464 * _.multiply(6, 4);
15467 var multiply = createMathOperation(function(multiplier, multiplicand) {
15468 return multiplier * multiplicand;
15472 * Computes `number` rounded to `precision`.
15478 * @param {number} number The number to round.
15479 * @param {number} [precision=0] The precision to round to.
15480 * @returns {number} Returns the rounded number.
15486 * _.round(4.006, 2);
15489 * _.round(4060, -2);
15492 var round = createRound('round');
15495 * Subtract two numbers.
15501 * @param {number} minuend The first number in a subtraction.
15502 * @param {number} subtrahend The second number in a subtraction.
15503 * @returns {number} Returns the difference.
15506 * _.subtract(6, 4);
15509 var subtract = createMathOperation(function(minuend, subtrahend) {
15510 return minuend - subtrahend;
15514 * Computes the sum of the values in `array`.
15520 * @param {Array} array The array to iterate over.
15521 * @returns {number} Returns the sum.
15524 * _.sum([4, 2, 8, 6]);
15527 function sum(array) {
15528 return (array && array.length)
15529 ? baseSum(array, identity)
15534 * This method is like `_.sum` except that it accepts `iteratee` which is
15535 * invoked for each element in `array` to generate the value to be summed.
15536 * The iteratee is invoked with one argument: (value).
15542 * @param {Array} array The array to iterate over.
15543 * @param {Array|Function|Object|string} [iteratee=_.identity]
15544 * The iteratee invoked per element.
15545 * @returns {number} Returns the sum.
15548 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
15550 * _.sumBy(objects, function(o) { return o.n; });
15553 * // The `_.property` iteratee shorthand.
15554 * _.sumBy(objects, 'n');
15557 function sumBy(array, iteratee) {
15558 return (array && array.length)
15559 ? baseSum(array, getIteratee(iteratee))
15563 /*------------------------------------------------------------------------*/
15565 // Add methods that return wrapped values in chain sequences.
15566 lodash.after = after;
15568 lodash.assign = assign;
15569 lodash.assignIn = assignIn;
15570 lodash.assignInWith = assignInWith;
15571 lodash.assignWith = assignWith;
15573 lodash.before = before;
15574 lodash.bind = bind;
15575 lodash.bindAll = bindAll;
15576 lodash.bindKey = bindKey;
15577 lodash.castArray = castArray;
15578 lodash.chain = chain;
15579 lodash.chunk = chunk;
15580 lodash.compact = compact;
15581 lodash.concat = concat;
15582 lodash.cond = cond;
15583 lodash.conforms = conforms;
15584 lodash.constant = constant;
15585 lodash.countBy = countBy;
15586 lodash.create = create;
15587 lodash.curry = curry;
15588 lodash.curryRight = curryRight;
15589 lodash.debounce = debounce;
15590 lodash.defaults = defaults;
15591 lodash.defaultsDeep = defaultsDeep;
15592 lodash.defer = defer;
15593 lodash.delay = delay;
15594 lodash.difference = difference;
15595 lodash.differenceBy = differenceBy;
15596 lodash.differenceWith = differenceWith;
15597 lodash.drop = drop;
15598 lodash.dropRight = dropRight;
15599 lodash.dropRightWhile = dropRightWhile;
15600 lodash.dropWhile = dropWhile;
15601 lodash.fill = fill;
15602 lodash.filter = filter;
15603 lodash.flatMap = flatMap;
15604 lodash.flatMapDeep = flatMapDeep;
15605 lodash.flatMapDepth = flatMapDepth;
15606 lodash.flatten = flatten;
15607 lodash.flattenDeep = flattenDeep;
15608 lodash.flattenDepth = flattenDepth;
15609 lodash.flip = flip;
15610 lodash.flow = flow;
15611 lodash.flowRight = flowRight;
15612 lodash.fromPairs = fromPairs;
15613 lodash.functions = functions;
15614 lodash.functionsIn = functionsIn;
15615 lodash.groupBy = groupBy;
15616 lodash.initial = initial;
15617 lodash.intersection = intersection;
15618 lodash.intersectionBy = intersectionBy;
15619 lodash.intersectionWith = intersectionWith;
15620 lodash.invert = invert;
15621 lodash.invertBy = invertBy;
15622 lodash.invokeMap = invokeMap;
15623 lodash.iteratee = iteratee;
15624 lodash.keyBy = keyBy;
15625 lodash.keys = keys;
15626 lodash.keysIn = keysIn;
15628 lodash.mapKeys = mapKeys;
15629 lodash.mapValues = mapValues;
15630 lodash.matches = matches;
15631 lodash.matchesProperty = matchesProperty;
15632 lodash.memoize = memoize;
15633 lodash.merge = merge;
15634 lodash.mergeWith = mergeWith;
15635 lodash.method = method;
15636 lodash.methodOf = methodOf;
15637 lodash.mixin = mixin;
15638 lodash.negate = negate;
15639 lodash.nthArg = nthArg;
15640 lodash.omit = omit;
15641 lodash.omitBy = omitBy;
15642 lodash.once = once;
15643 lodash.orderBy = orderBy;
15644 lodash.over = over;
15645 lodash.overArgs = overArgs;
15646 lodash.overEvery = overEvery;
15647 lodash.overSome = overSome;
15648 lodash.partial = partial;
15649 lodash.partialRight = partialRight;
15650 lodash.partition = partition;
15651 lodash.pick = pick;
15652 lodash.pickBy = pickBy;
15653 lodash.property = property;
15654 lodash.propertyOf = propertyOf;
15655 lodash.pull = pull;
15656 lodash.pullAll = pullAll;
15657 lodash.pullAllBy = pullAllBy;
15658 lodash.pullAllWith = pullAllWith;
15659 lodash.pullAt = pullAt;
15660 lodash.range = range;
15661 lodash.rangeRight = rangeRight;
15662 lodash.rearg = rearg;
15663 lodash.reject = reject;
15664 lodash.remove = remove;
15665 lodash.rest = rest;
15666 lodash.reverse = reverse;
15667 lodash.sampleSize = sampleSize;
15669 lodash.setWith = setWith;
15670 lodash.shuffle = shuffle;
15671 lodash.slice = slice;
15672 lodash.sortBy = sortBy;
15673 lodash.sortedUniq = sortedUniq;
15674 lodash.sortedUniqBy = sortedUniqBy;
15675 lodash.split = split;
15676 lodash.spread = spread;
15677 lodash.tail = tail;
15678 lodash.take = take;
15679 lodash.takeRight = takeRight;
15680 lodash.takeRightWhile = takeRightWhile;
15681 lodash.takeWhile = takeWhile;
15683 lodash.throttle = throttle;
15684 lodash.thru = thru;
15685 lodash.toArray = toArray;
15686 lodash.toPairs = toPairs;
15687 lodash.toPairsIn = toPairsIn;
15688 lodash.toPath = toPath;
15689 lodash.toPlainObject = toPlainObject;
15690 lodash.transform = transform;
15691 lodash.unary = unary;
15692 lodash.union = union;
15693 lodash.unionBy = unionBy;
15694 lodash.unionWith = unionWith;
15695 lodash.uniq = uniq;
15696 lodash.uniqBy = uniqBy;
15697 lodash.uniqWith = uniqWith;
15698 lodash.unset = unset;
15699 lodash.unzip = unzip;
15700 lodash.unzipWith = unzipWith;
15701 lodash.update = update;
15702 lodash.updateWith = updateWith;
15703 lodash.values = values;
15704 lodash.valuesIn = valuesIn;
15705 lodash.without = without;
15706 lodash.words = words;
15707 lodash.wrap = wrap;
15709 lodash.xorBy = xorBy;
15710 lodash.xorWith = xorWith;
15712 lodash.zipObject = zipObject;
15713 lodash.zipObjectDeep = zipObjectDeep;
15714 lodash.zipWith = zipWith;
15717 lodash.entries = toPairs;
15718 lodash.entriesIn = toPairsIn;
15719 lodash.extend = assignIn;
15720 lodash.extendWith = assignInWith;
15722 // Add methods to `lodash.prototype`.
15723 mixin(lodash, lodash);
15725 /*------------------------------------------------------------------------*/
15727 // Add methods that return unwrapped values in chain sequences.
15729 lodash.attempt = attempt;
15730 lodash.camelCase = camelCase;
15731 lodash.capitalize = capitalize;
15732 lodash.ceil = ceil;
15733 lodash.clamp = clamp;
15734 lodash.clone = clone;
15735 lodash.cloneDeep = cloneDeep;
15736 lodash.cloneDeepWith = cloneDeepWith;
15737 lodash.cloneWith = cloneWith;
15738 lodash.deburr = deburr;
15739 lodash.divide = divide;
15740 lodash.endsWith = endsWith;
15742 lodash.escape = escape;
15743 lodash.escapeRegExp = escapeRegExp;
15744 lodash.every = every;
15745 lodash.find = find;
15746 lodash.findIndex = findIndex;
15747 lodash.findKey = findKey;
15748 lodash.findLast = findLast;
15749 lodash.findLastIndex = findLastIndex;
15750 lodash.findLastKey = findLastKey;
15751 lodash.floor = floor;
15752 lodash.forEach = forEach;
15753 lodash.forEachRight = forEachRight;
15754 lodash.forIn = forIn;
15755 lodash.forInRight = forInRight;
15756 lodash.forOwn = forOwn;
15757 lodash.forOwnRight = forOwnRight;
15762 lodash.hasIn = hasIn;
15763 lodash.head = head;
15764 lodash.identity = identity;
15765 lodash.includes = includes;
15766 lodash.indexOf = indexOf;
15767 lodash.inRange = inRange;
15768 lodash.invoke = invoke;
15769 lodash.isArguments = isArguments;
15770 lodash.isArray = isArray;
15771 lodash.isArrayBuffer = isArrayBuffer;
15772 lodash.isArrayLike = isArrayLike;
15773 lodash.isArrayLikeObject = isArrayLikeObject;
15774 lodash.isBoolean = isBoolean;
15775 lodash.isBuffer = isBuffer;
15776 lodash.isDate = isDate;
15777 lodash.isElement = isElement;
15778 lodash.isEmpty = isEmpty;
15779 lodash.isEqual = isEqual;
15780 lodash.isEqualWith = isEqualWith;
15781 lodash.isError = isError;
15782 lodash.isFinite = isFinite;
15783 lodash.isFunction = isFunction;
15784 lodash.isInteger = isInteger;
15785 lodash.isLength = isLength;
15786 lodash.isMap = isMap;
15787 lodash.isMatch = isMatch;
15788 lodash.isMatchWith = isMatchWith;
15789 lodash.isNaN = isNaN;
15790 lodash.isNative = isNative;
15791 lodash.isNil = isNil;
15792 lodash.isNull = isNull;
15793 lodash.isNumber = isNumber;
15794 lodash.isObject = isObject;
15795 lodash.isObjectLike = isObjectLike;
15796 lodash.isPlainObject = isPlainObject;
15797 lodash.isRegExp = isRegExp;
15798 lodash.isSafeInteger = isSafeInteger;
15799 lodash.isSet = isSet;
15800 lodash.isString = isString;
15801 lodash.isSymbol = isSymbol;
15802 lodash.isTypedArray = isTypedArray;
15803 lodash.isUndefined = isUndefined;
15804 lodash.isWeakMap = isWeakMap;
15805 lodash.isWeakSet = isWeakSet;
15806 lodash.join = join;
15807 lodash.kebabCase = kebabCase;
15808 lodash.last = last;
15809 lodash.lastIndexOf = lastIndexOf;
15810 lodash.lowerCase = lowerCase;
15811 lodash.lowerFirst = lowerFirst;
15815 lodash.maxBy = maxBy;
15816 lodash.mean = mean;
15817 lodash.meanBy = meanBy;
15819 lodash.minBy = minBy;
15820 lodash.multiply = multiply;
15822 lodash.noConflict = noConflict;
15823 lodash.noop = noop;
15826 lodash.padEnd = padEnd;
15827 lodash.padStart = padStart;
15828 lodash.parseInt = parseInt;
15829 lodash.random = random;
15830 lodash.reduce = reduce;
15831 lodash.reduceRight = reduceRight;
15832 lodash.repeat = repeat;
15833 lodash.replace = replace;
15834 lodash.result = result;
15835 lodash.round = round;
15836 lodash.runInContext = runInContext;
15837 lodash.sample = sample;
15838 lodash.size = size;
15839 lodash.snakeCase = snakeCase;
15840 lodash.some = some;
15841 lodash.sortedIndex = sortedIndex;
15842 lodash.sortedIndexBy = sortedIndexBy;
15843 lodash.sortedIndexOf = sortedIndexOf;
15844 lodash.sortedLastIndex = sortedLastIndex;
15845 lodash.sortedLastIndexBy = sortedLastIndexBy;
15846 lodash.sortedLastIndexOf = sortedLastIndexOf;
15847 lodash.startCase = startCase;
15848 lodash.startsWith = startsWith;
15849 lodash.subtract = subtract;
15851 lodash.sumBy = sumBy;
15852 lodash.template = template;
15853 lodash.times = times;
15854 lodash.toInteger = toInteger;
15855 lodash.toLength = toLength;
15856 lodash.toLower = toLower;
15857 lodash.toNumber = toNumber;
15858 lodash.toSafeInteger = toSafeInteger;
15859 lodash.toString = toString;
15860 lodash.toUpper = toUpper;
15861 lodash.trim = trim;
15862 lodash.trimEnd = trimEnd;
15863 lodash.trimStart = trimStart;
15864 lodash.truncate = truncate;
15865 lodash.unescape = unescape;
15866 lodash.uniqueId = uniqueId;
15867 lodash.upperCase = upperCase;
15868 lodash.upperFirst = upperFirst;
15871 lodash.each = forEach;
15872 lodash.eachRight = forEachRight;
15873 lodash.first = head;
15875 mixin(lodash, (function() {
15877 baseForOwn(lodash, function(func, methodName) {
15878 if (!hasOwnProperty.call(lodash.prototype, methodName)) {
15879 source[methodName] = func;
15883 }()), { 'chain': false });
15885 /*------------------------------------------------------------------------*/
15888 * The semantic version number.
15894 lodash.VERSION = VERSION;
15896 // Assign default placeholders.
15897 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
15898 lodash[methodName].placeholder = lodash;
15901 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
15902 arrayEach(['drop', 'take'], function(methodName, index) {
15903 LazyWrapper.prototype[methodName] = function(n) {
15904 var filtered = this.__filtered__;
15905 if (filtered && !index) {
15906 return new LazyWrapper(this);
15908 n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
15910 var result = this.clone();
15912 result.__takeCount__ = nativeMin(n, result.__takeCount__);
15914 result.__views__.push({
15915 'size': nativeMin(n, MAX_ARRAY_LENGTH),
15916 'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
15922 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
15923 return this.reverse()[methodName](n).reverse();
15927 // Add `LazyWrapper` methods that accept an `iteratee` value.
15928 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
15929 var type = index + 1,
15930 isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
15932 LazyWrapper.prototype[methodName] = function(iteratee) {
15933 var result = this.clone();
15934 result.__iteratees__.push({
15935 'iteratee': getIteratee(iteratee, 3),
15938 result.__filtered__ = result.__filtered__ || isFilter;
15943 // Add `LazyWrapper` methods for `_.head` and `_.last`.
15944 arrayEach(['head', 'last'], function(methodName, index) {
15945 var takeName = 'take' + (index ? 'Right' : '');
15947 LazyWrapper.prototype[methodName] = function() {
15948 return this[takeName](1).value()[0];
15952 // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
15953 arrayEach(['initial', 'tail'], function(methodName, index) {
15954 var dropName = 'drop' + (index ? '' : 'Right');
15956 LazyWrapper.prototype[methodName] = function() {
15957 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
15961 LazyWrapper.prototype.compact = function() {
15962 return this.filter(identity);
15965 LazyWrapper.prototype.find = function(predicate) {
15966 return this.filter(predicate).head();
15969 LazyWrapper.prototype.findLast = function(predicate) {
15970 return this.reverse().find(predicate);
15973 LazyWrapper.prototype.invokeMap = rest(function(path, args) {
15974 if (typeof path == 'function') {
15975 return new LazyWrapper(this);
15977 return this.map(function(value) {
15978 return baseInvoke(value, path, args);
15982 LazyWrapper.prototype.reject = function(predicate) {
15983 predicate = getIteratee(predicate, 3);
15984 return this.filter(function(value) {
15985 return !predicate(value);
15989 LazyWrapper.prototype.slice = function(start, end) {
15990 start = toInteger(start);
15993 if (result.__filtered__ && (start > 0 || end < 0)) {
15994 return new LazyWrapper(result);
15997 result = result.takeRight(-start);
15998 } else if (start) {
15999 result = result.drop(start);
16001 if (end !== undefined) {
16002 end = toInteger(end);
16003 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
16008 LazyWrapper.prototype.takeRightWhile = function(predicate) {
16009 return this.reverse().takeWhile(predicate).reverse();
16012 LazyWrapper.prototype.toArray = function() {
16013 return this.take(MAX_ARRAY_LENGTH);
16016 // Add `LazyWrapper` methods to `lodash.prototype`.
16017 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
16018 var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
16019 isTaker = /^(?:head|last)$/.test(methodName),
16020 lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
16021 retUnwrapped = isTaker || /^find/.test(methodName);
16026 lodash.prototype[methodName] = function() {
16027 var value = this.__wrapped__,
16028 args = isTaker ? [1] : arguments,
16029 isLazy = value instanceof LazyWrapper,
16030 iteratee = args[0],
16031 useLazy = isLazy || isArray(value);
16033 var interceptor = function(value) {
16034 var result = lodashFunc.apply(lodash, arrayPush([value], args));
16035 return (isTaker && chainAll) ? result[0] : result;
16038 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
16039 // Avoid lazy use if the iteratee has a "length" value other than `1`.
16040 isLazy = useLazy = false;
16042 var chainAll = this.__chain__,
16043 isHybrid = !!this.__actions__.length,
16044 isUnwrapped = retUnwrapped && !chainAll,
16045 onlyLazy = isLazy && !isHybrid;
16047 if (!retUnwrapped && useLazy) {
16048 value = onlyLazy ? value : new LazyWrapper(this);
16049 var result = func.apply(value, args);
16050 result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
16051 return new LodashWrapper(result, chainAll);
16053 if (isUnwrapped && onlyLazy) {
16054 return func.apply(this, args);
16056 result = this.thru(interceptor);
16057 return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
16061 // Add `Array` methods to `lodash.prototype`.
16062 arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
16063 var func = arrayProto[methodName],
16064 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
16065 retUnwrapped = /^(?:pop|shift)$/.test(methodName);
16067 lodash.prototype[methodName] = function() {
16068 var args = arguments;
16069 if (retUnwrapped && !this.__chain__) {
16070 var value = this.value();
16071 return func.apply(isArray(value) ? value : [], args);
16073 return this[chainName](function(value) {
16074 return func.apply(isArray(value) ? value : [], args);
16079 // Map minified method names to their real names.
16080 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
16081 var lodashFunc = lodash[methodName];
16083 var key = (lodashFunc.name + ''),
16084 names = realNames[key] || (realNames[key] = []);
16086 names.push({ 'name': methodName, 'func': lodashFunc });
16090 realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{
16095 // Add methods to `LazyWrapper`.
16096 LazyWrapper.prototype.clone = lazyClone;
16097 LazyWrapper.prototype.reverse = lazyReverse;
16098 LazyWrapper.prototype.value = lazyValue;
16100 // Add chain sequence methods to the `lodash` wrapper.
16101 lodash.prototype.at = wrapperAt;
16102 lodash.prototype.chain = wrapperChain;
16103 lodash.prototype.commit = wrapperCommit;
16104 lodash.prototype.next = wrapperNext;
16105 lodash.prototype.plant = wrapperPlant;
16106 lodash.prototype.reverse = wrapperReverse;
16107 lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
16109 if (iteratorSymbol) {
16110 lodash.prototype[iteratorSymbol] = wrapperToIterator;
16115 /*--------------------------------------------------------------------------*/
16118 var _ = runInContext();
16120 // Expose Lodash on the free variable `window` or `self` when available so it's
16121 // globally accessible, even when bundled with Browserify, Webpack, etc. This
16122 // also prevents errors in cases where Lodash is loaded by a script tag in the
16123 // presence of an AMD loader. See http://requirejs.org/docs/errors.html#mismatch
16124 // for more details. Use `_.noConflict` to remove Lodash from the global object.
16125 (freeWindow || freeSelf || {})._ = _;
16127 // Some AMD build optimizers like r.js check for condition patterns like the following:
16128 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
16129 // Define as an anonymous module so, through path mapping, it can be
16130 // referenced as the "underscore" module.
16131 define(function() {
16135 // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
16136 else if (freeExports && freeModule) {
16137 // Export for Node.js.
16138 if (moduleExports) {
16139 (freeModule.exports = _)._ = _;
16141 // Export for CommonJS support.
16145 // Export to the global object.