Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80736 views
1
/**
2
* @license
3
* lodash 3.9.3 (Custom Build) <https://lodash.com/>
4
* Build: `lodash modern -d -o ./index.js`
5
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
6
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
7
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
8
* Available under MIT license <https://lodash.com/license>
9
*/
10
;(function() {
11
12
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
13
var undefined;
14
15
/** Used as the semantic version number. */
16
var VERSION = '3.9.3';
17
18
/** Used to compose bitmasks for wrapper metadata. */
19
var BIND_FLAG = 1,
20
BIND_KEY_FLAG = 2,
21
CURRY_BOUND_FLAG = 4,
22
CURRY_FLAG = 8,
23
CURRY_RIGHT_FLAG = 16,
24
PARTIAL_FLAG = 32,
25
PARTIAL_RIGHT_FLAG = 64,
26
ARY_FLAG = 128,
27
REARG_FLAG = 256;
28
29
/** Used as default options for `_.trunc`. */
30
var DEFAULT_TRUNC_LENGTH = 30,
31
DEFAULT_TRUNC_OMISSION = '...';
32
33
/** Used to detect when a function becomes hot. */
34
var HOT_COUNT = 150,
35
HOT_SPAN = 16;
36
37
/** Used to indicate the type of lazy iteratees. */
38
var LAZY_DROP_WHILE_FLAG = 0,
39
LAZY_FILTER_FLAG = 1,
40
LAZY_MAP_FLAG = 2;
41
42
/** Used as the `TypeError` message for "Functions" methods. */
43
var FUNC_ERROR_TEXT = 'Expected a function';
44
45
/** Used as the internal argument placeholder. */
46
var PLACEHOLDER = '__lodash_placeholder__';
47
48
/** `Object#toString` result references. */
49
var argsTag = '[object Arguments]',
50
arrayTag = '[object Array]',
51
boolTag = '[object Boolean]',
52
dateTag = '[object Date]',
53
errorTag = '[object Error]',
54
funcTag = '[object Function]',
55
mapTag = '[object Map]',
56
numberTag = '[object Number]',
57
objectTag = '[object Object]',
58
regexpTag = '[object RegExp]',
59
setTag = '[object Set]',
60
stringTag = '[object String]',
61
weakMapTag = '[object WeakMap]';
62
63
var arrayBufferTag = '[object ArrayBuffer]',
64
float32Tag = '[object Float32Array]',
65
float64Tag = '[object Float64Array]',
66
int8Tag = '[object Int8Array]',
67
int16Tag = '[object Int16Array]',
68
int32Tag = '[object Int32Array]',
69
uint8Tag = '[object Uint8Array]',
70
uint8ClampedTag = '[object Uint8ClampedArray]',
71
uint16Tag = '[object Uint16Array]',
72
uint32Tag = '[object Uint32Array]';
73
74
/** Used to match empty string literals in compiled template source. */
75
var reEmptyStringLeading = /\b__p \+= '';/g,
76
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
77
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
78
79
/** Used to match HTML entities and HTML characters. */
80
var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
81
reUnescapedHtml = /[&<>"'`]/g,
82
reHasEscapedHtml = RegExp(reEscapedHtml.source),
83
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
84
85
/** Used to match template delimiters. */
86
var reEscape = /<%-([\s\S]+?)%>/g,
87
reEvaluate = /<%([\s\S]+?)%>/g,
88
reInterpolate = /<%=([\s\S]+?)%>/g;
89
90
/** Used to match property names within property paths. */
91
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
92
reIsPlainProp = /^\w*$/,
93
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
94
95
/**
96
* Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special).
97
* In addition to special characters the forward slash is escaped to allow for
98
* easier `eval` use and `Function` compilation.
99
*/
100
var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g,
101
reHasRegExpChars = RegExp(reRegExpChars.source);
102
103
/** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */
104
var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g;
105
106
/** Used to match backslashes in property paths. */
107
var reEscapeChar = /\\(\\)?/g;
108
109
/** Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components). */
110
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
111
112
/** Used to match `RegExp` flags from their coerced string values. */
113
var reFlags = /\w*$/;
114
115
/** Used to detect hexadecimal string values. */
116
var reHasHexPrefix = /^0[xX]/;
117
118
/** Used to detect host constructors (Safari > 5). */
119
var reIsHostCtor = /^\[object .+?Constructor\]$/;
120
121
/** Used to detect unsigned integer values. */
122
var reIsUint = /^\d+$/;
123
124
/** Used to match latin-1 supplementary letters (excluding mathematical operators). */
125
var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
126
127
/** Used to ensure capturing order of template delimiters. */
128
var reNoMatch = /($^)/;
129
130
/** Used to match unescaped characters in compiled string literals. */
131
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
132
133
/** Used to match words to create compound words. */
134
var reWords = (function() {
135
var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
136
lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
137
138
return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
139
}());
140
141
/** Used to detect and test for whitespace. */
142
var whitespace = (
143
// Basic whitespace characters.
144
' \t\x0b\f\xa0\ufeff' +
145
146
// Line terminators.
147
'\n\r\u2028\u2029' +
148
149
// Unicode category "Zs" space separators.
150
'\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
151
);
152
153
/** Used to assign default `context` object properties. */
154
var contextProps = [
155
'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
156
'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
157
'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'document',
158
'isFinite', 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
159
'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', 'window'
160
];
161
162
/** Used to make template sourceURLs easier to identify. */
163
var templateCounter = -1;
164
165
/** Used to identify `toStringTag` values of typed arrays. */
166
var typedArrayTags = {};
167
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
168
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
169
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
170
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
171
typedArrayTags[uint32Tag] = true;
172
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
173
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
174
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
175
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
176
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
177
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
178
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
179
180
/** Used to identify `toStringTag` values supported by `_.clone`. */
181
var cloneableTags = {};
182
cloneableTags[argsTag] = cloneableTags[arrayTag] =
183
cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
184
cloneableTags[dateTag] = cloneableTags[float32Tag] =
185
cloneableTags[float64Tag] = cloneableTags[int8Tag] =
186
cloneableTags[int16Tag] = cloneableTags[int32Tag] =
187
cloneableTags[numberTag] = cloneableTags[objectTag] =
188
cloneableTags[regexpTag] = cloneableTags[stringTag] =
189
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
190
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
191
cloneableTags[errorTag] = cloneableTags[funcTag] =
192
cloneableTags[mapTag] = cloneableTags[setTag] =
193
cloneableTags[weakMapTag] = false;
194
195
/** Used as an internal `_.debounce` options object by `_.throttle`. */
196
var debounceOptions = {
197
'leading': false,
198
'maxWait': 0,
199
'trailing': false
200
};
201
202
/** Used to map latin-1 supplementary letters to basic latin letters. */
203
var deburredLetters = {
204
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
205
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
206
'\xc7': 'C', '\xe7': 'c',
207
'\xd0': 'D', '\xf0': 'd',
208
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
209
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
210
'\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
211
'\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
212
'\xd1': 'N', '\xf1': 'n',
213
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
214
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
215
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
216
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
217
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
218
'\xc6': 'Ae', '\xe6': 'ae',
219
'\xde': 'Th', '\xfe': 'th',
220
'\xdf': 'ss'
221
};
222
223
/** Used to map characters to HTML entities. */
224
var htmlEscapes = {
225
'&': '&amp;',
226
'<': '&lt;',
227
'>': '&gt;',
228
'"': '&quot;',
229
"'": '&#39;',
230
'`': '&#96;'
231
};
232
233
/** Used to map HTML entities to characters. */
234
var htmlUnescapes = {
235
'&amp;': '&',
236
'&lt;': '<',
237
'&gt;': '>',
238
'&quot;': '"',
239
'&#39;': "'",
240
'&#96;': '`'
241
};
242
243
/** Used to determine if values are of the language type `Object`. */
244
var objectTypes = {
245
'function': true,
246
'object': true
247
};
248
249
/** Used to escape characters for inclusion in compiled string literals. */
250
var stringEscapes = {
251
'\\': '\\',
252
"'": "'",
253
'\n': 'n',
254
'\r': 'r',
255
'\u2028': 'u2028',
256
'\u2029': 'u2029'
257
};
258
259
/** Detect free variable `exports`. */
260
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
261
262
/** Detect free variable `module`. */
263
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
264
265
/** Detect free variable `global` from Node.js. */
266
var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
267
268
/** Detect free variable `self`. */
269
var freeSelf = objectTypes[typeof self] && self && self.Object && self;
270
271
/** Detect free variable `window`. */
272
var freeWindow = objectTypes[typeof window] && window && window.Object && window;
273
274
/** Detect the popular CommonJS extension `module.exports`. */
275
var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
276
277
/**
278
* Used as a reference to the global object.
279
*
280
* The `this` value is used if it's the global object to avoid Greasemonkey's
281
* restricted `window` object, otherwise the `window` object is used.
282
*/
283
var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
284
285
/*--------------------------------------------------------------------------*/
286
287
/**
288
* The base implementation of `compareAscending` which compares values and
289
* sorts them in ascending order without guaranteeing a stable sort.
290
*
291
* @private
292
* @param {*} value The value to compare.
293
* @param {*} other The other value to compare.
294
* @returns {number} Returns the sort order indicator for `value`.
295
*/
296
function baseCompareAscending(value, other) {
297
if (value !== other) {
298
var valIsNull = value === null,
299
valIsUndef = value === undefined,
300
valIsReflexive = value === value;
301
302
var othIsNull = other === null,
303
othIsUndef = other === undefined,
304
othIsReflexive = other === other;
305
306
if ((value > other && !othIsNull) || !valIsReflexive ||
307
(valIsNull && !othIsUndef && othIsReflexive) ||
308
(valIsUndef && othIsReflexive)) {
309
return 1;
310
}
311
if ((value < other && !valIsNull) || !othIsReflexive ||
312
(othIsNull && !valIsUndef && valIsReflexive) ||
313
(othIsUndef && valIsReflexive)) {
314
return -1;
315
}
316
}
317
return 0;
318
}
319
320
/**
321
* The base implementation of `_.findIndex` and `_.findLastIndex` without
322
* support for callback shorthands and `this` binding.
323
*
324
* @private
325
* @param {Array} array The array to search.
326
* @param {Function} predicate The function invoked per iteration.
327
* @param {boolean} [fromRight] Specify iterating from right to left.
328
* @returns {number} Returns the index of the matched value, else `-1`.
329
*/
330
function baseFindIndex(array, predicate, fromRight) {
331
var length = array.length,
332
index = fromRight ? length : -1;
333
334
while ((fromRight ? index-- : ++index < length)) {
335
if (predicate(array[index], index, array)) {
336
return index;
337
}
338
}
339
return -1;
340
}
341
342
/**
343
* The base implementation of `_.indexOf` without support for binary searches.
344
*
345
* @private
346
* @param {Array} array The array to search.
347
* @param {*} value The value to search for.
348
* @param {number} fromIndex The index to search from.
349
* @returns {number} Returns the index of the matched value, else `-1`.
350
*/
351
function baseIndexOf(array, value, fromIndex) {
352
if (value !== value) {
353
return indexOfNaN(array, fromIndex);
354
}
355
var index = fromIndex - 1,
356
length = array.length;
357
358
while (++index < length) {
359
if (array[index] === value) {
360
return index;
361
}
362
}
363
return -1;
364
}
365
366
/**
367
* The base implementation of `_.isFunction` without support for environments
368
* with incorrect `typeof` results.
369
*
370
* @private
371
* @param {*} value The value to check.
372
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
373
*/
374
function baseIsFunction(value) {
375
// Avoid a Chakra JIT bug in compatibility modes of IE 11.
376
// See https://github.com/jashkenas/underscore/issues/1621 for more details.
377
return typeof value == 'function' || false;
378
}
379
380
/**
381
* Converts `value` to a string if it's not one. An empty string is returned
382
* for `null` or `undefined` values.
383
*
384
* @private
385
* @param {*} value The value to process.
386
* @returns {string} Returns the string.
387
*/
388
function baseToString(value) {
389
if (typeof value == 'string') {
390
return value;
391
}
392
return value == null ? '' : (value + '');
393
}
394
395
/**
396
* Used by `_.trim` and `_.trimLeft` to get the index of the first character
397
* of `string` that is not found in `chars`.
398
*
399
* @private
400
* @param {string} string The string to inspect.
401
* @param {string} chars The characters to find.
402
* @returns {number} Returns the index of the first character not found in `chars`.
403
*/
404
function charsLeftIndex(string, chars) {
405
var index = -1,
406
length = string.length;
407
408
while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
409
return index;
410
}
411
412
/**
413
* Used by `_.trim` and `_.trimRight` to get the index of the last character
414
* of `string` that is not found in `chars`.
415
*
416
* @private
417
* @param {string} string The string to inspect.
418
* @param {string} chars The characters to find.
419
* @returns {number} Returns the index of the last character not found in `chars`.
420
*/
421
function charsRightIndex(string, chars) {
422
var index = string.length;
423
424
while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
425
return index;
426
}
427
428
/**
429
* Used by `_.sortBy` to compare transformed elements of a collection and stable
430
* sort them in ascending order.
431
*
432
* @private
433
* @param {Object} object The object to compare to `other`.
434
* @param {Object} other The object to compare to `object`.
435
* @returns {number} Returns the sort order indicator for `object`.
436
*/
437
function compareAscending(object, other) {
438
return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
439
}
440
441
/**
442
* Used by `_.sortByOrder` to compare multiple properties of each element
443
* in a collection and stable sort them in the following order:
444
*
445
* If `orders` is unspecified, sort in ascending order for all properties.
446
* Otherwise, for each property, sort in ascending order if its corresponding value in
447
* orders is true, and descending order if false.
448
*
449
* @private
450
* @param {Object} object The object to compare to `other`.
451
* @param {Object} other The object to compare to `object`.
452
* @param {boolean[]} orders The order to sort by for each property.
453
* @returns {number} Returns the sort order indicator for `object`.
454
*/
455
function compareMultiple(object, other, orders) {
456
var index = -1,
457
objCriteria = object.criteria,
458
othCriteria = other.criteria,
459
length = objCriteria.length,
460
ordersLength = orders.length;
461
462
while (++index < length) {
463
var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
464
if (result) {
465
if (index >= ordersLength) {
466
return result;
467
}
468
return result * (orders[index] ? 1 : -1);
469
}
470
}
471
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
472
// that causes it, under certain circumstances, to provide the same value for
473
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
474
// for more details.
475
//
476
// This also ensures a stable sort in V8 and other engines.
477
// See https://code.google.com/p/v8/issues/detail?id=90 for more details.
478
return object.index - other.index;
479
}
480
481
/**
482
* Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
483
*
484
* @private
485
* @param {string} letter The matched letter to deburr.
486
* @returns {string} Returns the deburred letter.
487
*/
488
function deburrLetter(letter) {
489
return deburredLetters[letter];
490
}
491
492
/**
493
* Used by `_.escape` to convert characters to HTML entities.
494
*
495
* @private
496
* @param {string} chr The matched character to escape.
497
* @returns {string} Returns the escaped character.
498
*/
499
function escapeHtmlChar(chr) {
500
return htmlEscapes[chr];
501
}
502
503
/**
504
* Used by `_.template` to escape characters for inclusion in compiled
505
* string literals.
506
*
507
* @private
508
* @param {string} chr The matched character to escape.
509
* @returns {string} Returns the escaped character.
510
*/
511
function escapeStringChar(chr) {
512
return '\\' + stringEscapes[chr];
513
}
514
515
/**
516
* Gets the index at which the first occurrence of `NaN` is found in `array`.
517
*
518
* @private
519
* @param {Array} array The array to search.
520
* @param {number} fromIndex The index to search from.
521
* @param {boolean} [fromRight] Specify iterating from right to left.
522
* @returns {number} Returns the index of the matched `NaN`, else `-1`.
523
*/
524
function indexOfNaN(array, fromIndex, fromRight) {
525
var length = array.length,
526
index = fromIndex + (fromRight ? 0 : -1);
527
528
while ((fromRight ? index-- : ++index < length)) {
529
var other = array[index];
530
if (other !== other) {
531
return index;
532
}
533
}
534
return -1;
535
}
536
537
/**
538
* Checks if `value` is object-like.
539
*
540
* @private
541
* @param {*} value The value to check.
542
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
543
*/
544
function isObjectLike(value) {
545
return !!value && typeof value == 'object';
546
}
547
548
/**
549
* Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
550
* character code is whitespace.
551
*
552
* @private
553
* @param {number} charCode The character code to inspect.
554
* @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
555
*/
556
function isSpace(charCode) {
557
return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
558
(charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
559
}
560
561
/**
562
* Replaces all `placeholder` elements in `array` with an internal placeholder
563
* and returns an array of their indexes.
564
*
565
* @private
566
* @param {Array} array The array to modify.
567
* @param {*} placeholder The placeholder to replace.
568
* @returns {Array} Returns the new array of placeholder indexes.
569
*/
570
function replaceHolders(array, placeholder) {
571
var index = -1,
572
length = array.length,
573
resIndex = -1,
574
result = [];
575
576
while (++index < length) {
577
if (array[index] === placeholder) {
578
array[index] = PLACEHOLDER;
579
result[++resIndex] = index;
580
}
581
}
582
return result;
583
}
584
585
/**
586
* An implementation of `_.uniq` optimized for sorted arrays without support
587
* for callback shorthands and `this` binding.
588
*
589
* @private
590
* @param {Array} array The array to inspect.
591
* @param {Function} [iteratee] The function invoked per iteration.
592
* @returns {Array} Returns the new duplicate-value-free array.
593
*/
594
function sortedUniq(array, iteratee) {
595
var seen,
596
index = -1,
597
length = array.length,
598
resIndex = -1,
599
result = [];
600
601
while (++index < length) {
602
var value = array[index],
603
computed = iteratee ? iteratee(value, index, array) : value;
604
605
if (!index || seen !== computed) {
606
seen = computed;
607
result[++resIndex] = value;
608
}
609
}
610
return result;
611
}
612
613
/**
614
* Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
615
* character of `string`.
616
*
617
* @private
618
* @param {string} string The string to inspect.
619
* @returns {number} Returns the index of the first non-whitespace character.
620
*/
621
function trimmedLeftIndex(string) {
622
var index = -1,
623
length = string.length;
624
625
while (++index < length && isSpace(string.charCodeAt(index))) {}
626
return index;
627
}
628
629
/**
630
* Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
631
* character of `string`.
632
*
633
* @private
634
* @param {string} string The string to inspect.
635
* @returns {number} Returns the index of the last non-whitespace character.
636
*/
637
function trimmedRightIndex(string) {
638
var index = string.length;
639
640
while (index-- && isSpace(string.charCodeAt(index))) {}
641
return index;
642
}
643
644
/**
645
* Used by `_.unescape` to convert HTML entities to characters.
646
*
647
* @private
648
* @param {string} chr The matched character to unescape.
649
* @returns {string} Returns the unescaped character.
650
*/
651
function unescapeHtmlChar(chr) {
652
return htmlUnescapes[chr];
653
}
654
655
/*--------------------------------------------------------------------------*/
656
657
/**
658
* Create a new pristine `lodash` function using the given `context` object.
659
*
660
* @static
661
* @memberOf _
662
* @category Utility
663
* @param {Object} [context=root] The context object.
664
* @returns {Function} Returns a new `lodash` function.
665
* @example
666
*
667
* _.mixin({ 'foo': _.constant('foo') });
668
*
669
* var lodash = _.runInContext();
670
* lodash.mixin({ 'bar': lodash.constant('bar') });
671
*
672
* _.isFunction(_.foo);
673
* // => true
674
* _.isFunction(_.bar);
675
* // => false
676
*
677
* lodash.isFunction(lodash.foo);
678
* // => false
679
* lodash.isFunction(lodash.bar);
680
* // => true
681
*
682
* // using `context` to mock `Date#getTime` use in `_.now`
683
* var mock = _.runInContext({
684
* 'Date': function() {
685
* return { 'getTime': getTimeMock };
686
* }
687
* });
688
*
689
* // or creating a suped-up `defer` in Node.js
690
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
691
*/
692
function runInContext(context) {
693
// Avoid issues with some ES3 environments that attempt to use values, named
694
// after built-in constructors like `Object`, for the creation of literals.
695
// ES5 clears this up by stating that literals must use built-in constructors.
696
// See https://es5.github.io/#x11.1.5 for more details.
697
context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
698
699
/** Native constructor references. */
700
var Array = context.Array,
701
Date = context.Date,
702
Error = context.Error,
703
Function = context.Function,
704
Math = context.Math,
705
Number = context.Number,
706
Object = context.Object,
707
RegExp = context.RegExp,
708
String = context.String,
709
TypeError = context.TypeError;
710
711
/** Used for native method references. */
712
var arrayProto = Array.prototype,
713
objectProto = Object.prototype,
714
stringProto = String.prototype;
715
716
/** Used to detect DOM support. */
717
var document = (document = context.window) ? document.document : null;
718
719
/** Used to resolve the decompiled source of functions. */
720
var fnToString = Function.prototype.toString;
721
722
/** Used to check objects for own properties. */
723
var hasOwnProperty = objectProto.hasOwnProperty;
724
725
/** Used to generate unique IDs. */
726
var idCounter = 0;
727
728
/**
729
* Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
730
* of values.
731
*/
732
var objToString = objectProto.toString;
733
734
/** Used to restore the original `_` reference in `_.noConflict`. */
735
var oldDash = context._;
736
737
/** Used to detect if a method is native. */
738
var reIsNative = RegExp('^' +
739
escapeRegExp(fnToString.call(hasOwnProperty))
740
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
741
);
742
743
/** Native method references. */
744
var ArrayBuffer = getNative(context, 'ArrayBuffer'),
745
bufferSlice = getNative(ArrayBuffer && new ArrayBuffer(0), 'slice'),
746
ceil = Math.ceil,
747
clearTimeout = context.clearTimeout,
748
floor = Math.floor,
749
getPrototypeOf = getNative(Object, 'getPrototypeOf'),
750
parseFloat = context.parseFloat,
751
push = arrayProto.push,
752
Set = getNative(context, 'Set'),
753
setTimeout = context.setTimeout,
754
splice = arrayProto.splice,
755
Uint8Array = getNative(context, 'Uint8Array'),
756
WeakMap = getNative(context, 'WeakMap');
757
758
/** Used to clone array buffers. */
759
var Float64Array = (function() {
760
// Safari 5 errors when using an array buffer to initialize a typed array
761
// where the array buffer's `byteLength` is not a multiple of the typed
762
// array's `BYTES_PER_ELEMENT`.
763
try {
764
var func = getNative(context, 'Float64Array'),
765
result = new func(new ArrayBuffer(10), 0, 1) && func;
766
} catch(e) {}
767
return result || null;
768
}());
769
770
/* Native method references for those with the same name as other `lodash` methods. */
771
var nativeCreate = getNative(Object, 'create'),
772
nativeIsArray = getNative(Array, 'isArray'),
773
nativeIsFinite = context.isFinite,
774
nativeKeys = getNative(Object, 'keys'),
775
nativeMax = Math.max,
776
nativeMin = Math.min,
777
nativeNow = getNative(Date, 'now'),
778
nativeNumIsFinite = getNative(Number, 'isFinite'),
779
nativeParseInt = context.parseInt,
780
nativeRandom = Math.random;
781
782
/** Used as references for `-Infinity` and `Infinity`. */
783
var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
784
POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
785
786
/** Used as references for the maximum length and index of an array. */
787
var MAX_ARRAY_LENGTH = 4294967295,
788
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
789
HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
790
791
/** Used as the size, in bytes, of each `Float64Array` element. */
792
var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0;
793
794
/**
795
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
796
* of an array-like value.
797
*/
798
var MAX_SAFE_INTEGER = 9007199254740991;
799
800
/** Used to store function metadata. */
801
var metaMap = WeakMap && new WeakMap;
802
803
/** Used to lookup unminified function names. */
804
var realNames = {};
805
806
/*------------------------------------------------------------------------*/
807
808
/**
809
* Creates a `lodash` object which wraps `value` to enable implicit chaining.
810
* Methods that operate on and return arrays, collections, and functions can
811
* be chained together. Methods that return a boolean or single value will
812
* automatically end the chain returning the unwrapped value. Explicit chaining
813
* may be enabled using `_.chain`. The execution of chained methods is lazy,
814
* that is, execution is deferred until `_#value` is implicitly or explicitly
815
* called.
816
*
817
* Lazy evaluation allows several methods to support shortcut fusion. Shortcut
818
* fusion is an optimization that merges iteratees to avoid creating intermediate
819
* arrays and reduce the number of iteratee executions.
820
*
821
* Chaining is supported in custom builds as long as the `_#value` method is
822
* directly or indirectly included in the build.
823
*
824
* In addition to lodash methods, wrappers have `Array` and `String` methods.
825
*
826
* The wrapper `Array` methods are:
827
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
828
* `splice`, and `unshift`
829
*
830
* The wrapper `String` methods are:
831
* `replace` and `split`
832
*
833
* The wrapper methods that support shortcut fusion are:
834
* `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
835
* `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
836
* `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
837
* and `where`
838
*
839
* The chainable wrapper methods are:
840
* `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
841
* `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
842
* `countBy`, `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`,
843
* `difference`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `fill`,
844
* `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`,
845
* `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`,
846
* `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`,
847
* `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
848
* `memoize`, `merge`, `method`, `methodOf`, `mixin`, `negate`, `omit`, `once`,
849
* `pairs`, `partial`, `partialRight`, `partition`, `pick`, `plant`, `pluck`,
850
* `property`, `propertyOf`, `pull`, `pullAt`, `push`, `range`, `rearg`,
851
* `reject`, `remove`, `rest`, `restParam`, `reverse`, `set`, `shuffle`,
852
* `slice`, `sort`, `sortBy`, `sortByAll`, `sortByOrder`, `splice`, `spread`,
853
* `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`, `throttle`,
854
* `thru`, `times`, `toArray`, `toPlainObject`, `transform`, `union`, `uniq`,
855
* `unshift`, `unzip`, `unzipWith`, `values`, `valuesIn`, `where`, `without`,
856
* `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
857
*
858
* The wrapper methods that are **not** chainable by default are:
859
* `add`, `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`,
860
* `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`,
861
* `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `get`,
862
* `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`, `inRange`, `isArguments`,
863
* `isArray`, `isBoolean`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`,
864
* `isFinite` `isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`,
865
* `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`,
866
* `isTypedArray`, `join`, `kebabCase`, `last`, `lastIndexOf`, `lt`, `lte`,
867
* `max`, `min`, `noConflict`, `noop`, `now`, `pad`, `padLeft`, `padRight`,
868
* `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, `repeat`, `result`,
869
* `runInContext`, `shift`, `size`, `snakeCase`, `some`, `sortedIndex`,
870
* `sortedLastIndex`, `startCase`, `startsWith`, `sum`, `template`, `trim`,
871
* `trimLeft`, `trimRight`, `trunc`, `unescape`, `uniqueId`, `value`, and `words`
872
*
873
* The wrapper method `sample` will return a wrapped value when `n` is provided,
874
* otherwise an unwrapped value is returned.
875
*
876
* @name _
877
* @constructor
878
* @category Chain
879
* @param {*} value The value to wrap in a `lodash` instance.
880
* @returns {Object} Returns the new `lodash` wrapper instance.
881
* @example
882
*
883
* var wrapped = _([1, 2, 3]);
884
*
885
* // returns an unwrapped value
886
* wrapped.reduce(function(total, n) {
887
* return total + n;
888
* });
889
* // => 6
890
*
891
* // returns a wrapped value
892
* var squares = wrapped.map(function(n) {
893
* return n * n;
894
* });
895
*
896
* _.isArray(squares);
897
* // => false
898
*
899
* _.isArray(squares.value());
900
* // => true
901
*/
902
function lodash(value) {
903
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
904
if (value instanceof LodashWrapper) {
905
return value;
906
}
907
if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
908
return wrapperClone(value);
909
}
910
}
911
return new LodashWrapper(value);
912
}
913
914
/**
915
* The function whose prototype all chaining wrappers inherit from.
916
*
917
* @private
918
*/
919
function baseLodash() {
920
// No operation performed.
921
}
922
923
/**
924
* The base constructor for creating `lodash` wrapper objects.
925
*
926
* @private
927
* @param {*} value The value to wrap.
928
* @param {boolean} [chainAll] Enable chaining for all wrapper methods.
929
* @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
930
*/
931
function LodashWrapper(value, chainAll, actions) {
932
this.__wrapped__ = value;
933
this.__actions__ = actions || [];
934
this.__chain__ = !!chainAll;
935
}
936
937
/**
938
* An object environment feature flags.
939
*
940
* @static
941
* @memberOf _
942
* @type Object
943
*/
944
var support = lodash.support = {};
945
946
(function(x) {
947
var Ctor = function() { this.x = x; },
948
object = { '0': x, 'length': x },
949
props = [];
950
951
Ctor.prototype = { 'valueOf': x, 'y': x };
952
for (var key in new Ctor) { props.push(key); }
953
954
/**
955
* Detect if the DOM is supported.
956
*
957
* @memberOf _.support
958
* @type boolean
959
*/
960
try {
961
support.dom = document.createDocumentFragment().nodeType === 11;
962
} catch(e) {
963
support.dom = false;
964
}
965
}(1, 0));
966
967
/**
968
* By default, the template delimiters used by lodash are like those in
969
* embedded Ruby (ERB). Change the following template settings to use
970
* alternative delimiters.
971
*
972
* @static
973
* @memberOf _
974
* @type Object
975
*/
976
lodash.templateSettings = {
977
978
/**
979
* Used to detect `data` property values to be HTML-escaped.
980
*
981
* @memberOf _.templateSettings
982
* @type RegExp
983
*/
984
'escape': reEscape,
985
986
/**
987
* Used to detect code to be evaluated.
988
*
989
* @memberOf _.templateSettings
990
* @type RegExp
991
*/
992
'evaluate': reEvaluate,
993
994
/**
995
* Used to detect `data` property values to inject.
996
*
997
* @memberOf _.templateSettings
998
* @type RegExp
999
*/
1000
'interpolate': reInterpolate,
1001
1002
/**
1003
* Used to reference the data object in the template text.
1004
*
1005
* @memberOf _.templateSettings
1006
* @type string
1007
*/
1008
'variable': '',
1009
1010
/**
1011
* Used to import variables into the compiled template.
1012
*
1013
* @memberOf _.templateSettings
1014
* @type Object
1015
*/
1016
'imports': {
1017
1018
/**
1019
* A reference to the `lodash` function.
1020
*
1021
* @memberOf _.templateSettings.imports
1022
* @type Function
1023
*/
1024
'_': lodash
1025
}
1026
};
1027
1028
/*------------------------------------------------------------------------*/
1029
1030
/**
1031
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
1032
*
1033
* @private
1034
* @param {*} value The value to wrap.
1035
*/
1036
function LazyWrapper(value) {
1037
this.__wrapped__ = value;
1038
this.__actions__ = null;
1039
this.__dir__ = 1;
1040
this.__dropCount__ = 0;
1041
this.__filtered__ = false;
1042
this.__iteratees__ = null;
1043
this.__takeCount__ = POSITIVE_INFINITY;
1044
this.__views__ = null;
1045
}
1046
1047
/**
1048
* Creates a clone of the lazy wrapper object.
1049
*
1050
* @private
1051
* @name clone
1052
* @memberOf LazyWrapper
1053
* @returns {Object} Returns the cloned `LazyWrapper` object.
1054
*/
1055
function lazyClone() {
1056
var actions = this.__actions__,
1057
iteratees = this.__iteratees__,
1058
views = this.__views__,
1059
result = new LazyWrapper(this.__wrapped__);
1060
1061
result.__actions__ = actions ? arrayCopy(actions) : null;
1062
result.__dir__ = this.__dir__;
1063
result.__filtered__ = this.__filtered__;
1064
result.__iteratees__ = iteratees ? arrayCopy(iteratees) : null;
1065
result.__takeCount__ = this.__takeCount__;
1066
result.__views__ = views ? arrayCopy(views) : null;
1067
return result;
1068
}
1069
1070
/**
1071
* Reverses the direction of lazy iteration.
1072
*
1073
* @private
1074
* @name reverse
1075
* @memberOf LazyWrapper
1076
* @returns {Object} Returns the new reversed `LazyWrapper` object.
1077
*/
1078
function lazyReverse() {
1079
if (this.__filtered__) {
1080
var result = new LazyWrapper(this);
1081
result.__dir__ = -1;
1082
result.__filtered__ = true;
1083
} else {
1084
result = this.clone();
1085
result.__dir__ *= -1;
1086
}
1087
return result;
1088
}
1089
1090
/**
1091
* Extracts the unwrapped value from its lazy wrapper.
1092
*
1093
* @private
1094
* @name value
1095
* @memberOf LazyWrapper
1096
* @returns {*} Returns the unwrapped value.
1097
*/
1098
function lazyValue() {
1099
var array = this.__wrapped__.value();
1100
if (!isArray(array)) {
1101
return baseWrapperValue(array, this.__actions__);
1102
}
1103
var dir = this.__dir__,
1104
isRight = dir < 0,
1105
view = getView(0, array.length, this.__views__),
1106
start = view.start,
1107
end = view.end,
1108
length = end - start,
1109
index = isRight ? end : (start - 1),
1110
takeCount = nativeMin(length, this.__takeCount__),
1111
iteratees = this.__iteratees__,
1112
iterLength = iteratees ? iteratees.length : 0,
1113
resIndex = 0,
1114
result = [];
1115
1116
outer:
1117
while (length-- && resIndex < takeCount) {
1118
index += dir;
1119
1120
var iterIndex = -1,
1121
value = array[index];
1122
1123
while (++iterIndex < iterLength) {
1124
var data = iteratees[iterIndex],
1125
iteratee = data.iteratee,
1126
type = data.type;
1127
1128
if (type == LAZY_DROP_WHILE_FLAG) {
1129
if (data.done && (isRight ? (index > data.index) : (index < data.index))) {
1130
data.count = 0;
1131
data.done = false;
1132
}
1133
data.index = index;
1134
if (!data.done) {
1135
var limit = data.limit;
1136
if (!(data.done = limit > -1 ? (data.count++ >= limit) : !iteratee(value))) {
1137
continue outer;
1138
}
1139
}
1140
} else {
1141
var computed = iteratee(value);
1142
if (type == LAZY_MAP_FLAG) {
1143
value = computed;
1144
} else if (!computed) {
1145
if (type == LAZY_FILTER_FLAG) {
1146
continue outer;
1147
} else {
1148
break outer;
1149
}
1150
}
1151
}
1152
}
1153
result[resIndex++] = value;
1154
}
1155
return result;
1156
}
1157
1158
/*------------------------------------------------------------------------*/
1159
1160
/**
1161
* Creates a cache object to store key/value pairs.
1162
*
1163
* @private
1164
* @static
1165
* @name Cache
1166
* @memberOf _.memoize
1167
*/
1168
function MapCache() {
1169
this.__data__ = {};
1170
}
1171
1172
/**
1173
* Removes `key` and its value from the cache.
1174
*
1175
* @private
1176
* @name delete
1177
* @memberOf _.memoize.Cache
1178
* @param {string} key The key of the value to remove.
1179
* @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
1180
*/
1181
function mapDelete(key) {
1182
return this.has(key) && delete this.__data__[key];
1183
}
1184
1185
/**
1186
* Gets the cached value for `key`.
1187
*
1188
* @private
1189
* @name get
1190
* @memberOf _.memoize.Cache
1191
* @param {string} key The key of the value to get.
1192
* @returns {*} Returns the cached value.
1193
*/
1194
function mapGet(key) {
1195
return key == '__proto__' ? undefined : this.__data__[key];
1196
}
1197
1198
/**
1199
* Checks if a cached value for `key` exists.
1200
*
1201
* @private
1202
* @name has
1203
* @memberOf _.memoize.Cache
1204
* @param {string} key The key of the entry to check.
1205
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1206
*/
1207
function mapHas(key) {
1208
return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
1209
}
1210
1211
/**
1212
* Sets `value` to `key` of the cache.
1213
*
1214
* @private
1215
* @name set
1216
* @memberOf _.memoize.Cache
1217
* @param {string} key The key of the value to cache.
1218
* @param {*} value The value to cache.
1219
* @returns {Object} Returns the cache object.
1220
*/
1221
function mapSet(key, value) {
1222
if (key != '__proto__') {
1223
this.__data__[key] = value;
1224
}
1225
return this;
1226
}
1227
1228
/*------------------------------------------------------------------------*/
1229
1230
/**
1231
*
1232
* Creates a cache object to store unique values.
1233
*
1234
* @private
1235
* @param {Array} [values] The values to cache.
1236
*/
1237
function SetCache(values) {
1238
var length = values ? values.length : 0;
1239
1240
this.data = { 'hash': nativeCreate(null), 'set': new Set };
1241
while (length--) {
1242
this.push(values[length]);
1243
}
1244
}
1245
1246
/**
1247
* Checks if `value` is in `cache` mimicking the return signature of
1248
* `_.indexOf` by returning `0` if the value is found, else `-1`.
1249
*
1250
* @private
1251
* @param {Object} cache The cache to search.
1252
* @param {*} value The value to search for.
1253
* @returns {number} Returns `0` if `value` is found, else `-1`.
1254
*/
1255
function cacheIndexOf(cache, value) {
1256
var data = cache.data,
1257
result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];
1258
1259
return result ? 0 : -1;
1260
}
1261
1262
/**
1263
* Adds `value` to the cache.
1264
*
1265
* @private
1266
* @name push
1267
* @memberOf SetCache
1268
* @param {*} value The value to cache.
1269
*/
1270
function cachePush(value) {
1271
var data = this.data;
1272
if (typeof value == 'string' || isObject(value)) {
1273
data.set.add(value);
1274
} else {
1275
data.hash[value] = true;
1276
}
1277
}
1278
1279
/*------------------------------------------------------------------------*/
1280
1281
/**
1282
* Copies the values of `source` to `array`.
1283
*
1284
* @private
1285
* @param {Array} source The array to copy values from.
1286
* @param {Array} [array=[]] The array to copy values to.
1287
* @returns {Array} Returns `array`.
1288
*/
1289
function arrayCopy(source, array) {
1290
var index = -1,
1291
length = source.length;
1292
1293
array || (array = Array(length));
1294
while (++index < length) {
1295
array[index] = source[index];
1296
}
1297
return array;
1298
}
1299
1300
/**
1301
* A specialized version of `_.forEach` for arrays without support for callback
1302
* shorthands and `this` binding.
1303
*
1304
* @private
1305
* @param {Array} array The array to iterate over.
1306
* @param {Function} iteratee The function invoked per iteration.
1307
* @returns {Array} Returns `array`.
1308
*/
1309
function arrayEach(array, iteratee) {
1310
var index = -1,
1311
length = array.length;
1312
1313
while (++index < length) {
1314
if (iteratee(array[index], index, array) === false) {
1315
break;
1316
}
1317
}
1318
return array;
1319
}
1320
1321
/**
1322
* A specialized version of `_.forEachRight` for arrays without support for
1323
* callback shorthands and `this` binding.
1324
*
1325
* @private
1326
* @param {Array} array The array to iterate over.
1327
* @param {Function} iteratee The function invoked per iteration.
1328
* @returns {Array} Returns `array`.
1329
*/
1330
function arrayEachRight(array, iteratee) {
1331
var length = array.length;
1332
1333
while (length--) {
1334
if (iteratee(array[length], length, array) === false) {
1335
break;
1336
}
1337
}
1338
return array;
1339
}
1340
1341
/**
1342
* A specialized version of `_.every` for arrays without support for callback
1343
* shorthands and `this` binding.
1344
*
1345
* @private
1346
* @param {Array} array The array to iterate over.
1347
* @param {Function} predicate The function invoked per iteration.
1348
* @returns {boolean} Returns `true` if all elements pass the predicate check,
1349
* else `false`.
1350
*/
1351
function arrayEvery(array, predicate) {
1352
var index = -1,
1353
length = array.length;
1354
1355
while (++index < length) {
1356
if (!predicate(array[index], index, array)) {
1357
return false;
1358
}
1359
}
1360
return true;
1361
}
1362
1363
/**
1364
* A specialized version of `baseExtremum` for arrays which invokes `iteratee`
1365
* with one argument: (value).
1366
*
1367
* @private
1368
* @param {Array} array The array to iterate over.
1369
* @param {Function} iteratee The function invoked per iteration.
1370
* @param {Function} comparator The function used to compare values.
1371
* @param {*} exValue The initial extremum value.
1372
* @returns {*} Returns the extremum value.
1373
*/
1374
function arrayExtremum(array, iteratee, comparator, exValue) {
1375
var index = -1,
1376
length = array.length,
1377
computed = exValue,
1378
result = computed;
1379
1380
while (++index < length) {
1381
var value = array[index],
1382
current = +iteratee(value);
1383
1384
if (comparator(current, computed)) {
1385
computed = current;
1386
result = value;
1387
}
1388
}
1389
return result;
1390
}
1391
1392
/**
1393
* A specialized version of `_.filter` for arrays without support for callback
1394
* shorthands and `this` binding.
1395
*
1396
* @private
1397
* @param {Array} array The array to iterate over.
1398
* @param {Function} predicate The function invoked per iteration.
1399
* @returns {Array} Returns the new filtered array.
1400
*/
1401
function arrayFilter(array, predicate) {
1402
var index = -1,
1403
length = array.length,
1404
resIndex = -1,
1405
result = [];
1406
1407
while (++index < length) {
1408
var value = array[index];
1409
if (predicate(value, index, array)) {
1410
result[++resIndex] = value;
1411
}
1412
}
1413
return result;
1414
}
1415
1416
/**
1417
* A specialized version of `_.map` for arrays without support for callback
1418
* shorthands and `this` binding.
1419
*
1420
* @private
1421
* @param {Array} array The array to iterate over.
1422
* @param {Function} iteratee The function invoked per iteration.
1423
* @returns {Array} Returns the new mapped array.
1424
*/
1425
function arrayMap(array, iteratee) {
1426
var index = -1,
1427
length = array.length,
1428
result = Array(length);
1429
1430
while (++index < length) {
1431
result[index] = iteratee(array[index], index, array);
1432
}
1433
return result;
1434
}
1435
1436
/**
1437
* A specialized version of `_.reduce` for arrays without support for callback
1438
* shorthands and `this` binding.
1439
*
1440
* @private
1441
* @param {Array} array The array to iterate over.
1442
* @param {Function} iteratee The function invoked per iteration.
1443
* @param {*} [accumulator] The initial value.
1444
* @param {boolean} [initFromArray] Specify using the first element of `array`
1445
* as the initial value.
1446
* @returns {*} Returns the accumulated value.
1447
*/
1448
function arrayReduce(array, iteratee, accumulator, initFromArray) {
1449
var index = -1,
1450
length = array.length;
1451
1452
if (initFromArray && length) {
1453
accumulator = array[++index];
1454
}
1455
while (++index < length) {
1456
accumulator = iteratee(accumulator, array[index], index, array);
1457
}
1458
return accumulator;
1459
}
1460
1461
/**
1462
* A specialized version of `_.reduceRight` for arrays without support for
1463
* callback shorthands and `this` binding.
1464
*
1465
* @private
1466
* @param {Array} array The array to iterate over.
1467
* @param {Function} iteratee The function invoked per iteration.
1468
* @param {*} [accumulator] The initial value.
1469
* @param {boolean} [initFromArray] Specify using the last element of `array`
1470
* as the initial value.
1471
* @returns {*} Returns the accumulated value.
1472
*/
1473
function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
1474
var length = array.length;
1475
if (initFromArray && length) {
1476
accumulator = array[--length];
1477
}
1478
while (length--) {
1479
accumulator = iteratee(accumulator, array[length], length, array);
1480
}
1481
return accumulator;
1482
}
1483
1484
/**
1485
* A specialized version of `_.some` for arrays without support for callback
1486
* shorthands and `this` binding.
1487
*
1488
* @private
1489
* @param {Array} array The array to iterate over.
1490
* @param {Function} predicate The function invoked per iteration.
1491
* @returns {boolean} Returns `true` if any element passes the predicate check,
1492
* else `false`.
1493
*/
1494
function arraySome(array, predicate) {
1495
var index = -1,
1496
length = array.length;
1497
1498
while (++index < length) {
1499
if (predicate(array[index], index, array)) {
1500
return true;
1501
}
1502
}
1503
return false;
1504
}
1505
1506
/**
1507
* A specialized version of `_.sum` for arrays without support for iteratees.
1508
*
1509
* @private
1510
* @param {Array} array The array to iterate over.
1511
* @returns {number} Returns the sum.
1512
*/
1513
function arraySum(array) {
1514
var length = array.length,
1515
result = 0;
1516
1517
while (length--) {
1518
result += +array[length] || 0;
1519
}
1520
return result;
1521
}
1522
1523
/**
1524
* Used by `_.defaults` to customize its `_.assign` use.
1525
*
1526
* @private
1527
* @param {*} objectValue The destination object property value.
1528
* @param {*} sourceValue The source object property value.
1529
* @returns {*} Returns the value to assign to the destination object.
1530
*/
1531
function assignDefaults(objectValue, sourceValue) {
1532
return objectValue === undefined ? sourceValue : objectValue;
1533
}
1534
1535
/**
1536
* Used by `_.template` to customize its `_.assign` use.
1537
*
1538
* **Note:** This function is like `assignDefaults` except that it ignores
1539
* inherited property values when checking if a property is `undefined`.
1540
*
1541
* @private
1542
* @param {*} objectValue The destination object property value.
1543
* @param {*} sourceValue The source object property value.
1544
* @param {string} key The key associated with the object and source values.
1545
* @param {Object} object The destination object.
1546
* @returns {*} Returns the value to assign to the destination object.
1547
*/
1548
function assignOwnDefaults(objectValue, sourceValue, key, object) {
1549
return (objectValue === undefined || !hasOwnProperty.call(object, key))
1550
? sourceValue
1551
: objectValue;
1552
}
1553
1554
/**
1555
* A specialized version of `_.assign` for customizing assigned values without
1556
* support for argument juggling, multiple sources, and `this` binding `customizer`
1557
* functions.
1558
*
1559
* @private
1560
* @param {Object} object The destination object.
1561
* @param {Object} source The source object.
1562
* @param {Function} customizer The function to customize assigned values.
1563
* @returns {Object} Returns `object`.
1564
*/
1565
function assignWith(object, source, customizer) {
1566
var index = -1,
1567
props = keys(source),
1568
length = props.length;
1569
1570
while (++index < length) {
1571
var key = props[index],
1572
value = object[key],
1573
result = customizer(value, source[key], key, object, source);
1574
1575
if ((result === result ? (result !== value) : (value === value)) ||
1576
(value === undefined && !(key in object))) {
1577
object[key] = result;
1578
}
1579
}
1580
return object;
1581
}
1582
1583
/**
1584
* The base implementation of `_.assign` without support for argument juggling,
1585
* multiple sources, and `customizer` functions.
1586
*
1587
* @private
1588
* @param {Object} object The destination object.
1589
* @param {Object} source The source object.
1590
* @returns {Object} Returns `object`.
1591
*/
1592
function baseAssign(object, source) {
1593
return source == null
1594
? object
1595
: baseCopy(source, keys(source), object);
1596
}
1597
1598
/**
1599
* The base implementation of `_.at` without support for string collections
1600
* and individual key arguments.
1601
*
1602
* @private
1603
* @param {Array|Object} collection The collection to iterate over.
1604
* @param {number[]|string[]} props The property names or indexes of elements to pick.
1605
* @returns {Array} Returns the new array of picked elements.
1606
*/
1607
function baseAt(collection, props) {
1608
var index = -1,
1609
isNil = collection == null,
1610
isArr = !isNil && isArrayLike(collection),
1611
length = isArr ? collection.length : 0,
1612
propsLength = props.length,
1613
result = Array(propsLength);
1614
1615
while(++index < propsLength) {
1616
var key = props[index];
1617
if (isArr) {
1618
result[index] = isIndex(key, length) ? collection[key] : undefined;
1619
} else {
1620
result[index] = isNil ? undefined : collection[key];
1621
}
1622
}
1623
return result;
1624
}
1625
1626
/**
1627
* Copies properties of `source` to `object`.
1628
*
1629
* @private
1630
* @param {Object} source The object to copy properties from.
1631
* @param {Array} props The property names to copy.
1632
* @param {Object} [object={}] The object to copy properties to.
1633
* @returns {Object} Returns `object`.
1634
*/
1635
function baseCopy(source, props, object) {
1636
object || (object = {});
1637
1638
var index = -1,
1639
length = props.length;
1640
1641
while (++index < length) {
1642
var key = props[index];
1643
object[key] = source[key];
1644
}
1645
return object;
1646
}
1647
1648
/**
1649
* The base implementation of `_.callback` which supports specifying the
1650
* number of arguments to provide to `func`.
1651
*
1652
* @private
1653
* @param {*} [func=_.identity] The value to convert to a callback.
1654
* @param {*} [thisArg] The `this` binding of `func`.
1655
* @param {number} [argCount] The number of arguments to provide to `func`.
1656
* @returns {Function} Returns the callback.
1657
*/
1658
function baseCallback(func, thisArg, argCount) {
1659
var type = typeof func;
1660
if (type == 'function') {
1661
return thisArg === undefined
1662
? func
1663
: bindCallback(func, thisArg, argCount);
1664
}
1665
if (func == null) {
1666
return identity;
1667
}
1668
if (type == 'object') {
1669
return baseMatches(func);
1670
}
1671
return thisArg === undefined
1672
? property(func)
1673
: baseMatchesProperty(func, thisArg);
1674
}
1675
1676
/**
1677
* The base implementation of `_.clone` without support for argument juggling
1678
* and `this` binding `customizer` functions.
1679
*
1680
* @private
1681
* @param {*} value The value to clone.
1682
* @param {boolean} [isDeep] Specify a deep clone.
1683
* @param {Function} [customizer] The function to customize cloning values.
1684
* @param {string} [key] The key of `value`.
1685
* @param {Object} [object] The object `value` belongs to.
1686
* @param {Array} [stackA=[]] Tracks traversed source objects.
1687
* @param {Array} [stackB=[]] Associates clones with source counterparts.
1688
* @returns {*} Returns the cloned value.
1689
*/
1690
function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
1691
var result;
1692
if (customizer) {
1693
result = object ? customizer(value, key, object) : customizer(value);
1694
}
1695
if (result !== undefined) {
1696
return result;
1697
}
1698
if (!isObject(value)) {
1699
return value;
1700
}
1701
var isArr = isArray(value);
1702
if (isArr) {
1703
result = initCloneArray(value);
1704
if (!isDeep) {
1705
return arrayCopy(value, result);
1706
}
1707
} else {
1708
var tag = objToString.call(value),
1709
isFunc = tag == funcTag;
1710
1711
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
1712
result = initCloneObject(isFunc ? {} : value);
1713
if (!isDeep) {
1714
return baseAssign(result, value);
1715
}
1716
} else {
1717
return cloneableTags[tag]
1718
? initCloneByTag(value, tag, isDeep)
1719
: (object ? value : {});
1720
}
1721
}
1722
// Check for circular references and return corresponding clone.
1723
stackA || (stackA = []);
1724
stackB || (stackB = []);
1725
1726
var length = stackA.length;
1727
while (length--) {
1728
if (stackA[length] == value) {
1729
return stackB[length];
1730
}
1731
}
1732
// Add the source value to the stack of traversed objects and associate it with its clone.
1733
stackA.push(value);
1734
stackB.push(result);
1735
1736
// Recursively populate clone (susceptible to call stack limits).
1737
(isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
1738
result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
1739
});
1740
return result;
1741
}
1742
1743
/**
1744
* The base implementation of `_.create` without support for assigning
1745
* properties to the created object.
1746
*
1747
* @private
1748
* @param {Object} prototype The object to inherit from.
1749
* @returns {Object} Returns the new object.
1750
*/
1751
var baseCreate = (function() {
1752
function object() {}
1753
return function(prototype) {
1754
if (isObject(prototype)) {
1755
object.prototype = prototype;
1756
var result = new object;
1757
object.prototype = null;
1758
}
1759
return result || {};
1760
};
1761
}());
1762
1763
/**
1764
* The base implementation of `_.delay` and `_.defer` which accepts an index
1765
* of where to slice the arguments to provide to `func`.
1766
*
1767
* @private
1768
* @param {Function} func The function to delay.
1769
* @param {number} wait The number of milliseconds to delay invocation.
1770
* @param {Object} args The arguments provide to `func`.
1771
* @returns {number} Returns the timer id.
1772
*/
1773
function baseDelay(func, wait, args) {
1774
if (typeof func != 'function') {
1775
throw new TypeError(FUNC_ERROR_TEXT);
1776
}
1777
return setTimeout(function() { func.apply(undefined, args); }, wait);
1778
}
1779
1780
/**
1781
* The base implementation of `_.difference` which accepts a single array
1782
* of values to exclude.
1783
*
1784
* @private
1785
* @param {Array} array The array to inspect.
1786
* @param {Array} values The values to exclude.
1787
* @returns {Array} Returns the new array of filtered values.
1788
*/
1789
function baseDifference(array, values) {
1790
var length = array ? array.length : 0,
1791
result = [];
1792
1793
if (!length) {
1794
return result;
1795
}
1796
var index = -1,
1797
indexOf = getIndexOf(),
1798
isCommon = indexOf == baseIndexOf,
1799
cache = (isCommon && values.length >= 200) ? createCache(values) : null,
1800
valuesLength = values.length;
1801
1802
if (cache) {
1803
indexOf = cacheIndexOf;
1804
isCommon = false;
1805
values = cache;
1806
}
1807
outer:
1808
while (++index < length) {
1809
var value = array[index];
1810
1811
if (isCommon && value === value) {
1812
var valuesIndex = valuesLength;
1813
while (valuesIndex--) {
1814
if (values[valuesIndex] === value) {
1815
continue outer;
1816
}
1817
}
1818
result.push(value);
1819
}
1820
else if (indexOf(values, value, 0) < 0) {
1821
result.push(value);
1822
}
1823
}
1824
return result;
1825
}
1826
1827
/**
1828
* The base implementation of `_.forEach` without support for callback
1829
* shorthands and `this` binding.
1830
*
1831
* @private
1832
* @param {Array|Object|string} collection The collection to iterate over.
1833
* @param {Function} iteratee The function invoked per iteration.
1834
* @returns {Array|Object|string} Returns `collection`.
1835
*/
1836
var baseEach = createBaseEach(baseForOwn);
1837
1838
/**
1839
* The base implementation of `_.forEachRight` without support for callback
1840
* shorthands and `this` binding.
1841
*
1842
* @private
1843
* @param {Array|Object|string} collection The collection to iterate over.
1844
* @param {Function} iteratee The function invoked per iteration.
1845
* @returns {Array|Object|string} Returns `collection`.
1846
*/
1847
var baseEachRight = createBaseEach(baseForOwnRight, true);
1848
1849
/**
1850
* The base implementation of `_.every` without support for callback
1851
* shorthands and `this` binding.
1852
*
1853
* @private
1854
* @param {Array|Object|string} collection The collection to iterate over.
1855
* @param {Function} predicate The function invoked per iteration.
1856
* @returns {boolean} Returns `true` if all elements pass the predicate check,
1857
* else `false`
1858
*/
1859
function baseEvery(collection, predicate) {
1860
var result = true;
1861
baseEach(collection, function(value, index, collection) {
1862
result = !!predicate(value, index, collection);
1863
return result;
1864
});
1865
return result;
1866
}
1867
1868
/**
1869
* Gets the extremum value of `collection` invoking `iteratee` for each value
1870
* in `collection` to generate the criterion by which the value is ranked.
1871
* The `iteratee` is invoked with three arguments: (value, index|key, collection).
1872
*
1873
* @private
1874
* @param {Array|Object|string} collection The collection to iterate over.
1875
* @param {Function} iteratee The function invoked per iteration.
1876
* @param {Function} comparator The function used to compare values.
1877
* @param {*} exValue The initial extremum value.
1878
* @returns {*} Returns the extremum value.
1879
*/
1880
function baseExtremum(collection, iteratee, comparator, exValue) {
1881
var computed = exValue,
1882
result = computed;
1883
1884
baseEach(collection, function(value, index, collection) {
1885
var current = +iteratee(value, index, collection);
1886
if (comparator(current, computed) || (current === exValue && current === result)) {
1887
computed = current;
1888
result = value;
1889
}
1890
});
1891
return result;
1892
}
1893
1894
/**
1895
* The base implementation of `_.fill` without an iteratee call guard.
1896
*
1897
* @private
1898
* @param {Array} array The array to fill.
1899
* @param {*} value The value to fill `array` with.
1900
* @param {number} [start=0] The start position.
1901
* @param {number} [end=array.length] The end position.
1902
* @returns {Array} Returns `array`.
1903
*/
1904
function baseFill(array, value, start, end) {
1905
var length = array.length;
1906
1907
start = start == null ? 0 : (+start || 0);
1908
if (start < 0) {
1909
start = -start > length ? 0 : (length + start);
1910
}
1911
end = (end === undefined || end > length) ? length : (+end || 0);
1912
if (end < 0) {
1913
end += length;
1914
}
1915
length = start > end ? 0 : (end >>> 0);
1916
start >>>= 0;
1917
1918
while (start < length) {
1919
array[start++] = value;
1920
}
1921
return array;
1922
}
1923
1924
/**
1925
* The base implementation of `_.filter` without support for callback
1926
* shorthands and `this` binding.
1927
*
1928
* @private
1929
* @param {Array|Object|string} collection The collection to iterate over.
1930
* @param {Function} predicate The function invoked per iteration.
1931
* @returns {Array} Returns the new filtered array.
1932
*/
1933
function baseFilter(collection, predicate) {
1934
var result = [];
1935
baseEach(collection, function(value, index, collection) {
1936
if (predicate(value, index, collection)) {
1937
result.push(value);
1938
}
1939
});
1940
return result;
1941
}
1942
1943
/**
1944
* The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
1945
* without support for callback shorthands and `this` binding, which iterates
1946
* over `collection` using the provided `eachFunc`.
1947
*
1948
* @private
1949
* @param {Array|Object|string} collection The collection to search.
1950
* @param {Function} predicate The function invoked per iteration.
1951
* @param {Function} eachFunc The function to iterate over `collection`.
1952
* @param {boolean} [retKey] Specify returning the key of the found element
1953
* instead of the element itself.
1954
* @returns {*} Returns the found element or its key, else `undefined`.
1955
*/
1956
function baseFind(collection, predicate, eachFunc, retKey) {
1957
var result;
1958
eachFunc(collection, function(value, key, collection) {
1959
if (predicate(value, key, collection)) {
1960
result = retKey ? key : value;
1961
return false;
1962
}
1963
});
1964
return result;
1965
}
1966
1967
/**
1968
* The base implementation of `_.flatten` with added support for restricting
1969
* flattening and specifying the start index.
1970
*
1971
* @private
1972
* @param {Array} array The array to flatten.
1973
* @param {boolean} [isDeep] Specify a deep flatten.
1974
* @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
1975
* @returns {Array} Returns the new flattened array.
1976
*/
1977
function baseFlatten(array, isDeep, isStrict) {
1978
var index = -1,
1979
length = array.length,
1980
resIndex = -1,
1981
result = [];
1982
1983
while (++index < length) {
1984
var value = array[index];
1985
if (isObjectLike(value) && isArrayLike(value) &&
1986
(isStrict || isArray(value) || isArguments(value))) {
1987
if (isDeep) {
1988
// Recursively flatten arrays (susceptible to call stack limits).
1989
value = baseFlatten(value, isDeep, isStrict);
1990
}
1991
var valIndex = -1,
1992
valLength = value.length;
1993
1994
while (++valIndex < valLength) {
1995
result[++resIndex] = value[valIndex];
1996
}
1997
} else if (!isStrict) {
1998
result[++resIndex] = value;
1999
}
2000
}
2001
return result;
2002
}
2003
2004
/**
2005
* The base implementation of `baseForIn` and `baseForOwn` which iterates
2006
* over `object` properties returned by `keysFunc` invoking `iteratee` for
2007
* each property. Iteratee functions may exit iteration early by explicitly
2008
* returning `false`.
2009
*
2010
* @private
2011
* @param {Object} object The object to iterate over.
2012
* @param {Function} iteratee The function invoked per iteration.
2013
* @param {Function} keysFunc The function to get the keys of `object`.
2014
* @returns {Object} Returns `object`.
2015
*/
2016
var baseFor = createBaseFor();
2017
2018
/**
2019
* This function is like `baseFor` except that it iterates over properties
2020
* in the opposite order.
2021
*
2022
* @private
2023
* @param {Object} object The object to iterate over.
2024
* @param {Function} iteratee The function invoked per iteration.
2025
* @param {Function} keysFunc The function to get the keys of `object`.
2026
* @returns {Object} Returns `object`.
2027
*/
2028
var baseForRight = createBaseFor(true);
2029
2030
/**
2031
* The base implementation of `_.forIn` without support for callback
2032
* shorthands and `this` binding.
2033
*
2034
* @private
2035
* @param {Object} object The object to iterate over.
2036
* @param {Function} iteratee The function invoked per iteration.
2037
* @returns {Object} Returns `object`.
2038
*/
2039
function baseForIn(object, iteratee) {
2040
return baseFor(object, iteratee, keysIn);
2041
}
2042
2043
/**
2044
* The base implementation of `_.forOwn` without support for callback
2045
* shorthands and `this` binding.
2046
*
2047
* @private
2048
* @param {Object} object The object to iterate over.
2049
* @param {Function} iteratee The function invoked per iteration.
2050
* @returns {Object} Returns `object`.
2051
*/
2052
function baseForOwn(object, iteratee) {
2053
return baseFor(object, iteratee, keys);
2054
}
2055
2056
/**
2057
* The base implementation of `_.forOwnRight` without support for callback
2058
* shorthands and `this` binding.
2059
*
2060
* @private
2061
* @param {Object} object The object to iterate over.
2062
* @param {Function} iteratee The function invoked per iteration.
2063
* @returns {Object} Returns `object`.
2064
*/
2065
function baseForOwnRight(object, iteratee) {
2066
return baseForRight(object, iteratee, keys);
2067
}
2068
2069
/**
2070
* The base implementation of `_.functions` which creates an array of
2071
* `object` function property names filtered from those provided.
2072
*
2073
* @private
2074
* @param {Object} object The object to inspect.
2075
* @param {Array} props The property names to filter.
2076
* @returns {Array} Returns the new array of filtered property names.
2077
*/
2078
function baseFunctions(object, props) {
2079
var index = -1,
2080
length = props.length,
2081
resIndex = -1,
2082
result = [];
2083
2084
while (++index < length) {
2085
var key = props[index];
2086
if (isFunction(object[key])) {
2087
result[++resIndex] = key;
2088
}
2089
}
2090
return result;
2091
}
2092
2093
/**
2094
* The base implementation of `get` without support for string paths
2095
* and default values.
2096
*
2097
* @private
2098
* @param {Object} object The object to query.
2099
* @param {Array} path The path of the property to get.
2100
* @param {string} [pathKey] The key representation of path.
2101
* @returns {*} Returns the resolved value.
2102
*/
2103
function baseGet(object, path, pathKey) {
2104
if (object == null) {
2105
return;
2106
}
2107
if (pathKey !== undefined && pathKey in toObject(object)) {
2108
path = [pathKey];
2109
}
2110
var index = 0,
2111
length = path.length;
2112
2113
while (object != null && index < length) {
2114
object = object[path[index++]];
2115
}
2116
return (index && index == length) ? object : undefined;
2117
}
2118
2119
/**
2120
* The base implementation of `_.isEqual` without support for `this` binding
2121
* `customizer` functions.
2122
*
2123
* @private
2124
* @param {*} value The value to compare.
2125
* @param {*} other The other value to compare.
2126
* @param {Function} [customizer] The function to customize comparing values.
2127
* @param {boolean} [isLoose] Specify performing partial comparisons.
2128
* @param {Array} [stackA] Tracks traversed `value` objects.
2129
* @param {Array} [stackB] Tracks traversed `other` objects.
2130
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
2131
*/
2132
function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
2133
if (value === other) {
2134
return true;
2135
}
2136
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
2137
return value !== value && other !== other;
2138
}
2139
return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
2140
}
2141
2142
/**
2143
* A specialized version of `baseIsEqual` for arrays and objects which performs
2144
* deep comparisons and tracks traversed objects enabling objects with circular
2145
* references to be compared.
2146
*
2147
* @private
2148
* @param {Object} object The object to compare.
2149
* @param {Object} other The other object to compare.
2150
* @param {Function} equalFunc The function to determine equivalents of values.
2151
* @param {Function} [customizer] The function to customize comparing objects.
2152
* @param {boolean} [isLoose] Specify performing partial comparisons.
2153
* @param {Array} [stackA=[]] Tracks traversed `value` objects.
2154
* @param {Array} [stackB=[]] Tracks traversed `other` objects.
2155
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
2156
*/
2157
function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
2158
var objIsArr = isArray(object),
2159
othIsArr = isArray(other),
2160
objTag = arrayTag,
2161
othTag = arrayTag;
2162
2163
if (!objIsArr) {
2164
objTag = objToString.call(object);
2165
if (objTag == argsTag) {
2166
objTag = objectTag;
2167
} else if (objTag != objectTag) {
2168
objIsArr = isTypedArray(object);
2169
}
2170
}
2171
if (!othIsArr) {
2172
othTag = objToString.call(other);
2173
if (othTag == argsTag) {
2174
othTag = objectTag;
2175
} else if (othTag != objectTag) {
2176
othIsArr = isTypedArray(other);
2177
}
2178
}
2179
var objIsObj = objTag == objectTag,
2180
othIsObj = othTag == objectTag,
2181
isSameTag = objTag == othTag;
2182
2183
if (isSameTag && !(objIsArr || objIsObj)) {
2184
return equalByTag(object, other, objTag);
2185
}
2186
if (!isLoose) {
2187
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
2188
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
2189
2190
if (objIsWrapped || othIsWrapped) {
2191
return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
2192
}
2193
}
2194
if (!isSameTag) {
2195
return false;
2196
}
2197
// Assume cyclic values are equal.
2198
// For more information on detecting circular references see https://es5.github.io/#JO.
2199
stackA || (stackA = []);
2200
stackB || (stackB = []);
2201
2202
var length = stackA.length;
2203
while (length--) {
2204
if (stackA[length] == object) {
2205
return stackB[length] == other;
2206
}
2207
}
2208
// Add `object` and `other` to the stack of traversed objects.
2209
stackA.push(object);
2210
stackB.push(other);
2211
2212
var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
2213
2214
stackA.pop();
2215
stackB.pop();
2216
2217
return result;
2218
}
2219
2220
/**
2221
* The base implementation of `_.isMatch` without support for callback
2222
* shorthands and `this` binding.
2223
*
2224
* @private
2225
* @param {Object} object The object to inspect.
2226
* @param {Array} matchData The propery names, values, and compare flags to match.
2227
* @param {Function} [customizer] The function to customize comparing objects.
2228
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
2229
*/
2230
function baseIsMatch(object, matchData, customizer) {
2231
var index = matchData.length,
2232
length = index,
2233
noCustomizer = !customizer;
2234
2235
if (object == null) {
2236
return !length;
2237
}
2238
object = toObject(object);
2239
while (index--) {
2240
var data = matchData[index];
2241
if ((noCustomizer && data[2])
2242
? data[1] !== object[data[0]]
2243
: !(data[0] in object)
2244
) {
2245
return false;
2246
}
2247
}
2248
while (++index < length) {
2249
data = matchData[index];
2250
var key = data[0],
2251
objValue = object[key],
2252
srcValue = data[1];
2253
2254
if (noCustomizer && data[2]) {
2255
if (objValue === undefined && !(key in object)) {
2256
return false;
2257
}
2258
} else {
2259
var result = customizer ? customizer(objValue, srcValue, key) : undefined;
2260
if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
2261
return false;
2262
}
2263
}
2264
}
2265
return true;
2266
}
2267
2268
/**
2269
* The base implementation of `_.map` without support for callback shorthands
2270
* and `this` binding.
2271
*
2272
* @private
2273
* @param {Array|Object|string} collection The collection to iterate over.
2274
* @param {Function} iteratee The function invoked per iteration.
2275
* @returns {Array} Returns the new mapped array.
2276
*/
2277
function baseMap(collection, iteratee) {
2278
var index = -1,
2279
result = isArrayLike(collection) ? Array(collection.length) : [];
2280
2281
baseEach(collection, function(value, key, collection) {
2282
result[++index] = iteratee(value, key, collection);
2283
});
2284
return result;
2285
}
2286
2287
/**
2288
* The base implementation of `_.matches` which does not clone `source`.
2289
*
2290
* @private
2291
* @param {Object} source The object of property values to match.
2292
* @returns {Function} Returns the new function.
2293
*/
2294
function baseMatches(source) {
2295
var matchData = getMatchData(source);
2296
if (matchData.length == 1 && matchData[0][2]) {
2297
var key = matchData[0][0],
2298
value = matchData[0][1];
2299
2300
return function(object) {
2301
if (object == null) {
2302
return false;
2303
}
2304
return object[key] === value && (value !== undefined || (key in toObject(object)));
2305
};
2306
}
2307
return function(object) {
2308
return baseIsMatch(object, matchData);
2309
};
2310
}
2311
2312
/**
2313
* The base implementation of `_.matchesProperty` which does not clone `srcValue`.
2314
*
2315
* @private
2316
* @param {string} path The path of the property to get.
2317
* @param {*} srcValue The value to compare.
2318
* @returns {Function} Returns the new function.
2319
*/
2320
function baseMatchesProperty(path, srcValue) {
2321
var isArr = isArray(path),
2322
isCommon = isKey(path) && isStrictComparable(srcValue),
2323
pathKey = (path + '');
2324
2325
path = toPath(path);
2326
return function(object) {
2327
if (object == null) {
2328
return false;
2329
}
2330
var key = pathKey;
2331
object = toObject(object);
2332
if ((isArr || !isCommon) && !(key in object)) {
2333
object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
2334
if (object == null) {
2335
return false;
2336
}
2337
key = last(path);
2338
object = toObject(object);
2339
}
2340
return object[key] === srcValue
2341
? (srcValue !== undefined || (key in object))
2342
: baseIsEqual(srcValue, object[key], undefined, true);
2343
};
2344
}
2345
2346
/**
2347
* The base implementation of `_.merge` without support for argument juggling,
2348
* multiple sources, and `this` binding `customizer` functions.
2349
*
2350
* @private
2351
* @param {Object} object The destination object.
2352
* @param {Object} source The source object.
2353
* @param {Function} [customizer] The function to customize merging properties.
2354
* @param {Array} [stackA=[]] Tracks traversed source objects.
2355
* @param {Array} [stackB=[]] Associates values with source counterparts.
2356
* @returns {Object} Returns `object`.
2357
*/
2358
function baseMerge(object, source, customizer, stackA, stackB) {
2359
if (!isObject(object)) {
2360
return object;
2361
}
2362
var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
2363
props = isSrcArr ? null : keys(source);
2364
2365
arrayEach(props || source, function(srcValue, key) {
2366
if (props) {
2367
key = srcValue;
2368
srcValue = source[key];
2369
}
2370
if (isObjectLike(srcValue)) {
2371
stackA || (stackA = []);
2372
stackB || (stackB = []);
2373
baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
2374
}
2375
else {
2376
var value = object[key],
2377
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
2378
isCommon = result === undefined;
2379
2380
if (isCommon) {
2381
result = srcValue;
2382
}
2383
if ((result !== undefined || (isSrcArr && !(key in object))) &&
2384
(isCommon || (result === result ? (result !== value) : (value === value)))) {
2385
object[key] = result;
2386
}
2387
}
2388
});
2389
return object;
2390
}
2391
2392
/**
2393
* A specialized version of `baseMerge` for arrays and objects which performs
2394
* deep merges and tracks traversed objects enabling objects with circular
2395
* references to be merged.
2396
*
2397
* @private
2398
* @param {Object} object The destination object.
2399
* @param {Object} source The source object.
2400
* @param {string} key The key of the value to merge.
2401
* @param {Function} mergeFunc The function to merge values.
2402
* @param {Function} [customizer] The function to customize merging properties.
2403
* @param {Array} [stackA=[]] Tracks traversed source objects.
2404
* @param {Array} [stackB=[]] Associates values with source counterparts.
2405
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
2406
*/
2407
function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
2408
var length = stackA.length,
2409
srcValue = source[key];
2410
2411
while (length--) {
2412
if (stackA[length] == srcValue) {
2413
object[key] = stackB[length];
2414
return;
2415
}
2416
}
2417
var value = object[key],
2418
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
2419
isCommon = result === undefined;
2420
2421
if (isCommon) {
2422
result = srcValue;
2423
if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
2424
result = isArray(value)
2425
? value
2426
: (isArrayLike(value) ? arrayCopy(value) : []);
2427
}
2428
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
2429
result = isArguments(value)
2430
? toPlainObject(value)
2431
: (isPlainObject(value) ? value : {});
2432
}
2433
else {
2434
isCommon = false;
2435
}
2436
}
2437
// Add the source value to the stack of traversed objects and associate
2438
// it with its merged value.
2439
stackA.push(srcValue);
2440
stackB.push(result);
2441
2442
if (isCommon) {
2443
// Recursively merge objects and arrays (susceptible to call stack limits).
2444
object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
2445
} else if (result === result ? (result !== value) : (value === value)) {
2446
object[key] = result;
2447
}
2448
}
2449
2450
/**
2451
* The base implementation of `_.property` without support for deep paths.
2452
*
2453
* @private
2454
* @param {string} key The key of the property to get.
2455
* @returns {Function} Returns the new function.
2456
*/
2457
function baseProperty(key) {
2458
return function(object) {
2459
return object == null ? undefined : object[key];
2460
};
2461
}
2462
2463
/**
2464
* A specialized version of `baseProperty` which supports deep paths.
2465
*
2466
* @private
2467
* @param {Array|string} path The path of the property to get.
2468
* @returns {Function} Returns the new function.
2469
*/
2470
function basePropertyDeep(path) {
2471
var pathKey = (path + '');
2472
path = toPath(path);
2473
return function(object) {
2474
return baseGet(object, path, pathKey);
2475
};
2476
}
2477
2478
/**
2479
* The base implementation of `_.pullAt` without support for individual
2480
* index arguments and capturing the removed elements.
2481
*
2482
* @private
2483
* @param {Array} array The array to modify.
2484
* @param {number[]} indexes The indexes of elements to remove.
2485
* @returns {Array} Returns `array`.
2486
*/
2487
function basePullAt(array, indexes) {
2488
var length = array ? indexes.length : 0;
2489
while (length--) {
2490
var index = indexes[length];
2491
if (index != previous && isIndex(index)) {
2492
var previous = index;
2493
splice.call(array, index, 1);
2494
}
2495
}
2496
return array;
2497
}
2498
2499
/**
2500
* The base implementation of `_.random` without support for argument juggling
2501
* and returning floating-point numbers.
2502
*
2503
* @private
2504
* @param {number} min The minimum possible value.
2505
* @param {number} max The maximum possible value.
2506
* @returns {number} Returns the random number.
2507
*/
2508
function baseRandom(min, max) {
2509
return min + floor(nativeRandom() * (max - min + 1));
2510
}
2511
2512
/**
2513
* The base implementation of `_.reduce` and `_.reduceRight` without support
2514
* for callback shorthands and `this` binding, which iterates over `collection`
2515
* using the provided `eachFunc`.
2516
*
2517
* @private
2518
* @param {Array|Object|string} collection The collection to iterate over.
2519
* @param {Function} iteratee The function invoked per iteration.
2520
* @param {*} accumulator The initial value.
2521
* @param {boolean} initFromCollection Specify using the first or last element
2522
* of `collection` as the initial value.
2523
* @param {Function} eachFunc The function to iterate over `collection`.
2524
* @returns {*} Returns the accumulated value.
2525
*/
2526
function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
2527
eachFunc(collection, function(value, index, collection) {
2528
accumulator = initFromCollection
2529
? (initFromCollection = false, value)
2530
: iteratee(accumulator, value, index, collection);
2531
});
2532
return accumulator;
2533
}
2534
2535
/**
2536
* The base implementation of `setData` without support for hot loop detection.
2537
*
2538
* @private
2539
* @param {Function} func The function to associate metadata with.
2540
* @param {*} data The metadata.
2541
* @returns {Function} Returns `func`.
2542
*/
2543
var baseSetData = !metaMap ? identity : function(func, data) {
2544
metaMap.set(func, data);
2545
return func;
2546
};
2547
2548
/**
2549
* The base implementation of `_.slice` without an iteratee call guard.
2550
*
2551
* @private
2552
* @param {Array} array The array to slice.
2553
* @param {number} [start=0] The start position.
2554
* @param {number} [end=array.length] The end position.
2555
* @returns {Array} Returns the slice of `array`.
2556
*/
2557
function baseSlice(array, start, end) {
2558
var index = -1,
2559
length = array.length;
2560
2561
start = start == null ? 0 : (+start || 0);
2562
if (start < 0) {
2563
start = -start > length ? 0 : (length + start);
2564
}
2565
end = (end === undefined || end > length) ? length : (+end || 0);
2566
if (end < 0) {
2567
end += length;
2568
}
2569
length = start > end ? 0 : ((end - start) >>> 0);
2570
start >>>= 0;
2571
2572
var result = Array(length);
2573
while (++index < length) {
2574
result[index] = array[index + start];
2575
}
2576
return result;
2577
}
2578
2579
/**
2580
* The base implementation of `_.some` without support for callback shorthands
2581
* and `this` binding.
2582
*
2583
* @private
2584
* @param {Array|Object|string} collection The collection to iterate over.
2585
* @param {Function} predicate The function invoked per iteration.
2586
* @returns {boolean} Returns `true` if any element passes the predicate check,
2587
* else `false`.
2588
*/
2589
function baseSome(collection, predicate) {
2590
var result;
2591
2592
baseEach(collection, function(value, index, collection) {
2593
result = predicate(value, index, collection);
2594
return !result;
2595
});
2596
return !!result;
2597
}
2598
2599
/**
2600
* The base implementation of `_.sortBy` which uses `comparer` to define
2601
* the sort order of `array` and replaces criteria objects with their
2602
* corresponding values.
2603
*
2604
* @private
2605
* @param {Array} array The array to sort.
2606
* @param {Function} comparer The function to define sort order.
2607
* @returns {Array} Returns `array`.
2608
*/
2609
function baseSortBy(array, comparer) {
2610
var length = array.length;
2611
2612
array.sort(comparer);
2613
while (length--) {
2614
array[length] = array[length].value;
2615
}
2616
return array;
2617
}
2618
2619
/**
2620
* The base implementation of `_.sortByOrder` without param guards.
2621
*
2622
* @private
2623
* @param {Array|Object|string} collection The collection to iterate over.
2624
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
2625
* @param {boolean[]} orders The sort orders of `iteratees`.
2626
* @returns {Array} Returns the new sorted array.
2627
*/
2628
function baseSortByOrder(collection, iteratees, orders) {
2629
var callback = getCallback(),
2630
index = -1;
2631
2632
iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); });
2633
2634
var result = baseMap(collection, function(value) {
2635
var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); });
2636
return { 'criteria': criteria, 'index': ++index, 'value': value };
2637
});
2638
2639
return baseSortBy(result, function(object, other) {
2640
return compareMultiple(object, other, orders);
2641
});
2642
}
2643
2644
/**
2645
* The base implementation of `_.sum` without support for callback shorthands
2646
* and `this` binding.
2647
*
2648
* @private
2649
* @param {Array|Object|string} collection The collection to iterate over.
2650
* @param {Function} iteratee The function invoked per iteration.
2651
* @returns {number} Returns the sum.
2652
*/
2653
function baseSum(collection, iteratee) {
2654
var result = 0;
2655
baseEach(collection, function(value, index, collection) {
2656
result += +iteratee(value, index, collection) || 0;
2657
});
2658
return result;
2659
}
2660
2661
/**
2662
* The base implementation of `_.uniq` without support for callback shorthands
2663
* and `this` binding.
2664
*
2665
* @private
2666
* @param {Array} array The array to inspect.
2667
* @param {Function} [iteratee] The function invoked per iteration.
2668
* @returns {Array} Returns the new duplicate-value-free array.
2669
*/
2670
function baseUniq(array, iteratee) {
2671
var index = -1,
2672
indexOf = getIndexOf(),
2673
length = array.length,
2674
isCommon = indexOf == baseIndexOf,
2675
isLarge = isCommon && length >= 200,
2676
seen = isLarge ? createCache() : null,
2677
result = [];
2678
2679
if (seen) {
2680
indexOf = cacheIndexOf;
2681
isCommon = false;
2682
} else {
2683
isLarge = false;
2684
seen = iteratee ? [] : result;
2685
}
2686
outer:
2687
while (++index < length) {
2688
var value = array[index],
2689
computed = iteratee ? iteratee(value, index, array) : value;
2690
2691
if (isCommon && value === value) {
2692
var seenIndex = seen.length;
2693
while (seenIndex--) {
2694
if (seen[seenIndex] === computed) {
2695
continue outer;
2696
}
2697
}
2698
if (iteratee) {
2699
seen.push(computed);
2700
}
2701
result.push(value);
2702
}
2703
else if (indexOf(seen, computed, 0) < 0) {
2704
if (iteratee || isLarge) {
2705
seen.push(computed);
2706
}
2707
result.push(value);
2708
}
2709
}
2710
return result;
2711
}
2712
2713
/**
2714
* The base implementation of `_.values` and `_.valuesIn` which creates an
2715
* array of `object` property values corresponding to the property names
2716
* of `props`.
2717
*
2718
* @private
2719
* @param {Object} object The object to query.
2720
* @param {Array} props The property names to get values for.
2721
* @returns {Object} Returns the array of property values.
2722
*/
2723
function baseValues(object, props) {
2724
var index = -1,
2725
length = props.length,
2726
result = Array(length);
2727
2728
while (++index < length) {
2729
result[index] = object[props[index]];
2730
}
2731
return result;
2732
}
2733
2734
/**
2735
* The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
2736
* and `_.takeWhile` without support for callback shorthands and `this` binding.
2737
*
2738
* @private
2739
* @param {Array} array The array to query.
2740
* @param {Function} predicate The function invoked per iteration.
2741
* @param {boolean} [isDrop] Specify dropping elements instead of taking them.
2742
* @param {boolean} [fromRight] Specify iterating from right to left.
2743
* @returns {Array} Returns the slice of `array`.
2744
*/
2745
function baseWhile(array, predicate, isDrop, fromRight) {
2746
var length = array.length,
2747
index = fromRight ? length : -1;
2748
2749
while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
2750
return isDrop
2751
? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
2752
: baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
2753
}
2754
2755
/**
2756
* The base implementation of `wrapperValue` which returns the result of
2757
* performing a sequence of actions on the unwrapped `value`, where each
2758
* successive action is supplied the return value of the previous.
2759
*
2760
* @private
2761
* @param {*} value The unwrapped value.
2762
* @param {Array} actions Actions to peform to resolve the unwrapped value.
2763
* @returns {*} Returns the resolved value.
2764
*/
2765
function baseWrapperValue(value, actions) {
2766
var result = value;
2767
if (result instanceof LazyWrapper) {
2768
result = result.value();
2769
}
2770
var index = -1,
2771
length = actions.length;
2772
2773
while (++index < length) {
2774
var args = [result],
2775
action = actions[index];
2776
2777
push.apply(args, action.args);
2778
result = action.func.apply(action.thisArg, args);
2779
}
2780
return result;
2781
}
2782
2783
/**
2784
* Performs a binary search of `array` to determine the index at which `value`
2785
* should be inserted into `array` in order to maintain its sort order.
2786
*
2787
* @private
2788
* @param {Array} array The sorted array to inspect.
2789
* @param {*} value The value to evaluate.
2790
* @param {boolean} [retHighest] Specify returning the highest qualified index.
2791
* @returns {number} Returns the index at which `value` should be inserted
2792
* into `array`.
2793
*/
2794
function binaryIndex(array, value, retHighest) {
2795
var low = 0,
2796
high = array ? array.length : low;
2797
2798
if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
2799
while (low < high) {
2800
var mid = (low + high) >>> 1,
2801
computed = array[mid];
2802
2803
if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
2804
low = mid + 1;
2805
} else {
2806
high = mid;
2807
}
2808
}
2809
return high;
2810
}
2811
return binaryIndexBy(array, value, identity, retHighest);
2812
}
2813
2814
/**
2815
* This function is like `binaryIndex` except that it invokes `iteratee` for
2816
* `value` and each element of `array` to compute their sort ranking. The
2817
* iteratee is invoked with one argument; (value).
2818
*
2819
* @private
2820
* @param {Array} array The sorted array to inspect.
2821
* @param {*} value The value to evaluate.
2822
* @param {Function} iteratee The function invoked per iteration.
2823
* @param {boolean} [retHighest] Specify returning the highest qualified index.
2824
* @returns {number} Returns the index at which `value` should be inserted
2825
* into `array`.
2826
*/
2827
function binaryIndexBy(array, value, iteratee, retHighest) {
2828
value = iteratee(value);
2829
2830
var low = 0,
2831
high = array ? array.length : 0,
2832
valIsNaN = value !== value,
2833
valIsNull = value === null,
2834
valIsUndef = value === undefined;
2835
2836
while (low < high) {
2837
var mid = floor((low + high) / 2),
2838
computed = iteratee(array[mid]),
2839
isDef = computed !== undefined,
2840
isReflexive = computed === computed;
2841
2842
if (valIsNaN) {
2843
var setLow = isReflexive || retHighest;
2844
} else if (valIsNull) {
2845
setLow = isReflexive && isDef && (retHighest || computed != null);
2846
} else if (valIsUndef) {
2847
setLow = isReflexive && (retHighest || isDef);
2848
} else if (computed == null) {
2849
setLow = false;
2850
} else {
2851
setLow = retHighest ? (computed <= value) : (computed < value);
2852
}
2853
if (setLow) {
2854
low = mid + 1;
2855
} else {
2856
high = mid;
2857
}
2858
}
2859
return nativeMin(high, MAX_ARRAY_INDEX);
2860
}
2861
2862
/**
2863
* A specialized version of `baseCallback` which only supports `this` binding
2864
* and specifying the number of arguments to provide to `func`.
2865
*
2866
* @private
2867
* @param {Function} func The function to bind.
2868
* @param {*} thisArg The `this` binding of `func`.
2869
* @param {number} [argCount] The number of arguments to provide to `func`.
2870
* @returns {Function} Returns the callback.
2871
*/
2872
function bindCallback(func, thisArg, argCount) {
2873
if (typeof func != 'function') {
2874
return identity;
2875
}
2876
if (thisArg === undefined) {
2877
return func;
2878
}
2879
switch (argCount) {
2880
case 1: return function(value) {
2881
return func.call(thisArg, value);
2882
};
2883
case 3: return function(value, index, collection) {
2884
return func.call(thisArg, value, index, collection);
2885
};
2886
case 4: return function(accumulator, value, index, collection) {
2887
return func.call(thisArg, accumulator, value, index, collection);
2888
};
2889
case 5: return function(value, other, key, object, source) {
2890
return func.call(thisArg, value, other, key, object, source);
2891
};
2892
}
2893
return function() {
2894
return func.apply(thisArg, arguments);
2895
};
2896
}
2897
2898
/**
2899
* Creates a clone of the given array buffer.
2900
*
2901
* @private
2902
* @param {ArrayBuffer} buffer The array buffer to clone.
2903
* @returns {ArrayBuffer} Returns the cloned array buffer.
2904
*/
2905
function bufferClone(buffer) {
2906
return bufferSlice.call(buffer, 0);
2907
}
2908
if (!bufferSlice) {
2909
// PhantomJS has `ArrayBuffer` and `Uint8Array` but not `Float64Array`.
2910
bufferClone = !(ArrayBuffer && Uint8Array) ? constant(null) : function(buffer) {
2911
var byteLength = buffer.byteLength,
2912
floatLength = Float64Array ? floor(byteLength / FLOAT64_BYTES_PER_ELEMENT) : 0,
2913
offset = floatLength * FLOAT64_BYTES_PER_ELEMENT,
2914
result = new ArrayBuffer(byteLength);
2915
2916
if (floatLength) {
2917
var view = new Float64Array(result, 0, floatLength);
2918
view.set(new Float64Array(buffer, 0, floatLength));
2919
}
2920
if (byteLength != offset) {
2921
view = new Uint8Array(result, offset);
2922
view.set(new Uint8Array(buffer, offset));
2923
}
2924
return result;
2925
};
2926
}
2927
2928
/**
2929
* Creates an array that is the composition of partially applied arguments,
2930
* placeholders, and provided arguments into a single array of arguments.
2931
*
2932
* @private
2933
* @param {Array|Object} args The provided arguments.
2934
* @param {Array} partials The arguments to prepend to those provided.
2935
* @param {Array} holders The `partials` placeholder indexes.
2936
* @returns {Array} Returns the new array of composed arguments.
2937
*/
2938
function composeArgs(args, partials, holders) {
2939
var holdersLength = holders.length,
2940
argsIndex = -1,
2941
argsLength = nativeMax(args.length - holdersLength, 0),
2942
leftIndex = -1,
2943
leftLength = partials.length,
2944
result = Array(argsLength + leftLength);
2945
2946
while (++leftIndex < leftLength) {
2947
result[leftIndex] = partials[leftIndex];
2948
}
2949
while (++argsIndex < holdersLength) {
2950
result[holders[argsIndex]] = args[argsIndex];
2951
}
2952
while (argsLength--) {
2953
result[leftIndex++] = args[argsIndex++];
2954
}
2955
return result;
2956
}
2957
2958
/**
2959
* This function is like `composeArgs` except that the arguments composition
2960
* is tailored for `_.partialRight`.
2961
*
2962
* @private
2963
* @param {Array|Object} args The provided arguments.
2964
* @param {Array} partials The arguments to append to those provided.
2965
* @param {Array} holders The `partials` placeholder indexes.
2966
* @returns {Array} Returns the new array of composed arguments.
2967
*/
2968
function composeArgsRight(args, partials, holders) {
2969
var holdersIndex = -1,
2970
holdersLength = holders.length,
2971
argsIndex = -1,
2972
argsLength = nativeMax(args.length - holdersLength, 0),
2973
rightIndex = -1,
2974
rightLength = partials.length,
2975
result = Array(argsLength + rightLength);
2976
2977
while (++argsIndex < argsLength) {
2978
result[argsIndex] = args[argsIndex];
2979
}
2980
var offset = argsIndex;
2981
while (++rightIndex < rightLength) {
2982
result[offset + rightIndex] = partials[rightIndex];
2983
}
2984
while (++holdersIndex < holdersLength) {
2985
result[offset + holders[holdersIndex]] = args[argsIndex++];
2986
}
2987
return result;
2988
}
2989
2990
/**
2991
* Creates a function that aggregates a collection, creating an accumulator
2992
* object composed from the results of running each element in the collection
2993
* through an iteratee.
2994
*
2995
* **Note:** This function is used to create `_.countBy`, `_.groupBy`, `_.indexBy`,
2996
* and `_.partition`.
2997
*
2998
* @private
2999
* @param {Function} setter The function to set keys and values of the accumulator object.
3000
* @param {Function} [initializer] The function to initialize the accumulator object.
3001
* @returns {Function} Returns the new aggregator function.
3002
*/
3003
function createAggregator(setter, initializer) {
3004
return function(collection, iteratee, thisArg) {
3005
var result = initializer ? initializer() : {};
3006
iteratee = getCallback(iteratee, thisArg, 3);
3007
3008
if (isArray(collection)) {
3009
var index = -1,
3010
length = collection.length;
3011
3012
while (++index < length) {
3013
var value = collection[index];
3014
setter(result, value, iteratee(value, index, collection), collection);
3015
}
3016
} else {
3017
baseEach(collection, function(value, key, collection) {
3018
setter(result, value, iteratee(value, key, collection), collection);
3019
});
3020
}
3021
return result;
3022
};
3023
}
3024
3025
/**
3026
* Creates a function that assigns properties of source object(s) to a given
3027
* destination object.
3028
*
3029
* **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`.
3030
*
3031
* @private
3032
* @param {Function} assigner The function to assign values.
3033
* @returns {Function} Returns the new assigner function.
3034
*/
3035
function createAssigner(assigner) {
3036
return restParam(function(object, sources) {
3037
var index = -1,
3038
length = object == null ? 0 : sources.length,
3039
customizer = length > 2 ? sources[length - 2] : undefined,
3040
guard = length > 2 ? sources[2] : undefined,
3041
thisArg = length > 1 ? sources[length - 1] : undefined;
3042
3043
if (typeof customizer == 'function') {
3044
customizer = bindCallback(customizer, thisArg, 5);
3045
length -= 2;
3046
} else {
3047
customizer = typeof thisArg == 'function' ? thisArg : undefined;
3048
length -= (customizer ? 1 : 0);
3049
}
3050
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
3051
customizer = length < 3 ? undefined : customizer;
3052
length = 1;
3053
}
3054
while (++index < length) {
3055
var source = sources[index];
3056
if (source) {
3057
assigner(object, source, customizer);
3058
}
3059
}
3060
return object;
3061
});
3062
}
3063
3064
/**
3065
* Creates a `baseEach` or `baseEachRight` function.
3066
*
3067
* @private
3068
* @param {Function} eachFunc The function to iterate over a collection.
3069
* @param {boolean} [fromRight] Specify iterating from right to left.
3070
* @returns {Function} Returns the new base function.
3071
*/
3072
function createBaseEach(eachFunc, fromRight) {
3073
return function(collection, iteratee) {
3074
var length = collection ? getLength(collection) : 0;
3075
if (!isLength(length)) {
3076
return eachFunc(collection, iteratee);
3077
}
3078
var index = fromRight ? length : -1,
3079
iterable = toObject(collection);
3080
3081
while ((fromRight ? index-- : ++index < length)) {
3082
if (iteratee(iterable[index], index, iterable) === false) {
3083
break;
3084
}
3085
}
3086
return collection;
3087
};
3088
}
3089
3090
/**
3091
* Creates a base function for `_.forIn` or `_.forInRight`.
3092
*
3093
* @private
3094
* @param {boolean} [fromRight] Specify iterating from right to left.
3095
* @returns {Function} Returns the new base function.
3096
*/
3097
function createBaseFor(fromRight) {
3098
return function(object, iteratee, keysFunc) {
3099
var iterable = toObject(object),
3100
props = keysFunc(object),
3101
length = props.length,
3102
index = fromRight ? length : -1;
3103
3104
while ((fromRight ? index-- : ++index < length)) {
3105
var key = props[index];
3106
if (iteratee(iterable[key], key, iterable) === false) {
3107
break;
3108
}
3109
}
3110
return object;
3111
};
3112
}
3113
3114
/**
3115
* Creates a function that wraps `func` and invokes it with the `this`
3116
* binding of `thisArg`.
3117
*
3118
* @private
3119
* @param {Function} func The function to bind.
3120
* @param {*} [thisArg] The `this` binding of `func`.
3121
* @returns {Function} Returns the new bound function.
3122
*/
3123
function createBindWrapper(func, thisArg) {
3124
var Ctor = createCtorWrapper(func);
3125
3126
function wrapper() {
3127
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
3128
return fn.apply(thisArg, arguments);
3129
}
3130
return wrapper;
3131
}
3132
3133
/**
3134
* Creates a `Set` cache object to optimize linear searches of large arrays.
3135
*
3136
* @private
3137
* @param {Array} [values] The values to cache.
3138
* @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
3139
*/
3140
var createCache = !(nativeCreate && Set) ? constant(null) : function(values) {
3141
return new SetCache(values);
3142
};
3143
3144
/**
3145
* Creates a function that produces compound words out of the words in a
3146
* given string.
3147
*
3148
* @private
3149
* @param {Function} callback The function to combine each word.
3150
* @returns {Function} Returns the new compounder function.
3151
*/
3152
function createCompounder(callback) {
3153
return function(string) {
3154
var index = -1,
3155
array = words(deburr(string)),
3156
length = array.length,
3157
result = '';
3158
3159
while (++index < length) {
3160
result = callback(result, array[index], index);
3161
}
3162
return result;
3163
};
3164
}
3165
3166
/**
3167
* Creates a function that produces an instance of `Ctor` regardless of
3168
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
3169
*
3170
* @private
3171
* @param {Function} Ctor The constructor to wrap.
3172
* @returns {Function} Returns the new wrapped function.
3173
*/
3174
function createCtorWrapper(Ctor) {
3175
return function() {
3176
// Use a `switch` statement to work with class constructors.
3177
// See https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ecmascript-function-objects-call-thisargument-argumentslist
3178
// for more details.
3179
var args = arguments;
3180
switch (args.length) {
3181
case 0: return new Ctor;
3182
case 1: return new Ctor(args[0]);
3183
case 2: return new Ctor(args[0], args[1]);
3184
case 3: return new Ctor(args[0], args[1], args[2]);
3185
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
3186
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
3187
}
3188
var thisBinding = baseCreate(Ctor.prototype),
3189
result = Ctor.apply(thisBinding, args);
3190
3191
// Mimic the constructor's `return` behavior.
3192
// See https://es5.github.io/#x13.2.2 for more details.
3193
return isObject(result) ? result : thisBinding;
3194
};
3195
}
3196
3197
/**
3198
* Creates a `_.curry` or `_.curryRight` function.
3199
*
3200
* @private
3201
* @param {boolean} flag The curry bit flag.
3202
* @returns {Function} Returns the new curry function.
3203
*/
3204
function createCurry(flag) {
3205
function curryFunc(func, arity, guard) {
3206
if (guard && isIterateeCall(func, arity, guard)) {
3207
arity = null;
3208
}
3209
var result = createWrapper(func, flag, null, null, null, null, null, arity);
3210
result.placeholder = curryFunc.placeholder;
3211
return result;
3212
}
3213
return curryFunc;
3214
}
3215
3216
/**
3217
* Creates a `_.max` or `_.min` function.
3218
*
3219
* @private
3220
* @param {Function} comparator The function used to compare values.
3221
* @param {*} exValue The initial extremum value.
3222
* @returns {Function} Returns the new extremum function.
3223
*/
3224
function createExtremum(comparator, exValue) {
3225
return function(collection, iteratee, thisArg) {
3226
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
3227
iteratee = null;
3228
}
3229
iteratee = getCallback(iteratee, thisArg, 3);
3230
if (iteratee.length == 1) {
3231
collection = toIterable(collection);
3232
var result = arrayExtremum(collection, iteratee, comparator, exValue);
3233
if (!(collection.length && result === exValue)) {
3234
return result;
3235
}
3236
}
3237
return baseExtremum(collection, iteratee, comparator, exValue);
3238
};
3239
}
3240
3241
/**
3242
* Creates a `_.find` or `_.findLast` function.
3243
*
3244
* @private
3245
* @param {Function} eachFunc The function to iterate over a collection.
3246
* @param {boolean} [fromRight] Specify iterating from right to left.
3247
* @returns {Function} Returns the new find function.
3248
*/
3249
function createFind(eachFunc, fromRight) {
3250
return function(collection, predicate, thisArg) {
3251
predicate = getCallback(predicate, thisArg, 3);
3252
if (isArray(collection)) {
3253
var index = baseFindIndex(collection, predicate, fromRight);
3254
return index > -1 ? collection[index] : undefined;
3255
}
3256
return baseFind(collection, predicate, eachFunc);
3257
};
3258
}
3259
3260
/**
3261
* Creates a `_.findIndex` or `_.findLastIndex` function.
3262
*
3263
* @private
3264
* @param {boolean} [fromRight] Specify iterating from right to left.
3265
* @returns {Function} Returns the new find function.
3266
*/
3267
function createFindIndex(fromRight) {
3268
return function(array, predicate, thisArg) {
3269
if (!(array && array.length)) {
3270
return -1;
3271
}
3272
predicate = getCallback(predicate, thisArg, 3);
3273
return baseFindIndex(array, predicate, fromRight);
3274
};
3275
}
3276
3277
/**
3278
* Creates a `_.findKey` or `_.findLastKey` function.
3279
*
3280
* @private
3281
* @param {Function} objectFunc The function to iterate over an object.
3282
* @returns {Function} Returns the new find function.
3283
*/
3284
function createFindKey(objectFunc) {
3285
return function(object, predicate, thisArg) {
3286
predicate = getCallback(predicate, thisArg, 3);
3287
return baseFind(object, predicate, objectFunc, true);
3288
};
3289
}
3290
3291
/**
3292
* Creates a `_.flow` or `_.flowRight` function.
3293
*
3294
* @private
3295
* @param {boolean} [fromRight] Specify iterating from right to left.
3296
* @returns {Function} Returns the new flow function.
3297
*/
3298
function createFlow(fromRight) {
3299
return function() {
3300
var wrapper,
3301
length = arguments.length,
3302
index = fromRight ? length : -1,
3303
leftIndex = 0,
3304
funcs = Array(length);
3305
3306
while ((fromRight ? index-- : ++index < length)) {
3307
var func = funcs[leftIndex++] = arguments[index];
3308
if (typeof func != 'function') {
3309
throw new TypeError(FUNC_ERROR_TEXT);
3310
}
3311
if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') {
3312
wrapper = new LodashWrapper([]);
3313
}
3314
}
3315
index = wrapper ? -1 : length;
3316
while (++index < length) {
3317
func = funcs[index];
3318
3319
var funcName = getFuncName(func),
3320
data = funcName == 'wrapper' ? getData(func) : null;
3321
3322
if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
3323
wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
3324
} else {
3325
wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
3326
}
3327
}
3328
return function() {
3329
var args = arguments;
3330
if (wrapper && args.length == 1 && isArray(args[0])) {
3331
return wrapper.plant(args[0]).value();
3332
}
3333
var index = 0,
3334
result = length ? funcs[index].apply(this, args) : args[0];
3335
3336
while (++index < length) {
3337
result = funcs[index].call(this, result);
3338
}
3339
return result;
3340
};
3341
};
3342
}
3343
3344
/**
3345
* Creates a function for `_.forEach` or `_.forEachRight`.
3346
*
3347
* @private
3348
* @param {Function} arrayFunc The function to iterate over an array.
3349
* @param {Function} eachFunc The function to iterate over a collection.
3350
* @returns {Function} Returns the new each function.
3351
*/
3352
function createForEach(arrayFunc, eachFunc) {
3353
return function(collection, iteratee, thisArg) {
3354
return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
3355
? arrayFunc(collection, iteratee)
3356
: eachFunc(collection, bindCallback(iteratee, thisArg, 3));
3357
};
3358
}
3359
3360
/**
3361
* Creates a function for `_.forIn` or `_.forInRight`.
3362
*
3363
* @private
3364
* @param {Function} objectFunc The function to iterate over an object.
3365
* @returns {Function} Returns the new each function.
3366
*/
3367
function createForIn(objectFunc) {
3368
return function(object, iteratee, thisArg) {
3369
if (typeof iteratee != 'function' || thisArg !== undefined) {
3370
iteratee = bindCallback(iteratee, thisArg, 3);
3371
}
3372
return objectFunc(object, iteratee, keysIn);
3373
};
3374
}
3375
3376
/**
3377
* Creates a function for `_.forOwn` or `_.forOwnRight`.
3378
*
3379
* @private
3380
* @param {Function} objectFunc The function to iterate over an object.
3381
* @returns {Function} Returns the new each function.
3382
*/
3383
function createForOwn(objectFunc) {
3384
return function(object, iteratee, thisArg) {
3385
if (typeof iteratee != 'function' || thisArg !== undefined) {
3386
iteratee = bindCallback(iteratee, thisArg, 3);
3387
}
3388
return objectFunc(object, iteratee);
3389
};
3390
}
3391
3392
/**
3393
* Creates a function for `_.mapKeys` or `_.mapValues`.
3394
*
3395
* @private
3396
* @param {boolean} [isMapKeys] Specify mapping keys instead of values.
3397
* @returns {Function} Returns the new map function.
3398
*/
3399
function createObjectMapper(isMapKeys) {
3400
return function(object, iteratee, thisArg) {
3401
var result = {};
3402
iteratee = getCallback(iteratee, thisArg, 3);
3403
3404
baseForOwn(object, function(value, key, object) {
3405
var mapped = iteratee(value, key, object);
3406
key = isMapKeys ? mapped : key;
3407
value = isMapKeys ? value : mapped;
3408
result[key] = value;
3409
});
3410
return result;
3411
};
3412
}
3413
3414
/**
3415
* Creates a function for `_.padLeft` or `_.padRight`.
3416
*
3417
* @private
3418
* @param {boolean} [fromRight] Specify padding from the right.
3419
* @returns {Function} Returns the new pad function.
3420
*/
3421
function createPadDir(fromRight) {
3422
return function(string, length, chars) {
3423
string = baseToString(string);
3424
return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string);
3425
};
3426
}
3427
3428
/**
3429
* Creates a `_.partial` or `_.partialRight` function.
3430
*
3431
* @private
3432
* @param {boolean} flag The partial bit flag.
3433
* @returns {Function} Returns the new partial function.
3434
*/
3435
function createPartial(flag) {
3436
var partialFunc = restParam(function(func, partials) {
3437
var holders = replaceHolders(partials, partialFunc.placeholder);
3438
return createWrapper(func, flag, null, partials, holders);
3439
});
3440
return partialFunc;
3441
}
3442
3443
/**
3444
* Creates a function for `_.reduce` or `_.reduceRight`.
3445
*
3446
* @private
3447
* @param {Function} arrayFunc The function to iterate over an array.
3448
* @param {Function} eachFunc The function to iterate over a collection.
3449
* @returns {Function} Returns the new each function.
3450
*/
3451
function createReduce(arrayFunc, eachFunc) {
3452
return function(collection, iteratee, accumulator, thisArg) {
3453
var initFromArray = arguments.length < 3;
3454
return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
3455
? arrayFunc(collection, iteratee, accumulator, initFromArray)
3456
: baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
3457
};
3458
}
3459
3460
/**
3461
* Creates a function that wraps `func` and invokes it with optional `this`
3462
* binding of, partial application, and currying.
3463
*
3464
* @private
3465
* @param {Function|string} func The function or method name to reference.
3466
* @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
3467
* @param {*} [thisArg] The `this` binding of `func`.
3468
* @param {Array} [partials] The arguments to prepend to those provided to the new function.
3469
* @param {Array} [holders] The `partials` placeholder indexes.
3470
* @param {Array} [partialsRight] The arguments to append to those provided to the new function.
3471
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
3472
* @param {Array} [argPos] The argument positions of the new function.
3473
* @param {number} [ary] The arity cap of `func`.
3474
* @param {number} [arity] The arity of `func`.
3475
* @returns {Function} Returns the new wrapped function.
3476
*/
3477
function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
3478
var isAry = bitmask & ARY_FLAG,
3479
isBind = bitmask & BIND_FLAG,
3480
isBindKey = bitmask & BIND_KEY_FLAG,
3481
isCurry = bitmask & CURRY_FLAG,
3482
isCurryBound = bitmask & CURRY_BOUND_FLAG,
3483
isCurryRight = bitmask & CURRY_RIGHT_FLAG,
3484
Ctor = isBindKey ? null : createCtorWrapper(func);
3485
3486
function wrapper() {
3487
// Avoid `arguments` object use disqualifying optimizations by
3488
// converting it to an array before providing it to other functions.
3489
var length = arguments.length,
3490
index = length,
3491
args = Array(length);
3492
3493
while (index--) {
3494
args[index] = arguments[index];
3495
}
3496
if (partials) {
3497
args = composeArgs(args, partials, holders);
3498
}
3499
if (partialsRight) {
3500
args = composeArgsRight(args, partialsRight, holdersRight);
3501
}
3502
if (isCurry || isCurryRight) {
3503
var placeholder = wrapper.placeholder,
3504
argsHolders = replaceHolders(args, placeholder);
3505
3506
length -= argsHolders.length;
3507
if (length < arity) {
3508
var newArgPos = argPos ? arrayCopy(argPos) : null,
3509
newArity = nativeMax(arity - length, 0),
3510
newsHolders = isCurry ? argsHolders : null,
3511
newHoldersRight = isCurry ? null : argsHolders,
3512
newPartials = isCurry ? args : null,
3513
newPartialsRight = isCurry ? null : args;
3514
3515
bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
3516
bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
3517
3518
if (!isCurryBound) {
3519
bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
3520
}
3521
var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity],
3522
result = createHybridWrapper.apply(undefined, newData);
3523
3524
if (isLaziable(func)) {
3525
setData(result, newData);
3526
}
3527
result.placeholder = placeholder;
3528
return result;
3529
}
3530
}
3531
var thisBinding = isBind ? thisArg : this,
3532
fn = isBindKey ? thisBinding[func] : func;
3533
3534
if (argPos) {
3535
args = reorder(args, argPos);
3536
}
3537
if (isAry && ary < args.length) {
3538
args.length = ary;
3539
}
3540
if (this && this !== root && this instanceof wrapper) {
3541
fn = Ctor || createCtorWrapper(func);
3542
}
3543
return fn.apply(thisBinding, args);
3544
}
3545
return wrapper;
3546
}
3547
3548
/**
3549
* Creates the padding required for `string` based on the given `length`.
3550
* The `chars` string is truncated if the number of characters exceeds `length`.
3551
*
3552
* @private
3553
* @param {string} string The string to create padding for.
3554
* @param {number} [length=0] The padding length.
3555
* @param {string} [chars=' '] The string used as padding.
3556
* @returns {string} Returns the pad for `string`.
3557
*/
3558
function createPadding(string, length, chars) {
3559
var strLength = string.length;
3560
length = +length;
3561
3562
if (strLength >= length || !nativeIsFinite(length)) {
3563
return '';
3564
}
3565
var padLength = length - strLength;
3566
chars = chars == null ? ' ' : (chars + '');
3567
return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength);
3568
}
3569
3570
/**
3571
* Creates a function that wraps `func` and invokes it with the optional `this`
3572
* binding of `thisArg` and the `partials` prepended to those provided to
3573
* the wrapper.
3574
*
3575
* @private
3576
* @param {Function} func The function to partially apply arguments to.
3577
* @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
3578
* @param {*} thisArg The `this` binding of `func`.
3579
* @param {Array} partials The arguments to prepend to those provided to the new function.
3580
* @returns {Function} Returns the new bound function.
3581
*/
3582
function createPartialWrapper(func, bitmask, thisArg, partials) {
3583
var isBind = bitmask & BIND_FLAG,
3584
Ctor = createCtorWrapper(func);
3585
3586
function wrapper() {
3587
// Avoid `arguments` object use disqualifying optimizations by
3588
// converting it to an array before providing it `func`.
3589
var argsIndex = -1,
3590
argsLength = arguments.length,
3591
leftIndex = -1,
3592
leftLength = partials.length,
3593
args = Array(argsLength + leftLength);
3594
3595
while (++leftIndex < leftLength) {
3596
args[leftIndex] = partials[leftIndex];
3597
}
3598
while (argsLength--) {
3599
args[leftIndex++] = arguments[++argsIndex];
3600
}
3601
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
3602
return fn.apply(isBind ? thisArg : this, args);
3603
}
3604
return wrapper;
3605
}
3606
3607
/**
3608
* Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
3609
*
3610
* @private
3611
* @param {boolean} [retHighest] Specify returning the highest qualified index.
3612
* @returns {Function} Returns the new index function.
3613
*/
3614
function createSortedIndex(retHighest) {
3615
return function(array, value, iteratee, thisArg) {
3616
var callback = getCallback(iteratee);
3617
return (iteratee == null && callback === baseCallback)
3618
? binaryIndex(array, value, retHighest)
3619
: binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest);
3620
};
3621
}
3622
3623
/**
3624
* Creates a function that either curries or invokes `func` with optional
3625
* `this` binding and partially applied arguments.
3626
*
3627
* @private
3628
* @param {Function|string} func The function or method name to reference.
3629
* @param {number} bitmask The bitmask of flags.
3630
* The bitmask may be composed of the following flags:
3631
* 1 - `_.bind`
3632
* 2 - `_.bindKey`
3633
* 4 - `_.curry` or `_.curryRight` of a bound function
3634
* 8 - `_.curry`
3635
* 16 - `_.curryRight`
3636
* 32 - `_.partial`
3637
* 64 - `_.partialRight`
3638
* 128 - `_.rearg`
3639
* 256 - `_.ary`
3640
* @param {*} [thisArg] The `this` binding of `func`.
3641
* @param {Array} [partials] The arguments to be partially applied.
3642
* @param {Array} [holders] The `partials` placeholder indexes.
3643
* @param {Array} [argPos] The argument positions of the new function.
3644
* @param {number} [ary] The arity cap of `func`.
3645
* @param {number} [arity] The arity of `func`.
3646
* @returns {Function} Returns the new wrapped function.
3647
*/
3648
function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
3649
var isBindKey = bitmask & BIND_KEY_FLAG;
3650
if (!isBindKey && typeof func != 'function') {
3651
throw new TypeError(FUNC_ERROR_TEXT);
3652
}
3653
var length = partials ? partials.length : 0;
3654
if (!length) {
3655
bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
3656
partials = holders = null;
3657
}
3658
length -= (holders ? holders.length : 0);
3659
if (bitmask & PARTIAL_RIGHT_FLAG) {
3660
var partialsRight = partials,
3661
holdersRight = holders;
3662
3663
partials = holders = null;
3664
}
3665
var data = isBindKey ? null : getData(func),
3666
newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
3667
3668
if (data) {
3669
mergeData(newData, data);
3670
bitmask = newData[1];
3671
arity = newData[9];
3672
}
3673
newData[9] = arity == null
3674
? (isBindKey ? 0 : func.length)
3675
: (nativeMax(arity - length, 0) || 0);
3676
3677
if (bitmask == BIND_FLAG) {
3678
var result = createBindWrapper(newData[0], newData[2]);
3679
} else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
3680
result = createPartialWrapper.apply(undefined, newData);
3681
} else {
3682
result = createHybridWrapper.apply(undefined, newData);
3683
}
3684
var setter = data ? baseSetData : setData;
3685
return setter(result, newData);
3686
}
3687
3688
/**
3689
* A specialized version of `baseIsEqualDeep` for arrays with support for
3690
* partial deep comparisons.
3691
*
3692
* @private
3693
* @param {Array} array The array to compare.
3694
* @param {Array} other The other array to compare.
3695
* @param {Function} equalFunc The function to determine equivalents of values.
3696
* @param {Function} [customizer] The function to customize comparing arrays.
3697
* @param {boolean} [isLoose] Specify performing partial comparisons.
3698
* @param {Array} [stackA] Tracks traversed `value` objects.
3699
* @param {Array} [stackB] Tracks traversed `other` objects.
3700
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
3701
*/
3702
function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
3703
var index = -1,
3704
arrLength = array.length,
3705
othLength = other.length;
3706
3707
if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
3708
return false;
3709
}
3710
// Ignore non-index properties.
3711
while (++index < arrLength) {
3712
var arrValue = array[index],
3713
othValue = other[index],
3714
result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
3715
3716
if (result !== undefined) {
3717
if (result) {
3718
continue;
3719
}
3720
return false;
3721
}
3722
// Recursively compare arrays (susceptible to call stack limits).
3723
if (isLoose) {
3724
if (!arraySome(other, function(othValue) {
3725
return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
3726
})) {
3727
return false;
3728
}
3729
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
3730
return false;
3731
}
3732
}
3733
return true;
3734
}
3735
3736
/**
3737
* A specialized version of `baseIsEqualDeep` for comparing objects of
3738
* the same `toStringTag`.
3739
*
3740
* **Note:** This function only supports comparing values with tags of
3741
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
3742
*
3743
* @private
3744
* @param {Object} value The object to compare.
3745
* @param {Object} other The other object to compare.
3746
* @param {string} tag The `toStringTag` of the objects to compare.
3747
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
3748
*/
3749
function equalByTag(object, other, tag) {
3750
switch (tag) {
3751
case boolTag:
3752
case dateTag:
3753
// Coerce dates and booleans to numbers, dates to milliseconds and booleans
3754
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
3755
return +object == +other;
3756
3757
case errorTag:
3758
return object.name == other.name && object.message == other.message;
3759
3760
case numberTag:
3761
// Treat `NaN` vs. `NaN` as equal.
3762
return (object != +object)
3763
? other != +other
3764
: object == +other;
3765
3766
case regexpTag:
3767
case stringTag:
3768
// Coerce regexes to strings and treat strings primitives and string
3769
// objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
3770
return object == (other + '');
3771
}
3772
return false;
3773
}
3774
3775
/**
3776
* A specialized version of `baseIsEqualDeep` for objects with support for
3777
* partial deep comparisons.
3778
*
3779
* @private
3780
* @param {Object} object The object to compare.
3781
* @param {Object} other The other object to compare.
3782
* @param {Function} equalFunc The function to determine equivalents of values.
3783
* @param {Function} [customizer] The function to customize comparing values.
3784
* @param {boolean} [isLoose] Specify performing partial comparisons.
3785
* @param {Array} [stackA] Tracks traversed `value` objects.
3786
* @param {Array} [stackB] Tracks traversed `other` objects.
3787
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
3788
*/
3789
function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
3790
var objProps = keys(object),
3791
objLength = objProps.length,
3792
othProps = keys(other),
3793
othLength = othProps.length;
3794
3795
if (objLength != othLength && !isLoose) {
3796
return false;
3797
}
3798
var index = objLength;
3799
while (index--) {
3800
var key = objProps[index];
3801
if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
3802
return false;
3803
}
3804
}
3805
var skipCtor = isLoose;
3806
while (++index < objLength) {
3807
key = objProps[index];
3808
var objValue = object[key],
3809
othValue = other[key],
3810
result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
3811
3812
// Recursively compare objects (susceptible to call stack limits).
3813
if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
3814
return false;
3815
}
3816
skipCtor || (skipCtor = key == 'constructor');
3817
}
3818
if (!skipCtor) {
3819
var objCtor = object.constructor,
3820
othCtor = other.constructor;
3821
3822
// Non `Object` object instances with different constructors are not equal.
3823
if (objCtor != othCtor &&
3824
('constructor' in object && 'constructor' in other) &&
3825
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
3826
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
3827
return false;
3828
}
3829
}
3830
return true;
3831
}
3832
3833
/**
3834
* Gets the appropriate "callback" function. If the `_.callback` method is
3835
* customized this function returns the custom method, otherwise it returns
3836
* the `baseCallback` function. If arguments are provided the chosen function
3837
* is invoked with them and its result is returned.
3838
*
3839
* @private
3840
* @returns {Function} Returns the chosen function or its result.
3841
*/
3842
function getCallback(func, thisArg, argCount) {
3843
var result = lodash.callback || callback;
3844
result = result === callback ? baseCallback : result;
3845
return argCount ? result(func, thisArg, argCount) : result;
3846
}
3847
3848
/**
3849
* Gets metadata for `func`.
3850
*
3851
* @private
3852
* @param {Function} func The function to query.
3853
* @returns {*} Returns the metadata for `func`.
3854
*/
3855
var getData = !metaMap ? noop : function(func) {
3856
return metaMap.get(func);
3857
};
3858
3859
/**
3860
* Gets the name of `func`.
3861
*
3862
* @private
3863
* @param {Function} func The function to query.
3864
* @returns {string} Returns the function name.
3865
*/
3866
function getFuncName(func) {
3867
var result = func.name,
3868
array = realNames[result],
3869
length = array ? array.length : 0;
3870
3871
while (length--) {
3872
var data = array[length],
3873
otherFunc = data.func;
3874
if (otherFunc == null || otherFunc == func) {
3875
return data.name;
3876
}
3877
}
3878
return result;
3879
}
3880
3881
/**
3882
* Gets the appropriate "indexOf" function. If the `_.indexOf` method is
3883
* customized this function returns the custom method, otherwise it returns
3884
* the `baseIndexOf` function. If arguments are provided the chosen function
3885
* is invoked with them and its result is returned.
3886
*
3887
* @private
3888
* @returns {Function|number} Returns the chosen function or its result.
3889
*/
3890
function getIndexOf(collection, target, fromIndex) {
3891
var result = lodash.indexOf || indexOf;
3892
result = result === indexOf ? baseIndexOf : result;
3893
return collection ? result(collection, target, fromIndex) : result;
3894
}
3895
3896
/**
3897
* Gets the "length" property value of `object`.
3898
*
3899
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
3900
* that affects Safari on at least iOS 8.1-8.3 ARM64.
3901
*
3902
* @private
3903
* @param {Object} object The object to query.
3904
* @returns {*} Returns the "length" value.
3905
*/
3906
var getLength = baseProperty('length');
3907
3908
/**
3909
* Gets the propery names, values, and compare flags of `object`.
3910
*
3911
* @private
3912
* @param {Object} object The object to query.
3913
* @returns {Array} Returns the match data of `object`.
3914
*/
3915
function getMatchData(object) {
3916
var result = pairs(object),
3917
length = result.length;
3918
3919
while (length--) {
3920
result[length][2] = isStrictComparable(result[length][1]);
3921
}
3922
return result;
3923
}
3924
3925
/**
3926
* Gets the native function at `key` of `object`.
3927
*
3928
* @private
3929
* @param {Object} object The object to query.
3930
* @param {string} key The key of the method to get.
3931
* @returns {*} Returns the function if it's native, else `undefined`.
3932
*/
3933
function getNative(object, key) {
3934
var value = object == null ? undefined : object[key];
3935
return isNative(value) ? value : undefined;
3936
}
3937
3938
/**
3939
* Gets the view, applying any `transforms` to the `start` and `end` positions.
3940
*
3941
* @private
3942
* @param {number} start The start of the view.
3943
* @param {number} end The end of the view.
3944
* @param {Array} [transforms] The transformations to apply to the view.
3945
* @returns {Object} Returns an object containing the `start` and `end`
3946
* positions of the view.
3947
*/
3948
function getView(start, end, transforms) {
3949
var index = -1,
3950
length = transforms ? transforms.length : 0;
3951
3952
while (++index < length) {
3953
var data = transforms[index],
3954
size = data.size;
3955
3956
switch (data.type) {
3957
case 'drop': start += size; break;
3958
case 'dropRight': end -= size; break;
3959
case 'take': end = nativeMin(end, start + size); break;
3960
case 'takeRight': start = nativeMax(start, end - size); break;
3961
}
3962
}
3963
return { 'start': start, 'end': end };
3964
}
3965
3966
/**
3967
* Initializes an array clone.
3968
*
3969
* @private
3970
* @param {Array} array The array to clone.
3971
* @returns {Array} Returns the initialized clone.
3972
*/
3973
function initCloneArray(array) {
3974
var length = array.length,
3975
result = new array.constructor(length);
3976
3977
// Add array properties assigned by `RegExp#exec`.
3978
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
3979
result.index = array.index;
3980
result.input = array.input;
3981
}
3982
return result;
3983
}
3984
3985
/**
3986
* Initializes an object clone.
3987
*
3988
* @private
3989
* @param {Object} object The object to clone.
3990
* @returns {Object} Returns the initialized clone.
3991
*/
3992
function initCloneObject(object) {
3993
var Ctor = object.constructor;
3994
if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
3995
Ctor = Object;
3996
}
3997
return new Ctor;
3998
}
3999
4000
/**
4001
* Initializes an object clone based on its `toStringTag`.
4002
*
4003
* **Note:** This function only supports cloning values with tags of
4004
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
4005
*
4006
* @private
4007
* @param {Object} object The object to clone.
4008
* @param {string} tag The `toStringTag` of the object to clone.
4009
* @param {boolean} [isDeep] Specify a deep clone.
4010
* @returns {Object} Returns the initialized clone.
4011
*/
4012
function initCloneByTag(object, tag, isDeep) {
4013
var Ctor = object.constructor;
4014
switch (tag) {
4015
case arrayBufferTag:
4016
return bufferClone(object);
4017
4018
case boolTag:
4019
case dateTag:
4020
return new Ctor(+object);
4021
4022
case float32Tag: case float64Tag:
4023
case int8Tag: case int16Tag: case int32Tag:
4024
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
4025
var buffer = object.buffer;
4026
return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
4027
4028
case numberTag:
4029
case stringTag:
4030
return new Ctor(object);
4031
4032
case regexpTag:
4033
var result = new Ctor(object.source, reFlags.exec(object));
4034
result.lastIndex = object.lastIndex;
4035
}
4036
return result;
4037
}
4038
4039
/**
4040
* Invokes the method at `path` on `object`.
4041
*
4042
* @private
4043
* @param {Object} object The object to query.
4044
* @param {Array|string} path The path of the method to invoke.
4045
* @param {Array} args The arguments to invoke the method with.
4046
* @returns {*} Returns the result of the invoked method.
4047
*/
4048
function invokePath(object, path, args) {
4049
if (object != null && !isKey(path, object)) {
4050
path = toPath(path);
4051
object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
4052
path = last(path);
4053
}
4054
var func = object == null ? object : object[path];
4055
return func == null ? undefined : func.apply(object, args);
4056
}
4057
4058
/**
4059
* Checks if `value` is array-like.
4060
*
4061
* @private
4062
* @param {*} value The value to check.
4063
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
4064
*/
4065
function isArrayLike(value) {
4066
return value != null && isLength(getLength(value));
4067
}
4068
4069
/**
4070
* Checks if `value` is a valid array-like index.
4071
*
4072
* @private
4073
* @param {*} value The value to check.
4074
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
4075
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
4076
*/
4077
function isIndex(value, length) {
4078
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
4079
length = length == null ? MAX_SAFE_INTEGER : length;
4080
return value > -1 && value % 1 == 0 && value < length;
4081
}
4082
4083
/**
4084
* Checks if the provided arguments are from an iteratee call.
4085
*
4086
* @private
4087
* @param {*} value The potential iteratee value argument.
4088
* @param {*} index The potential iteratee index or key argument.
4089
* @param {*} object The potential iteratee object argument.
4090
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
4091
*/
4092
function isIterateeCall(value, index, object) {
4093
if (!isObject(object)) {
4094
return false;
4095
}
4096
var type = typeof index;
4097
if (type == 'number'
4098
? (isArrayLike(object) && isIndex(index, object.length))
4099
: (type == 'string' && index in object)) {
4100
var other = object[index];
4101
return value === value ? (value === other) : (other !== other);
4102
}
4103
return false;
4104
}
4105
4106
/**
4107
* Checks if `value` is a property name and not a property path.
4108
*
4109
* @private
4110
* @param {*} value The value to check.
4111
* @param {Object} [object] The object to query keys on.
4112
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
4113
*/
4114
function isKey(value, object) {
4115
var type = typeof value;
4116
if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
4117
return true;
4118
}
4119
if (isArray(value)) {
4120
return false;
4121
}
4122
var result = !reIsDeepProp.test(value);
4123
return result || (object != null && value in toObject(object));
4124
}
4125
4126
/**
4127
* Checks if `func` has a lazy counterpart.
4128
*
4129
* @private
4130
* @param {Function} func The function to check.
4131
* @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
4132
*/
4133
function isLaziable(func) {
4134
var funcName = getFuncName(func);
4135
if (!(funcName in LazyWrapper.prototype)) {
4136
return false;
4137
}
4138
var other = lodash[funcName];
4139
if (func === other) {
4140
return true;
4141
}
4142
var data = getData(other);
4143
return !!data && func === data[0];
4144
}
4145
4146
/**
4147
* Checks if `value` is a valid array-like length.
4148
*
4149
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
4150
*
4151
* @private
4152
* @param {*} value The value to check.
4153
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
4154
*/
4155
function isLength(value) {
4156
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
4157
}
4158
4159
/**
4160
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
4161
*
4162
* @private
4163
* @param {*} value The value to check.
4164
* @returns {boolean} Returns `true` if `value` if suitable for strict
4165
* equality comparisons, else `false`.
4166
*/
4167
function isStrictComparable(value) {
4168
return value === value && !isObject(value);
4169
}
4170
4171
/**
4172
* Merges the function metadata of `source` into `data`.
4173
*
4174
* Merging metadata reduces the number of wrappers required to invoke a function.
4175
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
4176
* may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
4177
* augment function arguments, making the order in which they are executed important,
4178
* preventing the merging of metadata. However, we make an exception for a safe
4179
* common case where curried functions have `_.ary` and or `_.rearg` applied.
4180
*
4181
* @private
4182
* @param {Array} data The destination metadata.
4183
* @param {Array} source The source metadata.
4184
* @returns {Array} Returns `data`.
4185
*/
4186
function mergeData(data, source) {
4187
var bitmask = data[1],
4188
srcBitmask = source[1],
4189
newBitmask = bitmask | srcBitmask,
4190
isCommon = newBitmask < ARY_FLAG;
4191
4192
var isCombo =
4193
(srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) ||
4194
(srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) ||
4195
(srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG);
4196
4197
// Exit early if metadata can't be merged.
4198
if (!(isCommon || isCombo)) {
4199
return data;
4200
}
4201
// Use source `thisArg` if available.
4202
if (srcBitmask & BIND_FLAG) {
4203
data[2] = source[2];
4204
// Set when currying a bound function.
4205
newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
4206
}
4207
// Compose partial arguments.
4208
var value = source[3];
4209
if (value) {
4210
var partials = data[3];
4211
data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
4212
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
4213
}
4214
// Compose partial right arguments.
4215
value = source[5];
4216
if (value) {
4217
partials = data[5];
4218
data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
4219
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
4220
}
4221
// Use source `argPos` if available.
4222
value = source[7];
4223
if (value) {
4224
data[7] = arrayCopy(value);
4225
}
4226
// Use source `ary` if it's smaller.
4227
if (srcBitmask & ARY_FLAG) {
4228
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
4229
}
4230
// Use source `arity` if one is not provided.
4231
if (data[9] == null) {
4232
data[9] = source[9];
4233
}
4234
// Use source `func` and merge bitmasks.
4235
data[0] = source[0];
4236
data[1] = newBitmask;
4237
4238
return data;
4239
}
4240
4241
/**
4242
* A specialized version of `_.pick` which picks `object` properties specified
4243
* by `props`.
4244
*
4245
* @private
4246
* @param {Object} object The source object.
4247
* @param {string[]} props The property names to pick.
4248
* @returns {Object} Returns the new object.
4249
*/
4250
function pickByArray(object, props) {
4251
object = toObject(object);
4252
4253
var index = -1,
4254
length = props.length,
4255
result = {};
4256
4257
while (++index < length) {
4258
var key = props[index];
4259
if (key in object) {
4260
result[key] = object[key];
4261
}
4262
}
4263
return result;
4264
}
4265
4266
/**
4267
* A specialized version of `_.pick` which picks `object` properties `predicate`
4268
* returns truthy for.
4269
*
4270
* @private
4271
* @param {Object} object The source object.
4272
* @param {Function} predicate The function invoked per iteration.
4273
* @returns {Object} Returns the new object.
4274
*/
4275
function pickByCallback(object, predicate) {
4276
var result = {};
4277
baseForIn(object, function(value, key, object) {
4278
if (predicate(value, key, object)) {
4279
result[key] = value;
4280
}
4281
});
4282
return result;
4283
}
4284
4285
/**
4286
* Reorder `array` according to the specified indexes where the element at
4287
* the first index is assigned as the first element, the element at
4288
* the second index is assigned as the second element, and so on.
4289
*
4290
* @private
4291
* @param {Array} array The array to reorder.
4292
* @param {Array} indexes The arranged array indexes.
4293
* @returns {Array} Returns `array`.
4294
*/
4295
function reorder(array, indexes) {
4296
var arrLength = array.length,
4297
length = nativeMin(indexes.length, arrLength),
4298
oldArray = arrayCopy(array);
4299
4300
while (length--) {
4301
var index = indexes[length];
4302
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
4303
}
4304
return array;
4305
}
4306
4307
/**
4308
* Sets metadata for `func`.
4309
*
4310
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
4311
* period of time, it will trip its breaker and transition to an identity function
4312
* to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
4313
* for more details.
4314
*
4315
* @private
4316
* @param {Function} func The function to associate metadata with.
4317
* @param {*} data The metadata.
4318
* @returns {Function} Returns `func`.
4319
*/
4320
var setData = (function() {
4321
var count = 0,
4322
lastCalled = 0;
4323
4324
return function(key, value) {
4325
var stamp = now(),
4326
remaining = HOT_SPAN - (stamp - lastCalled);
4327
4328
lastCalled = stamp;
4329
if (remaining > 0) {
4330
if (++count >= HOT_COUNT) {
4331
return key;
4332
}
4333
} else {
4334
count = 0;
4335
}
4336
return baseSetData(key, value);
4337
};
4338
}());
4339
4340
/**
4341
* A fallback implementation of `_.isPlainObject` which checks if `value`
4342
* is an object created by the `Object` constructor or has a `[[Prototype]]`
4343
* of `null`.
4344
*
4345
* @private
4346
* @param {*} value The value to check.
4347
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
4348
*/
4349
function shimIsPlainObject(value) {
4350
var Ctor,
4351
support = lodash.support;
4352
4353
// Exit early for non `Object` objects.
4354
if (!(isObjectLike(value) && objToString.call(value) == objectTag) ||
4355
(!hasOwnProperty.call(value, 'constructor') &&
4356
(Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
4357
return false;
4358
}
4359
// IE < 9 iterates inherited properties before own properties. If the first
4360
// iterated property is an object's own property then there are no inherited
4361
// enumerable properties.
4362
var result;
4363
// In most environments an object's own properties are iterated before
4364
// its inherited properties. If the last iterated property is an object's
4365
// own property then there are no inherited enumerable properties.
4366
baseForIn(value, function(subValue, key) {
4367
result = key;
4368
});
4369
return result === undefined || hasOwnProperty.call(value, result);
4370
}
4371
4372
/**
4373
* A fallback implementation of `Object.keys` which creates an array of the
4374
* own enumerable property names of `object`.
4375
*
4376
* @private
4377
* @param {Object} object The object to query.
4378
* @returns {Array} Returns the array of property names.
4379
*/
4380
function shimKeys(object) {
4381
var props = keysIn(object),
4382
propsLength = props.length,
4383
length = propsLength && object.length;
4384
4385
var allowIndexes = !!length && isLength(length) &&
4386
(isArray(object) || isArguments(object));
4387
4388
var index = -1,
4389
result = [];
4390
4391
while (++index < propsLength) {
4392
var key = props[index];
4393
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
4394
result.push(key);
4395
}
4396
}
4397
return result;
4398
}
4399
4400
/**
4401
* Converts `value` to an array-like object if it's not one.
4402
*
4403
* @private
4404
* @param {*} value The value to process.
4405
* @returns {Array|Object} Returns the array-like object.
4406
*/
4407
function toIterable(value) {
4408
if (value == null) {
4409
return [];
4410
}
4411
if (!isArrayLike(value)) {
4412
return values(value);
4413
}
4414
return isObject(value) ? value : Object(value);
4415
}
4416
4417
/**
4418
* Converts `value` to an object if it's not one.
4419
*
4420
* @private
4421
* @param {*} value The value to process.
4422
* @returns {Object} Returns the object.
4423
*/
4424
function toObject(value) {
4425
return isObject(value) ? value : Object(value);
4426
}
4427
4428
/**
4429
* Converts `value` to property path array if it's not one.
4430
*
4431
* @private
4432
* @param {*} value The value to process.
4433
* @returns {Array} Returns the property path array.
4434
*/
4435
function toPath(value) {
4436
if (isArray(value)) {
4437
return value;
4438
}
4439
var result = [];
4440
baseToString(value).replace(rePropName, function(match, number, quote, string) {
4441
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
4442
});
4443
return result;
4444
}
4445
4446
/**
4447
* Creates a clone of `wrapper`.
4448
*
4449
* @private
4450
* @param {Object} wrapper The wrapper to clone.
4451
* @returns {Object} Returns the cloned wrapper.
4452
*/
4453
function wrapperClone(wrapper) {
4454
return wrapper instanceof LazyWrapper
4455
? wrapper.clone()
4456
: new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
4457
}
4458
4459
/*------------------------------------------------------------------------*/
4460
4461
/**
4462
* Creates an array of elements split into groups the length of `size`.
4463
* If `collection` can't be split evenly, the final chunk will be the remaining
4464
* elements.
4465
*
4466
* @static
4467
* @memberOf _
4468
* @category Array
4469
* @param {Array} array The array to process.
4470
* @param {number} [size=1] The length of each chunk.
4471
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
4472
* @returns {Array} Returns the new array containing chunks.
4473
* @example
4474
*
4475
* _.chunk(['a', 'b', 'c', 'd'], 2);
4476
* // => [['a', 'b'], ['c', 'd']]
4477
*
4478
* _.chunk(['a', 'b', 'c', 'd'], 3);
4479
* // => [['a', 'b', 'c'], ['d']]
4480
*/
4481
function chunk(array, size, guard) {
4482
if (guard ? isIterateeCall(array, size, guard) : size == null) {
4483
size = 1;
4484
} else {
4485
size = nativeMax(+size || 1, 1);
4486
}
4487
var index = 0,
4488
length = array ? array.length : 0,
4489
resIndex = -1,
4490
result = Array(ceil(length / size));
4491
4492
while (index < length) {
4493
result[++resIndex] = baseSlice(array, index, (index += size));
4494
}
4495
return result;
4496
}
4497
4498
/**
4499
* Creates an array with all falsey values removed. The values `false`, `null`,
4500
* `0`, `""`, `undefined`, and `NaN` are falsey.
4501
*
4502
* @static
4503
* @memberOf _
4504
* @category Array
4505
* @param {Array} array The array to compact.
4506
* @returns {Array} Returns the new array of filtered values.
4507
* @example
4508
*
4509
* _.compact([0, 1, false, 2, '', 3]);
4510
* // => [1, 2, 3]
4511
*/
4512
function compact(array) {
4513
var index = -1,
4514
length = array ? array.length : 0,
4515
resIndex = -1,
4516
result = [];
4517
4518
while (++index < length) {
4519
var value = array[index];
4520
if (value) {
4521
result[++resIndex] = value;
4522
}
4523
}
4524
return result;
4525
}
4526
4527
/**
4528
* Creates an array of unique `array` values not included in the other
4529
* provided arrays using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
4530
* for equality comparisons.
4531
*
4532
* @static
4533
* @memberOf _
4534
* @category Array
4535
* @param {Array} array The array to inspect.
4536
* @param {...Array} [values] The arrays of values to exclude.
4537
* @returns {Array} Returns the new array of filtered values.
4538
* @example
4539
*
4540
* _.difference([1, 2, 3], [4, 2]);
4541
* // => [1, 3]
4542
*/
4543
var difference = restParam(function(array, values) {
4544
return isArrayLike(array)
4545
? baseDifference(array, baseFlatten(values, false, true))
4546
: [];
4547
});
4548
4549
/**
4550
* Creates a slice of `array` with `n` elements dropped from the beginning.
4551
*
4552
* @static
4553
* @memberOf _
4554
* @category Array
4555
* @param {Array} array The array to query.
4556
* @param {number} [n=1] The number of elements to drop.
4557
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
4558
* @returns {Array} Returns the slice of `array`.
4559
* @example
4560
*
4561
* _.drop([1, 2, 3]);
4562
* // => [2, 3]
4563
*
4564
* _.drop([1, 2, 3], 2);
4565
* // => [3]
4566
*
4567
* _.drop([1, 2, 3], 5);
4568
* // => []
4569
*
4570
* _.drop([1, 2, 3], 0);
4571
* // => [1, 2, 3]
4572
*/
4573
function drop(array, n, guard) {
4574
var length = array ? array.length : 0;
4575
if (!length) {
4576
return [];
4577
}
4578
if (guard ? isIterateeCall(array, n, guard) : n == null) {
4579
n = 1;
4580
}
4581
return baseSlice(array, n < 0 ? 0 : n);
4582
}
4583
4584
/**
4585
* Creates a slice of `array` with `n` elements dropped from the end.
4586
*
4587
* @static
4588
* @memberOf _
4589
* @category Array
4590
* @param {Array} array The array to query.
4591
* @param {number} [n=1] The number of elements to drop.
4592
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
4593
* @returns {Array} Returns the slice of `array`.
4594
* @example
4595
*
4596
* _.dropRight([1, 2, 3]);
4597
* // => [1, 2]
4598
*
4599
* _.dropRight([1, 2, 3], 2);
4600
* // => [1]
4601
*
4602
* _.dropRight([1, 2, 3], 5);
4603
* // => []
4604
*
4605
* _.dropRight([1, 2, 3], 0);
4606
* // => [1, 2, 3]
4607
*/
4608
function dropRight(array, n, guard) {
4609
var length = array ? array.length : 0;
4610
if (!length) {
4611
return [];
4612
}
4613
if (guard ? isIterateeCall(array, n, guard) : n == null) {
4614
n = 1;
4615
}
4616
n = length - (+n || 0);
4617
return baseSlice(array, 0, n < 0 ? 0 : n);
4618
}
4619
4620
/**
4621
* Creates a slice of `array` excluding elements dropped from the end.
4622
* Elements are dropped until `predicate` returns falsey. The predicate is
4623
* bound to `thisArg` and invoked with three arguments: (value, index, array).
4624
*
4625
* If a property name is provided for `predicate` the created `_.property`
4626
* style callback returns the property value of the given element.
4627
*
4628
* If a value is also provided for `thisArg` the created `_.matchesProperty`
4629
* style callback returns `true` for elements that have a matching property
4630
* value, else `false`.
4631
*
4632
* If an object is provided for `predicate` the created `_.matches` style
4633
* callback returns `true` for elements that match the properties of the given
4634
* object, else `false`.
4635
*
4636
* @static
4637
* @memberOf _
4638
* @category Array
4639
* @param {Array} array The array to query.
4640
* @param {Function|Object|string} [predicate=_.identity] The function invoked
4641
* per iteration.
4642
* @param {*} [thisArg] The `this` binding of `predicate`.
4643
* @returns {Array} Returns the slice of `array`.
4644
* @example
4645
*
4646
* _.dropRightWhile([1, 2, 3], function(n) {
4647
* return n > 1;
4648
* });
4649
* // => [1]
4650
*
4651
* var users = [
4652
* { 'user': 'barney', 'active': true },
4653
* { 'user': 'fred', 'active': false },
4654
* { 'user': 'pebbles', 'active': false }
4655
* ];
4656
*
4657
* // using the `_.matches` callback shorthand
4658
* _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
4659
* // => ['barney', 'fred']
4660
*
4661
* // using the `_.matchesProperty` callback shorthand
4662
* _.pluck(_.dropRightWhile(users, 'active', false), 'user');
4663
* // => ['barney']
4664
*
4665
* // using the `_.property` callback shorthand
4666
* _.pluck(_.dropRightWhile(users, 'active'), 'user');
4667
* // => ['barney', 'fred', 'pebbles']
4668
*/
4669
function dropRightWhile(array, predicate, thisArg) {
4670
return (array && array.length)
4671
? baseWhile(array, getCallback(predicate, thisArg, 3), true, true)
4672
: [];
4673
}
4674
4675
/**
4676
* Creates a slice of `array` excluding elements dropped from the beginning.
4677
* Elements are dropped until `predicate` returns falsey. The predicate is
4678
* bound to `thisArg` and invoked with three arguments: (value, index, array).
4679
*
4680
* If a property name is provided for `predicate` the created `_.property`
4681
* style callback returns the property value of the given element.
4682
*
4683
* If a value is also provided for `thisArg` the created `_.matchesProperty`
4684
* style callback returns `true` for elements that have a matching property
4685
* value, else `false`.
4686
*
4687
* If an object is provided for `predicate` the created `_.matches` style
4688
* callback returns `true` for elements that have the properties of the given
4689
* object, else `false`.
4690
*
4691
* @static
4692
* @memberOf _
4693
* @category Array
4694
* @param {Array} array The array to query.
4695
* @param {Function|Object|string} [predicate=_.identity] The function invoked
4696
* per iteration.
4697
* @param {*} [thisArg] The `this` binding of `predicate`.
4698
* @returns {Array} Returns the slice of `array`.
4699
* @example
4700
*
4701
* _.dropWhile([1, 2, 3], function(n) {
4702
* return n < 3;
4703
* });
4704
* // => [3]
4705
*
4706
* var users = [
4707
* { 'user': 'barney', 'active': false },
4708
* { 'user': 'fred', 'active': false },
4709
* { 'user': 'pebbles', 'active': true }
4710
* ];
4711
*
4712
* // using the `_.matches` callback shorthand
4713
* _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
4714
* // => ['fred', 'pebbles']
4715
*
4716
* // using the `_.matchesProperty` callback shorthand
4717
* _.pluck(_.dropWhile(users, 'active', false), 'user');
4718
* // => ['pebbles']
4719
*
4720
* // using the `_.property` callback shorthand
4721
* _.pluck(_.dropWhile(users, 'active'), 'user');
4722
* // => ['barney', 'fred', 'pebbles']
4723
*/
4724
function dropWhile(array, predicate, thisArg) {
4725
return (array && array.length)
4726
? baseWhile(array, getCallback(predicate, thisArg, 3), true)
4727
: [];
4728
}
4729
4730
/**
4731
* Fills elements of `array` with `value` from `start` up to, but not
4732
* including, `end`.
4733
*
4734
* **Note:** This method mutates `array`.
4735
*
4736
* @static
4737
* @memberOf _
4738
* @category Array
4739
* @param {Array} array The array to fill.
4740
* @param {*} value The value to fill `array` with.
4741
* @param {number} [start=0] The start position.
4742
* @param {number} [end=array.length] The end position.
4743
* @returns {Array} Returns `array`.
4744
* @example
4745
*
4746
* var array = [1, 2, 3];
4747
*
4748
* _.fill(array, 'a');
4749
* console.log(array);
4750
* // => ['a', 'a', 'a']
4751
*
4752
* _.fill(Array(3), 2);
4753
* // => [2, 2, 2]
4754
*
4755
* _.fill([4, 6, 8], '*', 1, 2);
4756
* // => [4, '*', 8]
4757
*/
4758
function fill(array, value, start, end) {
4759
var length = array ? array.length : 0;
4760
if (!length) {
4761
return [];
4762
}
4763
if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
4764
start = 0;
4765
end = length;
4766
}
4767
return baseFill(array, value, start, end);
4768
}
4769
4770
/**
4771
* This method is like `_.find` except that it returns the index of the first
4772
* element `predicate` returns truthy for instead of the element itself.
4773
*
4774
* If a property name is provided for `predicate` the created `_.property`
4775
* style callback returns the property value of the given element.
4776
*
4777
* If a value is also provided for `thisArg` the created `_.matchesProperty`
4778
* style callback returns `true` for elements that have a matching property
4779
* value, else `false`.
4780
*
4781
* If an object is provided for `predicate` the created `_.matches` style
4782
* callback returns `true` for elements that have the properties of the given
4783
* object, else `false`.
4784
*
4785
* @static
4786
* @memberOf _
4787
* @category Array
4788
* @param {Array} array The array to search.
4789
* @param {Function|Object|string} [predicate=_.identity] The function invoked
4790
* per iteration.
4791
* @param {*} [thisArg] The `this` binding of `predicate`.
4792
* @returns {number} Returns the index of the found element, else `-1`.
4793
* @example
4794
*
4795
* var users = [
4796
* { 'user': 'barney', 'active': false },
4797
* { 'user': 'fred', 'active': false },
4798
* { 'user': 'pebbles', 'active': true }
4799
* ];
4800
*
4801
* _.findIndex(users, function(chr) {
4802
* return chr.user == 'barney';
4803
* });
4804
* // => 0
4805
*
4806
* // using the `_.matches` callback shorthand
4807
* _.findIndex(users, { 'user': 'fred', 'active': false });
4808
* // => 1
4809
*
4810
* // using the `_.matchesProperty` callback shorthand
4811
* _.findIndex(users, 'active', false);
4812
* // => 0
4813
*
4814
* // using the `_.property` callback shorthand
4815
* _.findIndex(users, 'active');
4816
* // => 2
4817
*/
4818
var findIndex = createFindIndex();
4819
4820
/**
4821
* This method is like `_.findIndex` except that it iterates over elements
4822
* of `collection` from right to left.
4823
*
4824
* If a property name is provided for `predicate` the created `_.property`
4825
* style callback returns the property value of the given element.
4826
*
4827
* If a value is also provided for `thisArg` the created `_.matchesProperty`
4828
* style callback returns `true` for elements that have a matching property
4829
* value, else `false`.
4830
*
4831
* If an object is provided for `predicate` the created `_.matches` style
4832
* callback returns `true` for elements that have the properties of the given
4833
* object, else `false`.
4834
*
4835
* @static
4836
* @memberOf _
4837
* @category Array
4838
* @param {Array} array The array to search.
4839
* @param {Function|Object|string} [predicate=_.identity] The function invoked
4840
* per iteration.
4841
* @param {*} [thisArg] The `this` binding of `predicate`.
4842
* @returns {number} Returns the index of the found element, else `-1`.
4843
* @example
4844
*
4845
* var users = [
4846
* { 'user': 'barney', 'active': true },
4847
* { 'user': 'fred', 'active': false },
4848
* { 'user': 'pebbles', 'active': false }
4849
* ];
4850
*
4851
* _.findLastIndex(users, function(chr) {
4852
* return chr.user == 'pebbles';
4853
* });
4854
* // => 2
4855
*
4856
* // using the `_.matches` callback shorthand
4857
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
4858
* // => 0
4859
*
4860
* // using the `_.matchesProperty` callback shorthand
4861
* _.findLastIndex(users, 'active', false);
4862
* // => 2
4863
*
4864
* // using the `_.property` callback shorthand
4865
* _.findLastIndex(users, 'active');
4866
* // => 0
4867
*/
4868
var findLastIndex = createFindIndex(true);
4869
4870
/**
4871
* Gets the first element of `array`.
4872
*
4873
* @static
4874
* @memberOf _
4875
* @alias head
4876
* @category Array
4877
* @param {Array} array The array to query.
4878
* @returns {*} Returns the first element of `array`.
4879
* @example
4880
*
4881
* _.first([1, 2, 3]);
4882
* // => 1
4883
*
4884
* _.first([]);
4885
* // => undefined
4886
*/
4887
function first(array) {
4888
return array ? array[0] : undefined;
4889
}
4890
4891
/**
4892
* Flattens a nested array. If `isDeep` is `true` the array is recursively
4893
* flattened, otherwise it is only flattened a single level.
4894
*
4895
* @static
4896
* @memberOf _
4897
* @category Array
4898
* @param {Array} array The array to flatten.
4899
* @param {boolean} [isDeep] Specify a deep flatten.
4900
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
4901
* @returns {Array} Returns the new flattened array.
4902
* @example
4903
*
4904
* _.flatten([1, [2, 3, [4]]]);
4905
* // => [1, 2, 3, [4]]
4906
*
4907
* // using `isDeep`
4908
* _.flatten([1, [2, 3, [4]]], true);
4909
* // => [1, 2, 3, 4]
4910
*/
4911
function flatten(array, isDeep, guard) {
4912
var length = array ? array.length : 0;
4913
if (guard && isIterateeCall(array, isDeep, guard)) {
4914
isDeep = false;
4915
}
4916
return length ? baseFlatten(array, isDeep) : [];
4917
}
4918
4919
/**
4920
* Recursively flattens a nested array.
4921
*
4922
* @static
4923
* @memberOf _
4924
* @category Array
4925
* @param {Array} array The array to recursively flatten.
4926
* @returns {Array} Returns the new flattened array.
4927
* @example
4928
*
4929
* _.flattenDeep([1, [2, 3, [4]]]);
4930
* // => [1, 2, 3, 4]
4931
*/
4932
function flattenDeep(array) {
4933
var length = array ? array.length : 0;
4934
return length ? baseFlatten(array, true) : [];
4935
}
4936
4937
/**
4938
* Gets the index at which the first occurrence of `value` is found in `array`
4939
* using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
4940
* for equality comparisons. If `fromIndex` is negative, it is used as the offset
4941
* from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
4942
* performs a faster binary search.
4943
*
4944
* @static
4945
* @memberOf _
4946
* @category Array
4947
* @param {Array} array The array to search.
4948
* @param {*} value The value to search for.
4949
* @param {boolean|number} [fromIndex=0] The index to search from or `true`
4950
* to perform a binary search on a sorted array.
4951
* @returns {number} Returns the index of the matched value, else `-1`.
4952
* @example
4953
*
4954
* _.indexOf([1, 2, 1, 2], 2);
4955
* // => 1
4956
*
4957
* // using `fromIndex`
4958
* _.indexOf([1, 2, 1, 2], 2, 2);
4959
* // => 3
4960
*
4961
* // performing a binary search
4962
* _.indexOf([1, 1, 2, 2], 2, true);
4963
* // => 2
4964
*/
4965
function indexOf(array, value, fromIndex) {
4966
var length = array ? array.length : 0;
4967
if (!length) {
4968
return -1;
4969
}
4970
if (typeof fromIndex == 'number') {
4971
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
4972
} else if (fromIndex) {
4973
var index = binaryIndex(array, value),
4974
other = array[index];
4975
4976
if (value === value ? (value === other) : (other !== other)) {
4977
return index;
4978
}
4979
return -1;
4980
}
4981
return baseIndexOf(array, value, fromIndex || 0);
4982
}
4983
4984
/**
4985
* Gets all but the last element of `array`.
4986
*
4987
* @static
4988
* @memberOf _
4989
* @category Array
4990
* @param {Array} array The array to query.
4991
* @returns {Array} Returns the slice of `array`.
4992
* @example
4993
*
4994
* _.initial([1, 2, 3]);
4995
* // => [1, 2]
4996
*/
4997
function initial(array) {
4998
return dropRight(array, 1);
4999
}
5000
5001
/**
5002
* Creates an array of unique values that are included in all of the provided
5003
* arrays using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
5004
* for equality comparisons.
5005
*
5006
* @static
5007
* @memberOf _
5008
* @category Array
5009
* @param {...Array} [arrays] The arrays to inspect.
5010
* @returns {Array} Returns the new array of shared values.
5011
* @example
5012
* _.intersection([1, 2], [4, 2], [2, 1]);
5013
* // => [2]
5014
*/
5015
var intersection = restParam(function(arrays) {
5016
var othLength = arrays.length,
5017
othIndex = othLength,
5018
caches = Array(length),
5019
indexOf = getIndexOf(),
5020
isCommon = indexOf == baseIndexOf,
5021
result = [];
5022
5023
while (othIndex--) {
5024
var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
5025
caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
5026
}
5027
var array = arrays[0],
5028
index = -1,
5029
length = array ? array.length : 0,
5030
seen = caches[0];
5031
5032
outer:
5033
while (++index < length) {
5034
value = array[index];
5035
if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
5036
var othIndex = othLength;
5037
while (--othIndex) {
5038
var cache = caches[othIndex];
5039
if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
5040
continue outer;
5041
}
5042
}
5043
if (seen) {
5044
seen.push(value);
5045
}
5046
result.push(value);
5047
}
5048
}
5049
return result;
5050
});
5051
5052
/**
5053
* Gets the last element of `array`.
5054
*
5055
* @static
5056
* @memberOf _
5057
* @category Array
5058
* @param {Array} array The array to query.
5059
* @returns {*} Returns the last element of `array`.
5060
* @example
5061
*
5062
* _.last([1, 2, 3]);
5063
* // => 3
5064
*/
5065
function last(array) {
5066
var length = array ? array.length : 0;
5067
return length ? array[length - 1] : undefined;
5068
}
5069
5070
/**
5071
* This method is like `_.indexOf` except that it iterates over elements of
5072
* `array` from right to left.
5073
*
5074
* @static
5075
* @memberOf _
5076
* @category Array
5077
* @param {Array} array The array to search.
5078
* @param {*} value The value to search for.
5079
* @param {boolean|number} [fromIndex=array.length-1] The index to search from
5080
* or `true` to perform a binary search on a sorted array.
5081
* @returns {number} Returns the index of the matched value, else `-1`.
5082
* @example
5083
*
5084
* _.lastIndexOf([1, 2, 1, 2], 2);
5085
* // => 3
5086
*
5087
* // using `fromIndex`
5088
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
5089
* // => 1
5090
*
5091
* // performing a binary search
5092
* _.lastIndexOf([1, 1, 2, 2], 2, true);
5093
* // => 3
5094
*/
5095
function lastIndexOf(array, value, fromIndex) {
5096
var length = array ? array.length : 0;
5097
if (!length) {
5098
return -1;
5099
}
5100
var index = length;
5101
if (typeof fromIndex == 'number') {
5102
index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
5103
} else if (fromIndex) {
5104
index = binaryIndex(array, value, true) - 1;
5105
var other = array[index];
5106
if (value === value ? (value === other) : (other !== other)) {
5107
return index;
5108
}
5109
return -1;
5110
}
5111
if (value !== value) {
5112
return indexOfNaN(array, index, true);
5113
}
5114
while (index--) {
5115
if (array[index] === value) {
5116
return index;
5117
}
5118
}
5119
return -1;
5120
}
5121
5122
/**
5123
* Removes all provided values from `array` using
5124
* [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
5125
* for equality comparisons.
5126
*
5127
* **Note:** Unlike `_.without`, this method mutates `array`.
5128
*
5129
* @static
5130
* @memberOf _
5131
* @category Array
5132
* @param {Array} array The array to modify.
5133
* @param {...*} [values] The values to remove.
5134
* @returns {Array} Returns `array`.
5135
* @example
5136
*
5137
* var array = [1, 2, 3, 1, 2, 3];
5138
*
5139
* _.pull(array, 2, 3);
5140
* console.log(array);
5141
* // => [1, 1]
5142
*/
5143
function pull() {
5144
var args = arguments,
5145
array = args[0];
5146
5147
if (!(array && array.length)) {
5148
return array;
5149
}
5150
var index = 0,
5151
indexOf = getIndexOf(),
5152
length = args.length;
5153
5154
while (++index < length) {
5155
var fromIndex = 0,
5156
value = args[index];
5157
5158
while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
5159
splice.call(array, fromIndex, 1);
5160
}
5161
}
5162
return array;
5163
}
5164
5165
/**
5166
* Removes elements from `array` corresponding to the given indexes and returns
5167
* an array of the removed elements. Indexes may be specified as an array of
5168
* indexes or as individual arguments.
5169
*
5170
* **Note:** Unlike `_.at`, this method mutates `array`.
5171
*
5172
* @static
5173
* @memberOf _
5174
* @category Array
5175
* @param {Array} array The array to modify.
5176
* @param {...(number|number[])} [indexes] The indexes of elements to remove,
5177
* specified as individual indexes or arrays of indexes.
5178
* @returns {Array} Returns the new array of removed elements.
5179
* @example
5180
*
5181
* var array = [5, 10, 15, 20];
5182
* var evens = _.pullAt(array, 1, 3);
5183
*
5184
* console.log(array);
5185
* // => [5, 15]
5186
*
5187
* console.log(evens);
5188
* // => [10, 20]
5189
*/
5190
var pullAt = restParam(function(array, indexes) {
5191
indexes = baseFlatten(indexes);
5192
5193
var result = baseAt(array, indexes);
5194
basePullAt(array, indexes.sort(baseCompareAscending));
5195
return result;
5196
});
5197
5198
/**
5199
* Removes all elements from `array` that `predicate` returns truthy for
5200
* and returns an array of the removed elements. The predicate is bound to
5201
* `thisArg` and invoked with three arguments: (value, index, array).
5202
*
5203
* If a property name is provided for `predicate` the created `_.property`
5204
* style callback returns the property value of the given element.
5205
*
5206
* If a value is also provided for `thisArg` the created `_.matchesProperty`
5207
* style callback returns `true` for elements that have a matching property
5208
* value, else `false`.
5209
*
5210
* If an object is provided for `predicate` the created `_.matches` style
5211
* callback returns `true` for elements that have the properties of the given
5212
* object, else `false`.
5213
*
5214
* **Note:** Unlike `_.filter`, this method mutates `array`.
5215
*
5216
* @static
5217
* @memberOf _
5218
* @category Array
5219
* @param {Array} array The array to modify.
5220
* @param {Function|Object|string} [predicate=_.identity] The function invoked
5221
* per iteration.
5222
* @param {*} [thisArg] The `this` binding of `predicate`.
5223
* @returns {Array} Returns the new array of removed elements.
5224
* @example
5225
*
5226
* var array = [1, 2, 3, 4];
5227
* var evens = _.remove(array, function(n) {
5228
* return n % 2 == 0;
5229
* });
5230
*
5231
* console.log(array);
5232
* // => [1, 3]
5233
*
5234
* console.log(evens);
5235
* // => [2, 4]
5236
*/
5237
function remove(array, predicate, thisArg) {
5238
var result = [];
5239
if (!(array && array.length)) {
5240
return result;
5241
}
5242
var index = -1,
5243
indexes = [],
5244
length = array.length;
5245
5246
predicate = getCallback(predicate, thisArg, 3);
5247
while (++index < length) {
5248
var value = array[index];
5249
if (predicate(value, index, array)) {
5250
result.push(value);
5251
indexes.push(index);
5252
}
5253
}
5254
basePullAt(array, indexes);
5255
return result;
5256
}
5257
5258
/**
5259
* Gets all but the first element of `array`.
5260
*
5261
* @static
5262
* @memberOf _
5263
* @alias tail
5264
* @category Array
5265
* @param {Array} array The array to query.
5266
* @returns {Array} Returns the slice of `array`.
5267
* @example
5268
*
5269
* _.rest([1, 2, 3]);
5270
* // => [2, 3]
5271
*/
5272
function rest(array) {
5273
return drop(array, 1);
5274
}
5275
5276
/**
5277
* Creates a slice of `array` from `start` up to, but not including, `end`.
5278
*
5279
* **Note:** This method is used instead of `Array#slice` to support node
5280
* lists in IE < 9 and to ensure dense arrays are returned.
5281
*
5282
* @static
5283
* @memberOf _
5284
* @category Array
5285
* @param {Array} array The array to slice.
5286
* @param {number} [start=0] The start position.
5287
* @param {number} [end=array.length] The end position.
5288
* @returns {Array} Returns the slice of `array`.
5289
*/
5290
function slice(array, start, end) {
5291
var length = array ? array.length : 0;
5292
if (!length) {
5293
return [];
5294
}
5295
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
5296
start = 0;
5297
end = length;
5298
}
5299
return baseSlice(array, start, end);
5300
}
5301
5302
/**
5303
* Uses a binary search to determine the lowest index at which `value` should
5304
* be inserted into `array` in order to maintain its sort order. If an iteratee
5305
* function is provided it is invoked for `value` and each element of `array`
5306
* to compute their sort ranking. The iteratee is bound to `thisArg` and
5307
* invoked with one argument; (value).
5308
*
5309
* If a property name is provided for `iteratee` the created `_.property`
5310
* style callback returns the property value of the given element.
5311
*
5312
* If a value is also provided for `thisArg` the created `_.matchesProperty`
5313
* style callback returns `true` for elements that have a matching property
5314
* value, else `false`.
5315
*
5316
* If an object is provided for `iteratee` the created `_.matches` style
5317
* callback returns `true` for elements that have the properties of the given
5318
* object, else `false`.
5319
*
5320
* @static
5321
* @memberOf _
5322
* @category Array
5323
* @param {Array} array The sorted array to inspect.
5324
* @param {*} value The value to evaluate.
5325
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
5326
* per iteration.
5327
* @param {*} [thisArg] The `this` binding of `iteratee`.
5328
* @returns {number} Returns the index at which `value` should be inserted
5329
* into `array`.
5330
* @example
5331
*
5332
* _.sortedIndex([30, 50], 40);
5333
* // => 1
5334
*
5335
* _.sortedIndex([4, 4, 5, 5], 5);
5336
* // => 2
5337
*
5338
* var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
5339
*
5340
* // using an iteratee function
5341
* _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
5342
* return this.data[word];
5343
* }, dict);
5344
* // => 1
5345
*
5346
* // using the `_.property` callback shorthand
5347
* _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
5348
* // => 1
5349
*/
5350
var sortedIndex = createSortedIndex();
5351
5352
/**
5353
* This method is like `_.sortedIndex` except that it returns the highest
5354
* index at which `value` should be inserted into `array` in order to
5355
* maintain its sort order.
5356
*
5357
* @static
5358
* @memberOf _
5359
* @category Array
5360
* @param {Array} array The sorted array to inspect.
5361
* @param {*} value The value to evaluate.
5362
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
5363
* per iteration.
5364
* @param {*} [thisArg] The `this` binding of `iteratee`.
5365
* @returns {number} Returns the index at which `value` should be inserted
5366
* into `array`.
5367
* @example
5368
*
5369
* _.sortedLastIndex([4, 4, 5, 5], 5);
5370
* // => 4
5371
*/
5372
var sortedLastIndex = createSortedIndex(true);
5373
5374
/**
5375
* Creates a slice of `array` with `n` elements taken from the beginning.
5376
*
5377
* @static
5378
* @memberOf _
5379
* @category Array
5380
* @param {Array} array The array to query.
5381
* @param {number} [n=1] The number of elements to take.
5382
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
5383
* @returns {Array} Returns the slice of `array`.
5384
* @example
5385
*
5386
* _.take([1, 2, 3]);
5387
* // => [1]
5388
*
5389
* _.take([1, 2, 3], 2);
5390
* // => [1, 2]
5391
*
5392
* _.take([1, 2, 3], 5);
5393
* // => [1, 2, 3]
5394
*
5395
* _.take([1, 2, 3], 0);
5396
* // => []
5397
*/
5398
function take(array, n, guard) {
5399
var length = array ? array.length : 0;
5400
if (!length) {
5401
return [];
5402
}
5403
if (guard ? isIterateeCall(array, n, guard) : n == null) {
5404
n = 1;
5405
}
5406
return baseSlice(array, 0, n < 0 ? 0 : n);
5407
}
5408
5409
/**
5410
* Creates a slice of `array` with `n` elements taken from the end.
5411
*
5412
* @static
5413
* @memberOf _
5414
* @category Array
5415
* @param {Array} array The array to query.
5416
* @param {number} [n=1] The number of elements to take.
5417
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
5418
* @returns {Array} Returns the slice of `array`.
5419
* @example
5420
*
5421
* _.takeRight([1, 2, 3]);
5422
* // => [3]
5423
*
5424
* _.takeRight([1, 2, 3], 2);
5425
* // => [2, 3]
5426
*
5427
* _.takeRight([1, 2, 3], 5);
5428
* // => [1, 2, 3]
5429
*
5430
* _.takeRight([1, 2, 3], 0);
5431
* // => []
5432
*/
5433
function takeRight(array, n, guard) {
5434
var length = array ? array.length : 0;
5435
if (!length) {
5436
return [];
5437
}
5438
if (guard ? isIterateeCall(array, n, guard) : n == null) {
5439
n = 1;
5440
}
5441
n = length - (+n || 0);
5442
return baseSlice(array, n < 0 ? 0 : n);
5443
}
5444
5445
/**
5446
* Creates a slice of `array` with elements taken from the end. Elements are
5447
* taken until `predicate` returns falsey. The predicate is bound to `thisArg`
5448
* and invoked with three arguments: (value, index, array).
5449
*
5450
* If a property name is provided for `predicate` the created `_.property`
5451
* style callback returns the property value of the given element.
5452
*
5453
* If a value is also provided for `thisArg` the created `_.matchesProperty`
5454
* style callback returns `true` for elements that have a matching property
5455
* value, else `false`.
5456
*
5457
* If an object is provided for `predicate` the created `_.matches` style
5458
* callback returns `true` for elements that have the properties of the given
5459
* object, else `false`.
5460
*
5461
* @static
5462
* @memberOf _
5463
* @category Array
5464
* @param {Array} array The array to query.
5465
* @param {Function|Object|string} [predicate=_.identity] The function invoked
5466
* per iteration.
5467
* @param {*} [thisArg] The `this` binding of `predicate`.
5468
* @returns {Array} Returns the slice of `array`.
5469
* @example
5470
*
5471
* _.takeRightWhile([1, 2, 3], function(n) {
5472
* return n > 1;
5473
* });
5474
* // => [2, 3]
5475
*
5476
* var users = [
5477
* { 'user': 'barney', 'active': true },
5478
* { 'user': 'fred', 'active': false },
5479
* { 'user': 'pebbles', 'active': false }
5480
* ];
5481
*
5482
* // using the `_.matches` callback shorthand
5483
* _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
5484
* // => ['pebbles']
5485
*
5486
* // using the `_.matchesProperty` callback shorthand
5487
* _.pluck(_.takeRightWhile(users, 'active', false), 'user');
5488
* // => ['fred', 'pebbles']
5489
*
5490
* // using the `_.property` callback shorthand
5491
* _.pluck(_.takeRightWhile(users, 'active'), 'user');
5492
* // => []
5493
*/
5494
function takeRightWhile(array, predicate, thisArg) {
5495
return (array && array.length)
5496
? baseWhile(array, getCallback(predicate, thisArg, 3), false, true)
5497
: [];
5498
}
5499
5500
/**
5501
* Creates a slice of `array` with elements taken from the beginning. Elements
5502
* are taken until `predicate` returns falsey. The predicate is bound to
5503
* `thisArg` and invoked with three arguments: (value, index, array).
5504
*
5505
* If a property name is provided for `predicate` the created `_.property`
5506
* style callback returns the property value of the given element.
5507
*
5508
* If a value is also provided for `thisArg` the created `_.matchesProperty`
5509
* style callback returns `true` for elements that have a matching property
5510
* value, else `false`.
5511
*
5512
* If an object is provided for `predicate` the created `_.matches` style
5513
* callback returns `true` for elements that have the properties of the given
5514
* object, else `false`.
5515
*
5516
* @static
5517
* @memberOf _
5518
* @category Array
5519
* @param {Array} array The array to query.
5520
* @param {Function|Object|string} [predicate=_.identity] The function invoked
5521
* per iteration.
5522
* @param {*} [thisArg] The `this` binding of `predicate`.
5523
* @returns {Array} Returns the slice of `array`.
5524
* @example
5525
*
5526
* _.takeWhile([1, 2, 3], function(n) {
5527
* return n < 3;
5528
* });
5529
* // => [1, 2]
5530
*
5531
* var users = [
5532
* { 'user': 'barney', 'active': false },
5533
* { 'user': 'fred', 'active': false},
5534
* { 'user': 'pebbles', 'active': true }
5535
* ];
5536
*
5537
* // using the `_.matches` callback shorthand
5538
* _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
5539
* // => ['barney']
5540
*
5541
* // using the `_.matchesProperty` callback shorthand
5542
* _.pluck(_.takeWhile(users, 'active', false), 'user');
5543
* // => ['barney', 'fred']
5544
*
5545
* // using the `_.property` callback shorthand
5546
* _.pluck(_.takeWhile(users, 'active'), 'user');
5547
* // => []
5548
*/
5549
function takeWhile(array, predicate, thisArg) {
5550
return (array && array.length)
5551
? baseWhile(array, getCallback(predicate, thisArg, 3))
5552
: [];
5553
}
5554
5555
/**
5556
* Creates an array of unique values, in order, from all of the provided arrays
5557
* using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
5558
* for equality comparisons.
5559
*
5560
* @static
5561
* @memberOf _
5562
* @category Array
5563
* @param {...Array} [arrays] The arrays to inspect.
5564
* @returns {Array} Returns the new array of combined values.
5565
* @example
5566
*
5567
* _.union([1, 2], [4, 2], [2, 1]);
5568
* // => [1, 2, 4]
5569
*/
5570
var union = restParam(function(arrays) {
5571
return baseUniq(baseFlatten(arrays, false, true));
5572
});
5573
5574
/**
5575
* Creates a duplicate-free version of an array, using
5576
* [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
5577
* for equality comparisons, in which only the first occurence of each element
5578
* is kept. Providing `true` for `isSorted` performs a faster search algorithm
5579
* for sorted arrays. If an iteratee function is provided it is invoked for
5580
* each element in the array to generate the criterion by which uniqueness
5581
* is computed. The `iteratee` is bound to `thisArg` and invoked with three
5582
* arguments: (value, index, array).
5583
*
5584
* If a property name is provided for `iteratee` the created `_.property`
5585
* style callback returns the property value of the given element.
5586
*
5587
* If a value is also provided for `thisArg` the created `_.matchesProperty`
5588
* style callback returns `true` for elements that have a matching property
5589
* value, else `false`.
5590
*
5591
* If an object is provided for `iteratee` the created `_.matches` style
5592
* callback returns `true` for elements that have the properties of the given
5593
* object, else `false`.
5594
*
5595
* @static
5596
* @memberOf _
5597
* @alias unique
5598
* @category Array
5599
* @param {Array} array The array to inspect.
5600
* @param {boolean} [isSorted] Specify the array is sorted.
5601
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
5602
* @param {*} [thisArg] The `this` binding of `iteratee`.
5603
* @returns {Array} Returns the new duplicate-value-free array.
5604
* @example
5605
*
5606
* _.uniq([2, 1, 2]);
5607
* // => [2, 1]
5608
*
5609
* // using `isSorted`
5610
* _.uniq([1, 1, 2], true);
5611
* // => [1, 2]
5612
*
5613
* // using an iteratee function
5614
* _.uniq([1, 2.5, 1.5, 2], function(n) {
5615
* return this.floor(n);
5616
* }, Math);
5617
* // => [1, 2.5]
5618
*
5619
* // using the `_.property` callback shorthand
5620
* _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
5621
* // => [{ 'x': 1 }, { 'x': 2 }]
5622
*/
5623
function uniq(array, isSorted, iteratee, thisArg) {
5624
var length = array ? array.length : 0;
5625
if (!length) {
5626
return [];
5627
}
5628
if (isSorted != null && typeof isSorted != 'boolean') {
5629
thisArg = iteratee;
5630
iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted;
5631
isSorted = false;
5632
}
5633
var callback = getCallback();
5634
if (!(iteratee == null && callback === baseCallback)) {
5635
iteratee = callback(iteratee, thisArg, 3);
5636
}
5637
return (isSorted && getIndexOf() == baseIndexOf)
5638
? sortedUniq(array, iteratee)
5639
: baseUniq(array, iteratee);
5640
}
5641
5642
/**
5643
* This method is like `_.zip` except that it accepts an array of grouped
5644
* elements and creates an array regrouping the elements to their pre-zip
5645
* configuration.
5646
*
5647
* @static
5648
* @memberOf _
5649
* @category Array
5650
* @param {Array} array The array of grouped elements to process.
5651
* @returns {Array} Returns the new array of regrouped elements.
5652
* @example
5653
*
5654
* var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
5655
* // => [['fred', 30, true], ['barney', 40, false]]
5656
*
5657
* _.unzip(zipped);
5658
* // => [['fred', 'barney'], [30, 40], [true, false]]
5659
*/
5660
function unzip(array) {
5661
if (!(array && array.length)) {
5662
return [];
5663
}
5664
var index = -1,
5665
length = 0;
5666
5667
array = arrayFilter(array, function(group) {
5668
if (isArrayLike(group)) {
5669
length = nativeMax(group.length, length);
5670
return true;
5671
}
5672
});
5673
var result = Array(length);
5674
while (++index < length) {
5675
result[index] = arrayMap(array, baseProperty(index));
5676
}
5677
return result;
5678
}
5679
5680
/**
5681
* This method is like `_.unzip` except that it accepts an iteratee to specify
5682
* how regrouped values should be combined. The `iteratee` is bound to `thisArg`
5683
* and invoked with four arguments: (accumulator, value, index, group).
5684
*
5685
* @static
5686
* @memberOf _
5687
* @category Array
5688
* @param {Array} array The array of grouped elements to process.
5689
* @param {Function} [iteratee] The function to combine regrouped values.
5690
* @param {*} [thisArg] The `this` binding of `iteratee`.
5691
* @returns {Array} Returns the new array of regrouped elements.
5692
* @example
5693
*
5694
* var zipped = _.zip([1, 2], [10, 20], [100, 200]);
5695
* // => [[1, 10, 100], [2, 20, 200]]
5696
*
5697
* _.unzipWith(zipped, _.add);
5698
* // => [3, 30, 300]
5699
*/
5700
function unzipWith(array, iteratee, thisArg) {
5701
var length = array ? array.length : 0;
5702
if (!length) {
5703
return [];
5704
}
5705
var result = unzip(array);
5706
if (iteratee == null) {
5707
return result;
5708
}
5709
iteratee = bindCallback(iteratee, thisArg, 4);
5710
return arrayMap(result, function(group) {
5711
return arrayReduce(group, iteratee, undefined, true);
5712
});
5713
}
5714
5715
/**
5716
* Creates an array excluding all provided values using
5717
* [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
5718
* for equality comparisons.
5719
*
5720
* @static
5721
* @memberOf _
5722
* @category Array
5723
* @param {Array} array The array to filter.
5724
* @param {...*} [values] The values to exclude.
5725
* @returns {Array} Returns the new array of filtered values.
5726
* @example
5727
*
5728
* _.without([1, 2, 1, 3], 1, 2);
5729
* // => [3]
5730
*/
5731
var without = restParam(function(array, values) {
5732
return isArrayLike(array)
5733
? baseDifference(array, values)
5734
: [];
5735
});
5736
5737
/**
5738
* Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
5739
* of the provided arrays.
5740
*
5741
* @static
5742
* @memberOf _
5743
* @category Array
5744
* @param {...Array} [arrays] The arrays to inspect.
5745
* @returns {Array} Returns the new array of values.
5746
* @example
5747
*
5748
* _.xor([1, 2], [4, 2]);
5749
* // => [1, 4]
5750
*/
5751
function xor() {
5752
var index = -1,
5753
length = arguments.length;
5754
5755
while (++index < length) {
5756
var array = arguments[index];
5757
if (isArrayLike(array)) {
5758
var result = result
5759
? baseDifference(result, array).concat(baseDifference(array, result))
5760
: array;
5761
}
5762
}
5763
return result ? baseUniq(result) : [];
5764
}
5765
5766
/**
5767
* Creates an array of grouped elements, the first of which contains the first
5768
* elements of the given arrays, the second of which contains the second elements
5769
* of the given arrays, and so on.
5770
*
5771
* @static
5772
* @memberOf _
5773
* @category Array
5774
* @param {...Array} [arrays] The arrays to process.
5775
* @returns {Array} Returns the new array of grouped elements.
5776
* @example
5777
*
5778
* _.zip(['fred', 'barney'], [30, 40], [true, false]);
5779
* // => [['fred', 30, true], ['barney', 40, false]]
5780
*/
5781
var zip = restParam(unzip);
5782
5783
/**
5784
* The inverse of `_.pairs`; this method returns an object composed from arrays
5785
* of property names and values. Provide either a single two dimensional array,
5786
* e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
5787
* and one of corresponding values.
5788
*
5789
* @static
5790
* @memberOf _
5791
* @alias object
5792
* @category Array
5793
* @param {Array} props The property names.
5794
* @param {Array} [values=[]] The property values.
5795
* @returns {Object} Returns the new object.
5796
* @example
5797
*
5798
* _.zipObject([['fred', 30], ['barney', 40]]);
5799
* // => { 'fred': 30, 'barney': 40 }
5800
*
5801
* _.zipObject(['fred', 'barney'], [30, 40]);
5802
* // => { 'fred': 30, 'barney': 40 }
5803
*/
5804
function zipObject(props, values) {
5805
var index = -1,
5806
length = props ? props.length : 0,
5807
result = {};
5808
5809
if (length && !values && !isArray(props[0])) {
5810
values = [];
5811
}
5812
while (++index < length) {
5813
var key = props[index];
5814
if (values) {
5815
result[key] = values[index];
5816
} else if (key) {
5817
result[key[0]] = key[1];
5818
}
5819
}
5820
return result;
5821
}
5822
5823
/**
5824
* This method is like `_.zip` except that it accepts an iteratee to specify
5825
* how grouped values should be combined. The `iteratee` is bound to `thisArg`
5826
* and invoked with four arguments: (accumulator, value, index, group).
5827
*
5828
* @static
5829
* @memberOf _
5830
* @category Array
5831
* @param {...Array} [arrays] The arrays to process.
5832
* @param {Function} [iteratee] The function to combine grouped values.
5833
* @param {*} [thisArg] The `this` binding of `iteratee`.
5834
* @returns {Array} Returns the new array of grouped elements.
5835
* @example
5836
*
5837
* _.zipWith([1, 2], [10, 20], [100, 200], _.add);
5838
* // => [111, 222]
5839
*/
5840
var zipWith = restParam(function(arrays) {
5841
var length = arrays.length,
5842
iteratee = length > 2 ? arrays[length - 2] : undefined,
5843
thisArg = length > 1 ? arrays[length - 1] : undefined;
5844
5845
if (length > 2 && typeof iteratee == 'function') {
5846
length -= 2;
5847
} else {
5848
iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined;
5849
thisArg = undefined;
5850
}
5851
arrays.length = length;
5852
return unzipWith(arrays, iteratee, thisArg);
5853
});
5854
5855
/*------------------------------------------------------------------------*/
5856
5857
/**
5858
* Creates a `lodash` object that wraps `value` with explicit method
5859
* chaining enabled.
5860
*
5861
* @static
5862
* @memberOf _
5863
* @category Chain
5864
* @param {*} value The value to wrap.
5865
* @returns {Object} Returns the new `lodash` wrapper instance.
5866
* @example
5867
*
5868
* var users = [
5869
* { 'user': 'barney', 'age': 36 },
5870
* { 'user': 'fred', 'age': 40 },
5871
* { 'user': 'pebbles', 'age': 1 }
5872
* ];
5873
*
5874
* var youngest = _.chain(users)
5875
* .sortBy('age')
5876
* .map(function(chr) {
5877
* return chr.user + ' is ' + chr.age;
5878
* })
5879
* .first()
5880
* .value();
5881
* // => 'pebbles is 1'
5882
*/
5883
function chain(value) {
5884
var result = lodash(value);
5885
result.__chain__ = true;
5886
return result;
5887
}
5888
5889
/**
5890
* This method invokes `interceptor` and returns `value`. The interceptor is
5891
* bound to `thisArg` and invoked with one argument; (value). The purpose of
5892
* this method is to "tap into" a method chain in order to perform operations
5893
* on intermediate results within the chain.
5894
*
5895
* @static
5896
* @memberOf _
5897
* @category Chain
5898
* @param {*} value The value to provide to `interceptor`.
5899
* @param {Function} interceptor The function to invoke.
5900
* @param {*} [thisArg] The `this` binding of `interceptor`.
5901
* @returns {*} Returns `value`.
5902
* @example
5903
*
5904
* _([1, 2, 3])
5905
* .tap(function(array) {
5906
* array.pop();
5907
* })
5908
* .reverse()
5909
* .value();
5910
* // => [2, 1]
5911
*/
5912
function tap(value, interceptor, thisArg) {
5913
interceptor.call(thisArg, value);
5914
return value;
5915
}
5916
5917
/**
5918
* This method is like `_.tap` except that it returns the result of `interceptor`.
5919
*
5920
* @static
5921
* @memberOf _
5922
* @category Chain
5923
* @param {*} value The value to provide to `interceptor`.
5924
* @param {Function} interceptor The function to invoke.
5925
* @param {*} [thisArg] The `this` binding of `interceptor`.
5926
* @returns {*} Returns the result of `interceptor`.
5927
* @example
5928
*
5929
* _(' abc ')
5930
* .chain()
5931
* .trim()
5932
* .thru(function(value) {
5933
* return [value];
5934
* })
5935
* .value();
5936
* // => ['abc']
5937
*/
5938
function thru(value, interceptor, thisArg) {
5939
return interceptor.call(thisArg, value);
5940
}
5941
5942
/**
5943
* Enables explicit method chaining on the wrapper object.
5944
*
5945
* @name chain
5946
* @memberOf _
5947
* @category Chain
5948
* @returns {Object} Returns the new `lodash` wrapper instance.
5949
* @example
5950
*
5951
* var users = [
5952
* { 'user': 'barney', 'age': 36 },
5953
* { 'user': 'fred', 'age': 40 }
5954
* ];
5955
*
5956
* // without explicit chaining
5957
* _(users).first();
5958
* // => { 'user': 'barney', 'age': 36 }
5959
*
5960
* // with explicit chaining
5961
* _(users).chain()
5962
* .first()
5963
* .pick('user')
5964
* .value();
5965
* // => { 'user': 'barney' }
5966
*/
5967
function wrapperChain() {
5968
return chain(this);
5969
}
5970
5971
/**
5972
* Executes the chained sequence and returns the wrapped result.
5973
*
5974
* @name commit
5975
* @memberOf _
5976
* @category Chain
5977
* @returns {Object} Returns the new `lodash` wrapper instance.
5978
* @example
5979
*
5980
* var array = [1, 2];
5981
* var wrapper = _(array).push(3);
5982
*
5983
* console.log(array);
5984
* // => [1, 2]
5985
*
5986
* wrapper = wrapper.commit();
5987
* console.log(array);
5988
* // => [1, 2, 3]
5989
*
5990
* wrapper.last();
5991
* // => 3
5992
*
5993
* console.log(array);
5994
* // => [1, 2, 3]
5995
*/
5996
function wrapperCommit() {
5997
return new LodashWrapper(this.value(), this.__chain__);
5998
}
5999
6000
/**
6001
* Creates a clone of the chained sequence planting `value` as the wrapped value.
6002
*
6003
* @name plant
6004
* @memberOf _
6005
* @category Chain
6006
* @returns {Object} Returns the new `lodash` wrapper instance.
6007
* @example
6008
*
6009
* var array = [1, 2];
6010
* var wrapper = _(array).map(function(value) {
6011
* return Math.pow(value, 2);
6012
* });
6013
*
6014
* var other = [3, 4];
6015
* var otherWrapper = wrapper.plant(other);
6016
*
6017
* otherWrapper.value();
6018
* // => [9, 16]
6019
*
6020
* wrapper.value();
6021
* // => [1, 4]
6022
*/
6023
function wrapperPlant(value) {
6024
var result,
6025
parent = this;
6026
6027
while (parent instanceof baseLodash) {
6028
var clone = wrapperClone(parent);
6029
if (result) {
6030
previous.__wrapped__ = clone;
6031
} else {
6032
result = clone;
6033
}
6034
var previous = clone;
6035
parent = parent.__wrapped__;
6036
}
6037
previous.__wrapped__ = value;
6038
return result;
6039
}
6040
6041
/**
6042
* Reverses the wrapped array so the first element becomes the last, the
6043
* second element becomes the second to last, and so on.
6044
*
6045
* **Note:** This method mutates the wrapped array.
6046
*
6047
* @name reverse
6048
* @memberOf _
6049
* @category Chain
6050
* @returns {Object} Returns the new reversed `lodash` wrapper instance.
6051
* @example
6052
*
6053
* var array = [1, 2, 3];
6054
*
6055
* _(array).reverse().value()
6056
* // => [3, 2, 1]
6057
*
6058
* console.log(array);
6059
* // => [3, 2, 1]
6060
*/
6061
function wrapperReverse() {
6062
var value = this.__wrapped__;
6063
if (value instanceof LazyWrapper) {
6064
if (this.__actions__.length) {
6065
value = new LazyWrapper(this);
6066
}
6067
return new LodashWrapper(value.reverse(), this.__chain__);
6068
}
6069
return this.thru(function(value) {
6070
return value.reverse();
6071
});
6072
}
6073
6074
/**
6075
* Produces the result of coercing the unwrapped value to a string.
6076
*
6077
* @name toString
6078
* @memberOf _
6079
* @category Chain
6080
* @returns {string} Returns the coerced string value.
6081
* @example
6082
*
6083
* _([1, 2, 3]).toString();
6084
* // => '1,2,3'
6085
*/
6086
function wrapperToString() {
6087
return (this.value() + '');
6088
}
6089
6090
/**
6091
* Executes the chained sequence to extract the unwrapped value.
6092
*
6093
* @name value
6094
* @memberOf _
6095
* @alias run, toJSON, valueOf
6096
* @category Chain
6097
* @returns {*} Returns the resolved unwrapped value.
6098
* @example
6099
*
6100
* _([1, 2, 3]).value();
6101
* // => [1, 2, 3]
6102
*/
6103
function wrapperValue() {
6104
return baseWrapperValue(this.__wrapped__, this.__actions__);
6105
}
6106
6107
/*------------------------------------------------------------------------*/
6108
6109
/**
6110
* Creates an array of elements corresponding to the given keys, or indexes,
6111
* of `collection`. Keys may be specified as individual arguments or as arrays
6112
* of keys.
6113
*
6114
* @static
6115
* @memberOf _
6116
* @category Collection
6117
* @param {Array|Object|string} collection The collection to iterate over.
6118
* @param {...(number|number[]|string|string[])} [props] The property names
6119
* or indexes of elements to pick, specified individually or in arrays.
6120
* @returns {Array} Returns the new array of picked elements.
6121
* @example
6122
*
6123
* _.at(['a', 'b', 'c'], [0, 2]);
6124
* // => ['a', 'c']
6125
*
6126
* _.at(['barney', 'fred', 'pebbles'], 0, 2);
6127
* // => ['barney', 'pebbles']
6128
*/
6129
var at = restParam(function(collection, props) {
6130
return baseAt(collection, baseFlatten(props));
6131
});
6132
6133
/**
6134
* Creates an object composed of keys generated from the results of running
6135
* each element of `collection` through `iteratee`. The corresponding value
6136
* of each key is the number of times the key was returned by `iteratee`.
6137
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
6138
* (value, index|key, collection).
6139
*
6140
* If a property name is provided for `iteratee` the created `_.property`
6141
* style callback returns the property value of the given element.
6142
*
6143
* If a value is also provided for `thisArg` the created `_.matchesProperty`
6144
* style callback returns `true` for elements that have a matching property
6145
* value, else `false`.
6146
*
6147
* If an object is provided for `iteratee` the created `_.matches` style
6148
* callback returns `true` for elements that have the properties of the given
6149
* object, else `false`.
6150
*
6151
* @static
6152
* @memberOf _
6153
* @category Collection
6154
* @param {Array|Object|string} collection The collection to iterate over.
6155
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
6156
* per iteration.
6157
* @param {*} [thisArg] The `this` binding of `iteratee`.
6158
* @returns {Object} Returns the composed aggregate object.
6159
* @example
6160
*
6161
* _.countBy([4.3, 6.1, 6.4], function(n) {
6162
* return Math.floor(n);
6163
* });
6164
* // => { '4': 1, '6': 2 }
6165
*
6166
* _.countBy([4.3, 6.1, 6.4], function(n) {
6167
* return this.floor(n);
6168
* }, Math);
6169
* // => { '4': 1, '6': 2 }
6170
*
6171
* _.countBy(['one', 'two', 'three'], 'length');
6172
* // => { '3': 2, '5': 1 }
6173
*/
6174
var countBy = createAggregator(function(result, value, key) {
6175
hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
6176
});
6177
6178
/**
6179
* Checks if `predicate` returns truthy for **all** elements of `collection`.
6180
* The predicate is bound to `thisArg` and invoked with three arguments:
6181
* (value, index|key, collection).
6182
*
6183
* If a property name is provided for `predicate` the created `_.property`
6184
* style callback returns the property value of the given element.
6185
*
6186
* If a value is also provided for `thisArg` the created `_.matchesProperty`
6187
* style callback returns `true` for elements that have a matching property
6188
* value, else `false`.
6189
*
6190
* If an object is provided for `predicate` the created `_.matches` style
6191
* callback returns `true` for elements that have the properties of the given
6192
* object, else `false`.
6193
*
6194
* @static
6195
* @memberOf _
6196
* @alias all
6197
* @category Collection
6198
* @param {Array|Object|string} collection The collection to iterate over.
6199
* @param {Function|Object|string} [predicate=_.identity] The function invoked
6200
* per iteration.
6201
* @param {*} [thisArg] The `this` binding of `predicate`.
6202
* @returns {boolean} Returns `true` if all elements pass the predicate check,
6203
* else `false`.
6204
* @example
6205
*
6206
* _.every([true, 1, null, 'yes'], Boolean);
6207
* // => false
6208
*
6209
* var users = [
6210
* { 'user': 'barney', 'active': false },
6211
* { 'user': 'fred', 'active': false }
6212
* ];
6213
*
6214
* // using the `_.matches` callback shorthand
6215
* _.every(users, { 'user': 'barney', 'active': false });
6216
* // => false
6217
*
6218
* // using the `_.matchesProperty` callback shorthand
6219
* _.every(users, 'active', false);
6220
* // => true
6221
*
6222
* // using the `_.property` callback shorthand
6223
* _.every(users, 'active');
6224
* // => false
6225
*/
6226
function every(collection, predicate, thisArg) {
6227
var func = isArray(collection) ? arrayEvery : baseEvery;
6228
if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
6229
predicate = null;
6230
}
6231
if (typeof predicate != 'function' || thisArg !== undefined) {
6232
predicate = getCallback(predicate, thisArg, 3);
6233
}
6234
return func(collection, predicate);
6235
}
6236
6237
/**
6238
* Iterates over elements of `collection`, returning an array of all elements
6239
* `predicate` returns truthy for. The predicate is bound to `thisArg` and
6240
* invoked with three arguments: (value, index|key, collection).
6241
*
6242
* If a property name is provided for `predicate` the created `_.property`
6243
* style callback returns the property value of the given element.
6244
*
6245
* If a value is also provided for `thisArg` the created `_.matchesProperty`
6246
* style callback returns `true` for elements that have a matching property
6247
* value, else `false`.
6248
*
6249
* If an object is provided for `predicate` the created `_.matches` style
6250
* callback returns `true` for elements that have the properties of the given
6251
* object, else `false`.
6252
*
6253
* @static
6254
* @memberOf _
6255
* @alias select
6256
* @category Collection
6257
* @param {Array|Object|string} collection The collection to iterate over.
6258
* @param {Function|Object|string} [predicate=_.identity] The function invoked
6259
* per iteration.
6260
* @param {*} [thisArg] The `this` binding of `predicate`.
6261
* @returns {Array} Returns the new filtered array.
6262
* @example
6263
*
6264
* _.filter([4, 5, 6], function(n) {
6265
* return n % 2 == 0;
6266
* });
6267
* // => [4, 6]
6268
*
6269
* var users = [
6270
* { 'user': 'barney', 'age': 36, 'active': true },
6271
* { 'user': 'fred', 'age': 40, 'active': false }
6272
* ];
6273
*
6274
* // using the `_.matches` callback shorthand
6275
* _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
6276
* // => ['barney']
6277
*
6278
* // using the `_.matchesProperty` callback shorthand
6279
* _.pluck(_.filter(users, 'active', false), 'user');
6280
* // => ['fred']
6281
*
6282
* // using the `_.property` callback shorthand
6283
* _.pluck(_.filter(users, 'active'), 'user');
6284
* // => ['barney']
6285
*/
6286
function filter(collection, predicate, thisArg) {
6287
var func = isArray(collection) ? arrayFilter : baseFilter;
6288
predicate = getCallback(predicate, thisArg, 3);
6289
return func(collection, predicate);
6290
}
6291
6292
/**
6293
* Iterates over elements of `collection`, returning the first element
6294
* `predicate` returns truthy for. The predicate is bound to `thisArg` and
6295
* invoked with three arguments: (value, index|key, collection).
6296
*
6297
* If a property name is provided for `predicate` the created `_.property`
6298
* style callback returns the property value of the given element.
6299
*
6300
* If a value is also provided for `thisArg` the created `_.matchesProperty`
6301
* style callback returns `true` for elements that have a matching property
6302
* value, else `false`.
6303
*
6304
* If an object is provided for `predicate` the created `_.matches` style
6305
* callback returns `true` for elements that have the properties of the given
6306
* object, else `false`.
6307
*
6308
* @static
6309
* @memberOf _
6310
* @alias detect
6311
* @category Collection
6312
* @param {Array|Object|string} collection The collection to search.
6313
* @param {Function|Object|string} [predicate=_.identity] The function invoked
6314
* per iteration.
6315
* @param {*} [thisArg] The `this` binding of `predicate`.
6316
* @returns {*} Returns the matched element, else `undefined`.
6317
* @example
6318
*
6319
* var users = [
6320
* { 'user': 'barney', 'age': 36, 'active': true },
6321
* { 'user': 'fred', 'age': 40, 'active': false },
6322
* { 'user': 'pebbles', 'age': 1, 'active': true }
6323
* ];
6324
*
6325
* _.result(_.find(users, function(chr) {
6326
* return chr.age < 40;
6327
* }), 'user');
6328
* // => 'barney'
6329
*
6330
* // using the `_.matches` callback shorthand
6331
* _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
6332
* // => 'pebbles'
6333
*
6334
* // using the `_.matchesProperty` callback shorthand
6335
* _.result(_.find(users, 'active', false), 'user');
6336
* // => 'fred'
6337
*
6338
* // using the `_.property` callback shorthand
6339
* _.result(_.find(users, 'active'), 'user');
6340
* // => 'barney'
6341
*/
6342
var find = createFind(baseEach);
6343
6344
/**
6345
* This method is like `_.find` except that it iterates over elements of
6346
* `collection` from right to left.
6347
*
6348
* @static
6349
* @memberOf _
6350
* @category Collection
6351
* @param {Array|Object|string} collection The collection to search.
6352
* @param {Function|Object|string} [predicate=_.identity] The function invoked
6353
* per iteration.
6354
* @param {*} [thisArg] The `this` binding of `predicate`.
6355
* @returns {*} Returns the matched element, else `undefined`.
6356
* @example
6357
*
6358
* _.findLast([1, 2, 3, 4], function(n) {
6359
* return n % 2 == 1;
6360
* });
6361
* // => 3
6362
*/
6363
var findLast = createFind(baseEachRight, true);
6364
6365
/**
6366
* Performs a deep comparison between each element in `collection` and the
6367
* source object, returning the first element that has equivalent property
6368
* values.
6369
*
6370
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
6371
* numbers, `Object` objects, regexes, and strings. Objects are compared by
6372
* their own, not inherited, enumerable properties. For comparing a single
6373
* own or inherited property value see `_.matchesProperty`.
6374
*
6375
* @static
6376
* @memberOf _
6377
* @category Collection
6378
* @param {Array|Object|string} collection The collection to search.
6379
* @param {Object} source The object of property values to match.
6380
* @returns {*} Returns the matched element, else `undefined`.
6381
* @example
6382
*
6383
* var users = [
6384
* { 'user': 'barney', 'age': 36, 'active': true },
6385
* { 'user': 'fred', 'age': 40, 'active': false }
6386
* ];
6387
*
6388
* _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
6389
* // => 'barney'
6390
*
6391
* _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
6392
* // => 'fred'
6393
*/
6394
function findWhere(collection, source) {
6395
return find(collection, baseMatches(source));
6396
}
6397
6398
/**
6399
* Iterates over elements of `collection` invoking `iteratee` for each element.
6400
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
6401
* (value, index|key, collection). Iteratee functions may exit iteration early
6402
* by explicitly returning `false`.
6403
*
6404
* **Note:** As with other "Collections" methods, objects with a "length" property
6405
* are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
6406
* may be used for object iteration.
6407
*
6408
* @static
6409
* @memberOf _
6410
* @alias each
6411
* @category Collection
6412
* @param {Array|Object|string} collection The collection to iterate over.
6413
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
6414
* @param {*} [thisArg] The `this` binding of `iteratee`.
6415
* @returns {Array|Object|string} Returns `collection`.
6416
* @example
6417
*
6418
* _([1, 2]).forEach(function(n) {
6419
* console.log(n);
6420
* }).value();
6421
* // => logs each value from left to right and returns the array
6422
*
6423
* _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
6424
* console.log(n, key);
6425
* });
6426
* // => logs each value-key pair and returns the object (iteration order is not guaranteed)
6427
*/
6428
var forEach = createForEach(arrayEach, baseEach);
6429
6430
/**
6431
* This method is like `_.forEach` except that it iterates over elements of
6432
* `collection` from right to left.
6433
*
6434
* @static
6435
* @memberOf _
6436
* @alias eachRight
6437
* @category Collection
6438
* @param {Array|Object|string} collection The collection to iterate over.
6439
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
6440
* @param {*} [thisArg] The `this` binding of `iteratee`.
6441
* @returns {Array|Object|string} Returns `collection`.
6442
* @example
6443
*
6444
* _([1, 2]).forEachRight(function(n) {
6445
* console.log(n);
6446
* }).value();
6447
* // => logs each value from right to left and returns the array
6448
*/
6449
var forEachRight = createForEach(arrayEachRight, baseEachRight);
6450
6451
/**
6452
* Creates an object composed of keys generated from the results of running
6453
* each element of `collection` through `iteratee`. The corresponding value
6454
* of each key is an array of the elements responsible for generating the key.
6455
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
6456
* (value, index|key, collection).
6457
*
6458
* If a property name is provided for `iteratee` the created `_.property`
6459
* style callback returns the property value of the given element.
6460
*
6461
* If a value is also provided for `thisArg` the created `_.matchesProperty`
6462
* style callback returns `true` for elements that have a matching property
6463
* value, else `false`.
6464
*
6465
* If an object is provided for `iteratee` the created `_.matches` style
6466
* callback returns `true` for elements that have the properties of the given
6467
* object, else `false`.
6468
*
6469
* @static
6470
* @memberOf _
6471
* @category Collection
6472
* @param {Array|Object|string} collection The collection to iterate over.
6473
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
6474
* per iteration.
6475
* @param {*} [thisArg] The `this` binding of `iteratee`.
6476
* @returns {Object} Returns the composed aggregate object.
6477
* @example
6478
*
6479
* _.groupBy([4.2, 6.1, 6.4], function(n) {
6480
* return Math.floor(n);
6481
* });
6482
* // => { '4': [4.2], '6': [6.1, 6.4] }
6483
*
6484
* _.groupBy([4.2, 6.1, 6.4], function(n) {
6485
* return this.floor(n);
6486
* }, Math);
6487
* // => { '4': [4.2], '6': [6.1, 6.4] }
6488
*
6489
* // using the `_.property` callback shorthand
6490
* _.groupBy(['one', 'two', 'three'], 'length');
6491
* // => { '3': ['one', 'two'], '5': ['three'] }
6492
*/
6493
var groupBy = createAggregator(function(result, value, key) {
6494
if (hasOwnProperty.call(result, key)) {
6495
result[key].push(value);
6496
} else {
6497
result[key] = [value];
6498
}
6499
});
6500
6501
/**
6502
* Checks if `value` is in `collection` using
6503
* [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
6504
* for equality comparisons. If `fromIndex` is negative, it is used as the offset
6505
* from the end of `collection`.
6506
*
6507
* @static
6508
* @memberOf _
6509
* @alias contains, include
6510
* @category Collection
6511
* @param {Array|Object|string} collection The collection to search.
6512
* @param {*} target The value to search for.
6513
* @param {number} [fromIndex=0] The index to search from.
6514
* @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
6515
* @returns {boolean} Returns `true` if a matching element is found, else `false`.
6516
* @example
6517
*
6518
* _.includes([1, 2, 3], 1);
6519
* // => true
6520
*
6521
* _.includes([1, 2, 3], 1, 2);
6522
* // => false
6523
*
6524
* _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
6525
* // => true
6526
*
6527
* _.includes('pebbles', 'eb');
6528
* // => true
6529
*/
6530
function includes(collection, target, fromIndex, guard) {
6531
var length = collection ? getLength(collection) : 0;
6532
if (!isLength(length)) {
6533
collection = values(collection);
6534
length = collection.length;
6535
}
6536
if (!length) {
6537
return false;
6538
}
6539
if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
6540
fromIndex = 0;
6541
} else {
6542
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
6543
}
6544
return (typeof collection == 'string' || !isArray(collection) && isString(collection))
6545
? (fromIndex < length && collection.indexOf(target, fromIndex) > -1)
6546
: (getIndexOf(collection, target, fromIndex) > -1);
6547
}
6548
6549
/**
6550
* Creates an object composed of keys generated from the results of running
6551
* each element of `collection` through `iteratee`. The corresponding value
6552
* of each key is the last element responsible for generating the key. The
6553
* iteratee function is bound to `thisArg` and invoked with three arguments:
6554
* (value, index|key, collection).
6555
*
6556
* If a property name is provided for `iteratee` the created `_.property`
6557
* style callback returns the property value of the given element.
6558
*
6559
* If a value is also provided for `thisArg` the created `_.matchesProperty`
6560
* style callback returns `true` for elements that have a matching property
6561
* value, else `false`.
6562
*
6563
* If an object is provided for `iteratee` the created `_.matches` style
6564
* callback returns `true` for elements that have the properties of the given
6565
* object, else `false`.
6566
*
6567
* @static
6568
* @memberOf _
6569
* @category Collection
6570
* @param {Array|Object|string} collection The collection to iterate over.
6571
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
6572
* per iteration.
6573
* @param {*} [thisArg] The `this` binding of `iteratee`.
6574
* @returns {Object} Returns the composed aggregate object.
6575
* @example
6576
*
6577
* var keyData = [
6578
* { 'dir': 'left', 'code': 97 },
6579
* { 'dir': 'right', 'code': 100 }
6580
* ];
6581
*
6582
* _.indexBy(keyData, 'dir');
6583
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
6584
*
6585
* _.indexBy(keyData, function(object) {
6586
* return String.fromCharCode(object.code);
6587
* });
6588
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
6589
*
6590
* _.indexBy(keyData, function(object) {
6591
* return this.fromCharCode(object.code);
6592
* }, String);
6593
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
6594
*/
6595
var indexBy = createAggregator(function(result, value, key) {
6596
result[key] = value;
6597
});
6598
6599
/**
6600
* Invokes the method at `path` of each element in `collection`, returning
6601
* an array of the results of each invoked method. Any additional arguments
6602
* are provided to each invoked method. If `methodName` is a function it is
6603
* invoked for, and `this` bound to, each element in `collection`.
6604
*
6605
* @static
6606
* @memberOf _
6607
* @category Collection
6608
* @param {Array|Object|string} collection The collection to iterate over.
6609
* @param {Array|Function|string} path The path of the method to invoke or
6610
* the function invoked per iteration.
6611
* @param {...*} [args] The arguments to invoke the method with.
6612
* @returns {Array} Returns the array of results.
6613
* @example
6614
*
6615
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
6616
* // => [[1, 5, 7], [1, 2, 3]]
6617
*
6618
* _.invoke([123, 456], String.prototype.split, '');
6619
* // => [['1', '2', '3'], ['4', '5', '6']]
6620
*/
6621
var invoke = restParam(function(collection, path, args) {
6622
var index = -1,
6623
isFunc = typeof path == 'function',
6624
isProp = isKey(path),
6625
result = isArrayLike(collection) ? Array(collection.length) : [];
6626
6627
baseEach(collection, function(value) {
6628
var func = isFunc ? path : ((isProp && value != null) ? value[path] : null);
6629
result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
6630
});
6631
return result;
6632
});
6633
6634
/**
6635
* Creates an array of values by running each element in `collection` through
6636
* `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
6637
* arguments: (value, index|key, collection).
6638
*
6639
* If a property name is provided for `iteratee` the created `_.property`
6640
* style callback returns the property value of the given element.
6641
*
6642
* If a value is also provided for `thisArg` the created `_.matchesProperty`
6643
* style callback returns `true` for elements that have a matching property
6644
* value, else `false`.
6645
*
6646
* If an object is provided for `iteratee` the created `_.matches` style
6647
* callback returns `true` for elements that have the properties of the given
6648
* object, else `false`.
6649
*
6650
* Many lodash methods are guarded to work as iteratees for methods like
6651
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
6652
*
6653
* The guarded methods are:
6654
* `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
6655
* `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
6656
* `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
6657
* `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
6658
* `sum`, `uniq`, and `words`
6659
*
6660
* @static
6661
* @memberOf _
6662
* @alias collect
6663
* @category Collection
6664
* @param {Array|Object|string} collection The collection to iterate over.
6665
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
6666
* per iteration.
6667
* @param {*} [thisArg] The `this` binding of `iteratee`.
6668
* @returns {Array} Returns the new mapped array.
6669
* @example
6670
*
6671
* function timesThree(n) {
6672
* return n * 3;
6673
* }
6674
*
6675
* _.map([1, 2], timesThree);
6676
* // => [3, 6]
6677
*
6678
* _.map({ 'a': 1, 'b': 2 }, timesThree);
6679
* // => [3, 6] (iteration order is not guaranteed)
6680
*
6681
* var users = [
6682
* { 'user': 'barney' },
6683
* { 'user': 'fred' }
6684
* ];
6685
*
6686
* // using the `_.property` callback shorthand
6687
* _.map(users, 'user');
6688
* // => ['barney', 'fred']
6689
*/
6690
function map(collection, iteratee, thisArg) {
6691
var func = isArray(collection) ? arrayMap : baseMap;
6692
iteratee = getCallback(iteratee, thisArg, 3);
6693
return func(collection, iteratee);
6694
}
6695
6696
/**
6697
* Creates an array of elements split into two groups, the first of which
6698
* contains elements `predicate` returns truthy for, while the second of which
6699
* contains elements `predicate` returns falsey for. The predicate is bound
6700
* to `thisArg` and invoked with three arguments: (value, index|key, collection).
6701
*
6702
* If a property name is provided for `predicate` the created `_.property`
6703
* style callback returns the property value of the given element.
6704
*
6705
* If a value is also provided for `thisArg` the created `_.matchesProperty`
6706
* style callback returns `true` for elements that have a matching property
6707
* value, else `false`.
6708
*
6709
* If an object is provided for `predicate` the created `_.matches` style
6710
* callback returns `true` for elements that have the properties of the given
6711
* object, else `false`.
6712
*
6713
* @static
6714
* @memberOf _
6715
* @category Collection
6716
* @param {Array|Object|string} collection The collection to iterate over.
6717
* @param {Function|Object|string} [predicate=_.identity] The function invoked
6718
* per iteration.
6719
* @param {*} [thisArg] The `this` binding of `predicate`.
6720
* @returns {Array} Returns the array of grouped elements.
6721
* @example
6722
*
6723
* _.partition([1, 2, 3], function(n) {
6724
* return n % 2;
6725
* });
6726
* // => [[1, 3], [2]]
6727
*
6728
* _.partition([1.2, 2.3, 3.4], function(n) {
6729
* return this.floor(n) % 2;
6730
* }, Math);
6731
* // => [[1.2, 3.4], [2.3]]
6732
*
6733
* var users = [
6734
* { 'user': 'barney', 'age': 36, 'active': false },
6735
* { 'user': 'fred', 'age': 40, 'active': true },
6736
* { 'user': 'pebbles', 'age': 1, 'active': false }
6737
* ];
6738
*
6739
* var mapper = function(array) {
6740
* return _.pluck(array, 'user');
6741
* };
6742
*
6743
* // using the `_.matches` callback shorthand
6744
* _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
6745
* // => [['pebbles'], ['barney', 'fred']]
6746
*
6747
* // using the `_.matchesProperty` callback shorthand
6748
* _.map(_.partition(users, 'active', false), mapper);
6749
* // => [['barney', 'pebbles'], ['fred']]
6750
*
6751
* // using the `_.property` callback shorthand
6752
* _.map(_.partition(users, 'active'), mapper);
6753
* // => [['fred'], ['barney', 'pebbles']]
6754
*/
6755
var partition = createAggregator(function(result, value, key) {
6756
result[key ? 0 : 1].push(value);
6757
}, function() { return [[], []]; });
6758
6759
/**
6760
* Gets the property value of `path` from all elements in `collection`.
6761
*
6762
* @static
6763
* @memberOf _
6764
* @category Collection
6765
* @param {Array|Object|string} collection The collection to iterate over.
6766
* @param {Array|string} path The path of the property to pluck.
6767
* @returns {Array} Returns the property values.
6768
* @example
6769
*
6770
* var users = [
6771
* { 'user': 'barney', 'age': 36 },
6772
* { 'user': 'fred', 'age': 40 }
6773
* ];
6774
*
6775
* _.pluck(users, 'user');
6776
* // => ['barney', 'fred']
6777
*
6778
* var userIndex = _.indexBy(users, 'user');
6779
* _.pluck(userIndex, 'age');
6780
* // => [36, 40] (iteration order is not guaranteed)
6781
*/
6782
function pluck(collection, path) {
6783
return map(collection, property(path));
6784
}
6785
6786
/**
6787
* Reduces `collection` to a value which is the accumulated result of running
6788
* each element in `collection` through `iteratee`, where each successive
6789
* invocation is supplied the return value of the previous. If `accumulator`
6790
* is not provided the first element of `collection` is used as the initial
6791
* value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
6792
* (accumulator, value, index|key, collection).
6793
*
6794
* Many lodash methods are guarded to work as iteratees for methods like
6795
* `_.reduce`, `_.reduceRight`, and `_.transform`.
6796
*
6797
* The guarded methods are:
6798
* `assign`, `defaults`, `includes`, `merge`, `sortByAll`, and `sortByOrder`
6799
*
6800
* @static
6801
* @memberOf _
6802
* @alias foldl, inject
6803
* @category Collection
6804
* @param {Array|Object|string} collection The collection to iterate over.
6805
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
6806
* @param {*} [accumulator] The initial value.
6807
* @param {*} [thisArg] The `this` binding of `iteratee`.
6808
* @returns {*} Returns the accumulated value.
6809
* @example
6810
*
6811
* _.reduce([1, 2], function(total, n) {
6812
* return total + n;
6813
* });
6814
* // => 3
6815
*
6816
* _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
6817
* result[key] = n * 3;
6818
* return result;
6819
* }, {});
6820
* // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
6821
*/
6822
var reduce = createReduce(arrayReduce, baseEach);
6823
6824
/**
6825
* This method is like `_.reduce` except that it iterates over elements of
6826
* `collection` from right to left.
6827
*
6828
* @static
6829
* @memberOf _
6830
* @alias foldr
6831
* @category Collection
6832
* @param {Array|Object|string} collection The collection to iterate over.
6833
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
6834
* @param {*} [accumulator] The initial value.
6835
* @param {*} [thisArg] The `this` binding of `iteratee`.
6836
* @returns {*} Returns the accumulated value.
6837
* @example
6838
*
6839
* var array = [[0, 1], [2, 3], [4, 5]];
6840
*
6841
* _.reduceRight(array, function(flattened, other) {
6842
* return flattened.concat(other);
6843
* }, []);
6844
* // => [4, 5, 2, 3, 0, 1]
6845
*/
6846
var reduceRight = createReduce(arrayReduceRight, baseEachRight);
6847
6848
/**
6849
* The opposite of `_.filter`; this method returns the elements of `collection`
6850
* that `predicate` does **not** return truthy for.
6851
*
6852
* @static
6853
* @memberOf _
6854
* @category Collection
6855
* @param {Array|Object|string} collection The collection to iterate over.
6856
* @param {Function|Object|string} [predicate=_.identity] The function invoked
6857
* per iteration.
6858
* @param {*} [thisArg] The `this` binding of `predicate`.
6859
* @returns {Array} Returns the new filtered array.
6860
* @example
6861
*
6862
* _.reject([1, 2, 3, 4], function(n) {
6863
* return n % 2 == 0;
6864
* });
6865
* // => [1, 3]
6866
*
6867
* var users = [
6868
* { 'user': 'barney', 'age': 36, 'active': false },
6869
* { 'user': 'fred', 'age': 40, 'active': true }
6870
* ];
6871
*
6872
* // using the `_.matches` callback shorthand
6873
* _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
6874
* // => ['barney']
6875
*
6876
* // using the `_.matchesProperty` callback shorthand
6877
* _.pluck(_.reject(users, 'active', false), 'user');
6878
* // => ['fred']
6879
*
6880
* // using the `_.property` callback shorthand
6881
* _.pluck(_.reject(users, 'active'), 'user');
6882
* // => ['barney']
6883
*/
6884
function reject(collection, predicate, thisArg) {
6885
var func = isArray(collection) ? arrayFilter : baseFilter;
6886
predicate = getCallback(predicate, thisArg, 3);
6887
return func(collection, function(value, index, collection) {
6888
return !predicate(value, index, collection);
6889
});
6890
}
6891
6892
/**
6893
* Gets a random element or `n` random elements from a collection.
6894
*
6895
* @static
6896
* @memberOf _
6897
* @category Collection
6898
* @param {Array|Object|string} collection The collection to sample.
6899
* @param {number} [n] The number of elements to sample.
6900
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
6901
* @returns {*} Returns the random sample(s).
6902
* @example
6903
*
6904
* _.sample([1, 2, 3, 4]);
6905
* // => 2
6906
*
6907
* _.sample([1, 2, 3, 4], 2);
6908
* // => [3, 1]
6909
*/
6910
function sample(collection, n, guard) {
6911
if (guard ? isIterateeCall(collection, n, guard) : n == null) {
6912
collection = toIterable(collection);
6913
var length = collection.length;
6914
return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
6915
}
6916
var index = -1,
6917
result = toArray(collection),
6918
length = result.length,
6919
lastIndex = length - 1;
6920
6921
n = nativeMin(n < 0 ? 0 : (+n || 0), length);
6922
while (++index < n) {
6923
var rand = baseRandom(index, lastIndex),
6924
value = result[rand];
6925
6926
result[rand] = result[index];
6927
result[index] = value;
6928
}
6929
result.length = n;
6930
return result;
6931
}
6932
6933
/**
6934
* Creates an array of shuffled values, using a version of the
6935
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
6936
*
6937
* @static
6938
* @memberOf _
6939
* @category Collection
6940
* @param {Array|Object|string} collection The collection to shuffle.
6941
* @returns {Array} Returns the new shuffled array.
6942
* @example
6943
*
6944
* _.shuffle([1, 2, 3, 4]);
6945
* // => [4, 1, 3, 2]
6946
*/
6947
function shuffle(collection) {
6948
return sample(collection, POSITIVE_INFINITY);
6949
}
6950
6951
/**
6952
* Gets the size of `collection` by returning its length for array-like
6953
* values or the number of own enumerable properties for objects.
6954
*
6955
* @static
6956
* @memberOf _
6957
* @category Collection
6958
* @param {Array|Object|string} collection The collection to inspect.
6959
* @returns {number} Returns the size of `collection`.
6960
* @example
6961
*
6962
* _.size([1, 2, 3]);
6963
* // => 3
6964
*
6965
* _.size({ 'a': 1, 'b': 2 });
6966
* // => 2
6967
*
6968
* _.size('pebbles');
6969
* // => 7
6970
*/
6971
function size(collection) {
6972
var length = collection ? getLength(collection) : 0;
6973
return isLength(length) ? length : keys(collection).length;
6974
}
6975
6976
/**
6977
* Checks if `predicate` returns truthy for **any** element of `collection`.
6978
* The function returns as soon as it finds a passing value and does not iterate
6979
* over the entire collection. The predicate is bound to `thisArg` and invoked
6980
* with three arguments: (value, index|key, collection).
6981
*
6982
* If a property name is provided for `predicate` the created `_.property`
6983
* style callback returns the property value of the given element.
6984
*
6985
* If a value is also provided for `thisArg` the created `_.matchesProperty`
6986
* style callback returns `true` for elements that have a matching property
6987
* value, else `false`.
6988
*
6989
* If an object is provided for `predicate` the created `_.matches` style
6990
* callback returns `true` for elements that have the properties of the given
6991
* object, else `false`.
6992
*
6993
* @static
6994
* @memberOf _
6995
* @alias any
6996
* @category Collection
6997
* @param {Array|Object|string} collection The collection to iterate over.
6998
* @param {Function|Object|string} [predicate=_.identity] The function invoked
6999
* per iteration.
7000
* @param {*} [thisArg] The `this` binding of `predicate`.
7001
* @returns {boolean} Returns `true` if any element passes the predicate check,
7002
* else `false`.
7003
* @example
7004
*
7005
* _.some([null, 0, 'yes', false], Boolean);
7006
* // => true
7007
*
7008
* var users = [
7009
* { 'user': 'barney', 'active': true },
7010
* { 'user': 'fred', 'active': false }
7011
* ];
7012
*
7013
* // using the `_.matches` callback shorthand
7014
* _.some(users, { 'user': 'barney', 'active': false });
7015
* // => false
7016
*
7017
* // using the `_.matchesProperty` callback shorthand
7018
* _.some(users, 'active', false);
7019
* // => true
7020
*
7021
* // using the `_.property` callback shorthand
7022
* _.some(users, 'active');
7023
* // => true
7024
*/
7025
function some(collection, predicate, thisArg) {
7026
var func = isArray(collection) ? arraySome : baseSome;
7027
if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
7028
predicate = null;
7029
}
7030
if (typeof predicate != 'function' || thisArg !== undefined) {
7031
predicate = getCallback(predicate, thisArg, 3);
7032
}
7033
return func(collection, predicate);
7034
}
7035
7036
/**
7037
* Creates an array of elements, sorted in ascending order by the results of
7038
* running each element in a collection through `iteratee`. This method performs
7039
* a stable sort, that is, it preserves the original sort order of equal elements.
7040
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
7041
* (value, index|key, collection).
7042
*
7043
* If a property name is provided for `iteratee` the created `_.property`
7044
* style callback returns the property value of the given element.
7045
*
7046
* If a value is also provided for `thisArg` the created `_.matchesProperty`
7047
* style callback returns `true` for elements that have a matching property
7048
* value, else `false`.
7049
*
7050
* If an object is provided for `iteratee` the created `_.matches` style
7051
* callback returns `true` for elements that have the properties of the given
7052
* object, else `false`.
7053
*
7054
* @static
7055
* @memberOf _
7056
* @category Collection
7057
* @param {Array|Object|string} collection The collection to iterate over.
7058
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
7059
* per iteration.
7060
* @param {*} [thisArg] The `this` binding of `iteratee`.
7061
* @returns {Array} Returns the new sorted array.
7062
* @example
7063
*
7064
* _.sortBy([1, 2, 3], function(n) {
7065
* return Math.sin(n);
7066
* });
7067
* // => [3, 1, 2]
7068
*
7069
* _.sortBy([1, 2, 3], function(n) {
7070
* return this.sin(n);
7071
* }, Math);
7072
* // => [3, 1, 2]
7073
*
7074
* var users = [
7075
* { 'user': 'fred' },
7076
* { 'user': 'pebbles' },
7077
* { 'user': 'barney' }
7078
* ];
7079
*
7080
* // using the `_.property` callback shorthand
7081
* _.pluck(_.sortBy(users, 'user'), 'user');
7082
* // => ['barney', 'fred', 'pebbles']
7083
*/
7084
function sortBy(collection, iteratee, thisArg) {
7085
if (collection == null) {
7086
return [];
7087
}
7088
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
7089
iteratee = null;
7090
}
7091
var index = -1;
7092
iteratee = getCallback(iteratee, thisArg, 3);
7093
7094
var result = baseMap(collection, function(value, key, collection) {
7095
return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
7096
});
7097
return baseSortBy(result, compareAscending);
7098
}
7099
7100
/**
7101
* This method is like `_.sortBy` except that it can sort by multiple iteratees
7102
* or property names.
7103
*
7104
* If a property name is provided for an iteratee the created `_.property`
7105
* style callback returns the property value of the given element.
7106
*
7107
* If an object is provided for an iteratee the created `_.matches` style
7108
* callback returns `true` for elements that have the properties of the given
7109
* object, else `false`.
7110
*
7111
* @static
7112
* @memberOf _
7113
* @category Collection
7114
* @param {Array|Object|string} collection The collection to iterate over.
7115
* @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
7116
* The iteratees to sort by, specified as individual values or arrays of values.
7117
* @returns {Array} Returns the new sorted array.
7118
* @example
7119
*
7120
* var users = [
7121
* { 'user': 'fred', 'age': 48 },
7122
* { 'user': 'barney', 'age': 36 },
7123
* { 'user': 'fred', 'age': 42 },
7124
* { 'user': 'barney', 'age': 34 }
7125
* ];
7126
*
7127
* _.map(_.sortByAll(users, ['user', 'age']), _.values);
7128
* // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
7129
*
7130
* _.map(_.sortByAll(users, 'user', function(chr) {
7131
* return Math.floor(chr.age / 10);
7132
* }), _.values);
7133
* // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
7134
*/
7135
var sortByAll = restParam(function(collection, iteratees) {
7136
if (collection == null) {
7137
return [];
7138
}
7139
var guard = iteratees[2];
7140
if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
7141
iteratees.length = 1;
7142
}
7143
return baseSortByOrder(collection, baseFlatten(iteratees), []);
7144
});
7145
7146
/**
7147
* This method is like `_.sortByAll` except that it allows specifying the
7148
* sort orders of the iteratees to sort by. A truthy value in `orders` will
7149
* sort the corresponding property name in ascending order while a falsey
7150
* value will sort it in descending order.
7151
*
7152
* If a property name is provided for an iteratee the created `_.property`
7153
* style callback returns the property value of the given element.
7154
*
7155
* If an object is provided for an iteratee the created `_.matches` style
7156
* callback returns `true` for elements that have the properties of the given
7157
* object, else `false`.
7158
*
7159
* @static
7160
* @memberOf _
7161
* @category Collection
7162
* @param {Array|Object|string} collection The collection to iterate over.
7163
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
7164
* @param {boolean[]} orders The sort orders of `iteratees`.
7165
* @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
7166
* @returns {Array} Returns the new sorted array.
7167
* @example
7168
*
7169
* var users = [
7170
* { 'user': 'fred', 'age': 48 },
7171
* { 'user': 'barney', 'age': 34 },
7172
* { 'user': 'fred', 'age': 42 },
7173
* { 'user': 'barney', 'age': 36 }
7174
* ];
7175
*
7176
* // sort by `user` in ascending order and by `age` in descending order
7177
* _.map(_.sortByOrder(users, ['user', 'age'], [true, false]), _.values);
7178
* // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
7179
*/
7180
function sortByOrder(collection, iteratees, orders, guard) {
7181
if (collection == null) {
7182
return [];
7183
}
7184
if (guard && isIterateeCall(iteratees, orders, guard)) {
7185
orders = null;
7186
}
7187
if (!isArray(iteratees)) {
7188
iteratees = iteratees == null ? [] : [iteratees];
7189
}
7190
if (!isArray(orders)) {
7191
orders = orders == null ? [] : [orders];
7192
}
7193
return baseSortByOrder(collection, iteratees, orders);
7194
}
7195
7196
/**
7197
* Performs a deep comparison between each element in `collection` and the
7198
* source object, returning an array of all elements that have equivalent
7199
* property values.
7200
*
7201
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
7202
* numbers, `Object` objects, regexes, and strings. Objects are compared by
7203
* their own, not inherited, enumerable properties. For comparing a single
7204
* own or inherited property value see `_.matchesProperty`.
7205
*
7206
* @static
7207
* @memberOf _
7208
* @category Collection
7209
* @param {Array|Object|string} collection The collection to search.
7210
* @param {Object} source The object of property values to match.
7211
* @returns {Array} Returns the new filtered array.
7212
* @example
7213
*
7214
* var users = [
7215
* { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
7216
* { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
7217
* ];
7218
*
7219
* _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
7220
* // => ['barney']
7221
*
7222
* _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
7223
* // => ['fred']
7224
*/
7225
function where(collection, source) {
7226
return filter(collection, baseMatches(source));
7227
}
7228
7229
/*------------------------------------------------------------------------*/
7230
7231
/**
7232
* Gets the number of milliseconds that have elapsed since the Unix epoch
7233
* (1 January 1970 00:00:00 UTC).
7234
*
7235
* @static
7236
* @memberOf _
7237
* @category Date
7238
* @example
7239
*
7240
* _.defer(function(stamp) {
7241
* console.log(_.now() - stamp);
7242
* }, _.now());
7243
* // => logs the number of milliseconds it took for the deferred function to be invoked
7244
*/
7245
var now = nativeNow || function() {
7246
return new Date().getTime();
7247
};
7248
7249
/*------------------------------------------------------------------------*/
7250
7251
/**
7252
* The opposite of `_.before`; this method creates a function that invokes
7253
* `func` once it is called `n` or more times.
7254
*
7255
* @static
7256
* @memberOf _
7257
* @category Function
7258
* @param {number} n The number of calls before `func` is invoked.
7259
* @param {Function} func The function to restrict.
7260
* @returns {Function} Returns the new restricted function.
7261
* @example
7262
*
7263
* var saves = ['profile', 'settings'];
7264
*
7265
* var done = _.after(saves.length, function() {
7266
* console.log('done saving!');
7267
* });
7268
*
7269
* _.forEach(saves, function(type) {
7270
* asyncSave({ 'type': type, 'complete': done });
7271
* });
7272
* // => logs 'done saving!' after the two async saves have completed
7273
*/
7274
function after(n, func) {
7275
if (typeof func != 'function') {
7276
if (typeof n == 'function') {
7277
var temp = n;
7278
n = func;
7279
func = temp;
7280
} else {
7281
throw new TypeError(FUNC_ERROR_TEXT);
7282
}
7283
}
7284
n = nativeIsFinite(n = +n) ? n : 0;
7285
return function() {
7286
if (--n < 1) {
7287
return func.apply(this, arguments);
7288
}
7289
};
7290
}
7291
7292
/**
7293
* Creates a function that accepts up to `n` arguments ignoring any
7294
* additional arguments.
7295
*
7296
* @static
7297
* @memberOf _
7298
* @category Function
7299
* @param {Function} func The function to cap arguments for.
7300
* @param {number} [n=func.length] The arity cap.
7301
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
7302
* @returns {Function} Returns the new function.
7303
* @example
7304
*
7305
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
7306
* // => [6, 8, 10]
7307
*/
7308
function ary(func, n, guard) {
7309
if (guard && isIterateeCall(func, n, guard)) {
7310
n = null;
7311
}
7312
n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
7313
return createWrapper(func, ARY_FLAG, null, null, null, null, n);
7314
}
7315
7316
/**
7317
* Creates a function that invokes `func`, with the `this` binding and arguments
7318
* of the created function, while it is called less than `n` times. Subsequent
7319
* calls to the created function return the result of the last `func` invocation.
7320
*
7321
* @static
7322
* @memberOf _
7323
* @category Function
7324
* @param {number} n The number of calls at which `func` is no longer invoked.
7325
* @param {Function} func The function to restrict.
7326
* @returns {Function} Returns the new restricted function.
7327
* @example
7328
*
7329
* jQuery('#add').on('click', _.before(5, addContactToList));
7330
* // => allows adding up to 4 contacts to the list
7331
*/
7332
function before(n, func) {
7333
var result;
7334
if (typeof func != 'function') {
7335
if (typeof n == 'function') {
7336
var temp = n;
7337
n = func;
7338
func = temp;
7339
} else {
7340
throw new TypeError(FUNC_ERROR_TEXT);
7341
}
7342
}
7343
return function() {
7344
if (--n > 0) {
7345
result = func.apply(this, arguments);
7346
}
7347
if (n <= 1) {
7348
func = null;
7349
}
7350
return result;
7351
};
7352
}
7353
7354
/**
7355
* Creates a function that invokes `func` with the `this` binding of `thisArg`
7356
* and prepends any additional `_.bind` arguments to those provided to the
7357
* bound function.
7358
*
7359
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
7360
* may be used as a placeholder for partially applied arguments.
7361
*
7362
* **Note:** Unlike native `Function#bind` this method does not set the "length"
7363
* property of bound functions.
7364
*
7365
* @static
7366
* @memberOf _
7367
* @category Function
7368
* @param {Function} func The function to bind.
7369
* @param {*} thisArg The `this` binding of `func`.
7370
* @param {...*} [partials] The arguments to be partially applied.
7371
* @returns {Function} Returns the new bound function.
7372
* @example
7373
*
7374
* var greet = function(greeting, punctuation) {
7375
* return greeting + ' ' + this.user + punctuation;
7376
* };
7377
*
7378
* var object = { 'user': 'fred' };
7379
*
7380
* var bound = _.bind(greet, object, 'hi');
7381
* bound('!');
7382
* // => 'hi fred!'
7383
*
7384
* // using placeholders
7385
* var bound = _.bind(greet, object, _, '!');
7386
* bound('hi');
7387
* // => 'hi fred!'
7388
*/
7389
var bind = restParam(function(func, thisArg, partials) {
7390
var bitmask = BIND_FLAG;
7391
if (partials.length) {
7392
var holders = replaceHolders(partials, bind.placeholder);
7393
bitmask |= PARTIAL_FLAG;
7394
}
7395
return createWrapper(func, bitmask, thisArg, partials, holders);
7396
});
7397
7398
/**
7399
* Binds methods of an object to the object itself, overwriting the existing
7400
* method. Method names may be specified as individual arguments or as arrays
7401
* of method names. If no method names are provided all enumerable function
7402
* properties, own and inherited, of `object` are bound.
7403
*
7404
* **Note:** This method does not set the "length" property of bound functions.
7405
*
7406
* @static
7407
* @memberOf _
7408
* @category Function
7409
* @param {Object} object The object to bind and assign the bound methods to.
7410
* @param {...(string|string[])} [methodNames] The object method names to bind,
7411
* specified as individual method names or arrays of method names.
7412
* @returns {Object} Returns `object`.
7413
* @example
7414
*
7415
* var view = {
7416
* 'label': 'docs',
7417
* 'onClick': function() {
7418
* console.log('clicked ' + this.label);
7419
* }
7420
* };
7421
*
7422
* _.bindAll(view);
7423
* jQuery('#docs').on('click', view.onClick);
7424
* // => logs 'clicked docs' when the element is clicked
7425
*/
7426
var bindAll = restParam(function(object, methodNames) {
7427
methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
7428
7429
var index = -1,
7430
length = methodNames.length;
7431
7432
while (++index < length) {
7433
var key = methodNames[index];
7434
object[key] = createWrapper(object[key], BIND_FLAG, object);
7435
}
7436
return object;
7437
});
7438
7439
/**
7440
* Creates a function that invokes the method at `object[key]` and prepends
7441
* any additional `_.bindKey` arguments to those provided to the bound function.
7442
*
7443
* This method differs from `_.bind` by allowing bound functions to reference
7444
* methods that may be redefined or don't yet exist.
7445
* See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
7446
* for more details.
7447
*
7448
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
7449
* builds, may be used as a placeholder for partially applied arguments.
7450
*
7451
* @static
7452
* @memberOf _
7453
* @category Function
7454
* @param {Object} object The object the method belongs to.
7455
* @param {string} key The key of the method.
7456
* @param {...*} [partials] The arguments to be partially applied.
7457
* @returns {Function} Returns the new bound function.
7458
* @example
7459
*
7460
* var object = {
7461
* 'user': 'fred',
7462
* 'greet': function(greeting, punctuation) {
7463
* return greeting + ' ' + this.user + punctuation;
7464
* }
7465
* };
7466
*
7467
* var bound = _.bindKey(object, 'greet', 'hi');
7468
* bound('!');
7469
* // => 'hi fred!'
7470
*
7471
* object.greet = function(greeting, punctuation) {
7472
* return greeting + 'ya ' + this.user + punctuation;
7473
* };
7474
*
7475
* bound('!');
7476
* // => 'hiya fred!'
7477
*
7478
* // using placeholders
7479
* var bound = _.bindKey(object, 'greet', _, '!');
7480
* bound('hi');
7481
* // => 'hiya fred!'
7482
*/
7483
var bindKey = restParam(function(object, key, partials) {
7484
var bitmask = BIND_FLAG | BIND_KEY_FLAG;
7485
if (partials.length) {
7486
var holders = replaceHolders(partials, bindKey.placeholder);
7487
bitmask |= PARTIAL_FLAG;
7488
}
7489
return createWrapper(key, bitmask, object, partials, holders);
7490
});
7491
7492
/**
7493
* Creates a function that accepts one or more arguments of `func` that when
7494
* called either invokes `func` returning its result, if all `func` arguments
7495
* have been provided, or returns a function that accepts one or more of the
7496
* remaining `func` arguments, and so on. The arity of `func` may be specified
7497
* if `func.length` is not sufficient.
7498
*
7499
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
7500
* may be used as a placeholder for provided arguments.
7501
*
7502
* **Note:** This method does not set the "length" property of curried functions.
7503
*
7504
* @static
7505
* @memberOf _
7506
* @category Function
7507
* @param {Function} func The function to curry.
7508
* @param {number} [arity=func.length] The arity of `func`.
7509
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
7510
* @returns {Function} Returns the new curried function.
7511
* @example
7512
*
7513
* var abc = function(a, b, c) {
7514
* return [a, b, c];
7515
* };
7516
*
7517
* var curried = _.curry(abc);
7518
*
7519
* curried(1)(2)(3);
7520
* // => [1, 2, 3]
7521
*
7522
* curried(1, 2)(3);
7523
* // => [1, 2, 3]
7524
*
7525
* curried(1, 2, 3);
7526
* // => [1, 2, 3]
7527
*
7528
* // using placeholders
7529
* curried(1)(_, 3)(2);
7530
* // => [1, 2, 3]
7531
*/
7532
var curry = createCurry(CURRY_FLAG);
7533
7534
/**
7535
* This method is like `_.curry` except that arguments are applied to `func`
7536
* in the manner of `_.partialRight` instead of `_.partial`.
7537
*
7538
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
7539
* builds, may be used as a placeholder for provided arguments.
7540
*
7541
* **Note:** This method does not set the "length" property of curried functions.
7542
*
7543
* @static
7544
* @memberOf _
7545
* @category Function
7546
* @param {Function} func The function to curry.
7547
* @param {number} [arity=func.length] The arity of `func`.
7548
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
7549
* @returns {Function} Returns the new curried function.
7550
* @example
7551
*
7552
* var abc = function(a, b, c) {
7553
* return [a, b, c];
7554
* };
7555
*
7556
* var curried = _.curryRight(abc);
7557
*
7558
* curried(3)(2)(1);
7559
* // => [1, 2, 3]
7560
*
7561
* curried(2, 3)(1);
7562
* // => [1, 2, 3]
7563
*
7564
* curried(1, 2, 3);
7565
* // => [1, 2, 3]
7566
*
7567
* // using placeholders
7568
* curried(3)(1, _)(2);
7569
* // => [1, 2, 3]
7570
*/
7571
var curryRight = createCurry(CURRY_RIGHT_FLAG);
7572
7573
/**
7574
* Creates a debounced function that delays invoking `func` until after `wait`
7575
* milliseconds have elapsed since the last time the debounced function was
7576
* invoked. The debounced function comes with a `cancel` method to cancel
7577
* delayed invocations. Provide an options object to indicate that `func`
7578
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
7579
* Subsequent calls to the debounced function return the result of the last
7580
* `func` invocation.
7581
*
7582
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
7583
* on the trailing edge of the timeout only if the the debounced function is
7584
* invoked more than once during the `wait` timeout.
7585
*
7586
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
7587
* for details over the differences between `_.debounce` and `_.throttle`.
7588
*
7589
* @static
7590
* @memberOf _
7591
* @category Function
7592
* @param {Function} func The function to debounce.
7593
* @param {number} [wait=0] The number of milliseconds to delay.
7594
* @param {Object} [options] The options object.
7595
* @param {boolean} [options.leading=false] Specify invoking on the leading
7596
* edge of the timeout.
7597
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
7598
* delayed before it is invoked.
7599
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
7600
* edge of the timeout.
7601
* @returns {Function} Returns the new debounced function.
7602
* @example
7603
*
7604
* // avoid costly calculations while the window size is in flux
7605
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
7606
*
7607
* // invoke `sendMail` when the click event is fired, debouncing subsequent calls
7608
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
7609
* 'leading': true,
7610
* 'trailing': false
7611
* }));
7612
*
7613
* // ensure `batchLog` is invoked once after 1 second of debounced calls
7614
* var source = new EventSource('/stream');
7615
* jQuery(source).on('message', _.debounce(batchLog, 250, {
7616
* 'maxWait': 1000
7617
* }));
7618
*
7619
* // cancel a debounced call
7620
* var todoChanges = _.debounce(batchLog, 1000);
7621
* Object.observe(models.todo, todoChanges);
7622
*
7623
* Object.observe(models, function(changes) {
7624
* if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
7625
* todoChanges.cancel();
7626
* }
7627
* }, ['delete']);
7628
*
7629
* // ...at some point `models.todo` is changed
7630
* models.todo.completed = true;
7631
*
7632
* // ...before 1 second has passed `models.todo` is deleted
7633
* // which cancels the debounced `todoChanges` call
7634
* delete models.todo;
7635
*/
7636
function debounce(func, wait, options) {
7637
var args,
7638
maxTimeoutId,
7639
result,
7640
stamp,
7641
thisArg,
7642
timeoutId,
7643
trailingCall,
7644
lastCalled = 0,
7645
maxWait = false,
7646
trailing = true;
7647
7648
if (typeof func != 'function') {
7649
throw new TypeError(FUNC_ERROR_TEXT);
7650
}
7651
wait = wait < 0 ? 0 : (+wait || 0);
7652
if (options === true) {
7653
var leading = true;
7654
trailing = false;
7655
} else if (isObject(options)) {
7656
leading = options.leading;
7657
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
7658
trailing = 'trailing' in options ? options.trailing : trailing;
7659
}
7660
7661
function cancel() {
7662
if (timeoutId) {
7663
clearTimeout(timeoutId);
7664
}
7665
if (maxTimeoutId) {
7666
clearTimeout(maxTimeoutId);
7667
}
7668
maxTimeoutId = timeoutId = trailingCall = undefined;
7669
}
7670
7671
function delayed() {
7672
var remaining = wait - (now() - stamp);
7673
if (remaining <= 0 || remaining > wait) {
7674
if (maxTimeoutId) {
7675
clearTimeout(maxTimeoutId);
7676
}
7677
var isCalled = trailingCall;
7678
maxTimeoutId = timeoutId = trailingCall = undefined;
7679
if (isCalled) {
7680
lastCalled = now();
7681
result = func.apply(thisArg, args);
7682
if (!timeoutId && !maxTimeoutId) {
7683
args = thisArg = null;
7684
}
7685
}
7686
} else {
7687
timeoutId = setTimeout(delayed, remaining);
7688
}
7689
}
7690
7691
function maxDelayed() {
7692
if (timeoutId) {
7693
clearTimeout(timeoutId);
7694
}
7695
maxTimeoutId = timeoutId = trailingCall = undefined;
7696
if (trailing || (maxWait !== wait)) {
7697
lastCalled = now();
7698
result = func.apply(thisArg, args);
7699
if (!timeoutId && !maxTimeoutId) {
7700
args = thisArg = null;
7701
}
7702
}
7703
}
7704
7705
function debounced() {
7706
args = arguments;
7707
stamp = now();
7708
thisArg = this;
7709
trailingCall = trailing && (timeoutId || !leading);
7710
7711
if (maxWait === false) {
7712
var leadingCall = leading && !timeoutId;
7713
} else {
7714
if (!maxTimeoutId && !leading) {
7715
lastCalled = stamp;
7716
}
7717
var remaining = maxWait - (stamp - lastCalled),
7718
isCalled = remaining <= 0 || remaining > maxWait;
7719
7720
if (isCalled) {
7721
if (maxTimeoutId) {
7722
maxTimeoutId = clearTimeout(maxTimeoutId);
7723
}
7724
lastCalled = stamp;
7725
result = func.apply(thisArg, args);
7726
}
7727
else if (!maxTimeoutId) {
7728
maxTimeoutId = setTimeout(maxDelayed, remaining);
7729
}
7730
}
7731
if (isCalled && timeoutId) {
7732
timeoutId = clearTimeout(timeoutId);
7733
}
7734
else if (!timeoutId && wait !== maxWait) {
7735
timeoutId = setTimeout(delayed, wait);
7736
}
7737
if (leadingCall) {
7738
isCalled = true;
7739
result = func.apply(thisArg, args);
7740
}
7741
if (isCalled && !timeoutId && !maxTimeoutId) {
7742
args = thisArg = null;
7743
}
7744
return result;
7745
}
7746
debounced.cancel = cancel;
7747
return debounced;
7748
}
7749
7750
/**
7751
* Defers invoking the `func` until the current call stack has cleared. Any
7752
* additional arguments are provided to `func` when it is invoked.
7753
*
7754
* @static
7755
* @memberOf _
7756
* @category Function
7757
* @param {Function} func The function to defer.
7758
* @param {...*} [args] The arguments to invoke the function with.
7759
* @returns {number} Returns the timer id.
7760
* @example
7761
*
7762
* _.defer(function(text) {
7763
* console.log(text);
7764
* }, 'deferred');
7765
* // logs 'deferred' after one or more milliseconds
7766
*/
7767
var defer = restParam(function(func, args) {
7768
return baseDelay(func, 1, args);
7769
});
7770
7771
/**
7772
* Invokes `func` after `wait` milliseconds. Any additional arguments are
7773
* provided to `func` when it is invoked.
7774
*
7775
* @static
7776
* @memberOf _
7777
* @category Function
7778
* @param {Function} func The function to delay.
7779
* @param {number} wait The number of milliseconds to delay invocation.
7780
* @param {...*} [args] The arguments to invoke the function with.
7781
* @returns {number} Returns the timer id.
7782
* @example
7783
*
7784
* _.delay(function(text) {
7785
* console.log(text);
7786
* }, 1000, 'later');
7787
* // => logs 'later' after one second
7788
*/
7789
var delay = restParam(function(func, wait, args) {
7790
return baseDelay(func, wait, args);
7791
});
7792
7793
/**
7794
* Creates a function that returns the result of invoking the provided
7795
* functions with the `this` binding of the created function, where each
7796
* successive invocation is supplied the return value of the previous.
7797
*
7798
* @static
7799
* @memberOf _
7800
* @category Function
7801
* @param {...Function} [funcs] Functions to invoke.
7802
* @returns {Function} Returns the new function.
7803
* @example
7804
*
7805
* function square(n) {
7806
* return n * n;
7807
* }
7808
*
7809
* var addSquare = _.flow(_.add, square);
7810
* addSquare(1, 2);
7811
* // => 9
7812
*/
7813
var flow = createFlow();
7814
7815
/**
7816
* This method is like `_.flow` except that it creates a function that
7817
* invokes the provided functions from right to left.
7818
*
7819
* @static
7820
* @memberOf _
7821
* @alias backflow, compose
7822
* @category Function
7823
* @param {...Function} [funcs] Functions to invoke.
7824
* @returns {Function} Returns the new function.
7825
* @example
7826
*
7827
* function square(n) {
7828
* return n * n;
7829
* }
7830
*
7831
* var addSquare = _.flowRight(square, _.add);
7832
* addSquare(1, 2);
7833
* // => 9
7834
*/
7835
var flowRight = createFlow(true);
7836
7837
/**
7838
* Creates a function that memoizes the result of `func`. If `resolver` is
7839
* provided it determines the cache key for storing the result based on the
7840
* arguments provided to the memoized function. By default, the first argument
7841
* provided to the memoized function is coerced to a string and used as the
7842
* cache key. The `func` is invoked with the `this` binding of the memoized
7843
* function.
7844
*
7845
* **Note:** The cache is exposed as the `cache` property on the memoized
7846
* function. Its creation may be customized by replacing the `_.memoize.Cache`
7847
* constructor with one whose instances implement the [`Map`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object)
7848
* method interface of `get`, `has`, and `set`.
7849
*
7850
* @static
7851
* @memberOf _
7852
* @category Function
7853
* @param {Function} func The function to have its output memoized.
7854
* @param {Function} [resolver] The function to resolve the cache key.
7855
* @returns {Function} Returns the new memoizing function.
7856
* @example
7857
*
7858
* var upperCase = _.memoize(function(string) {
7859
* return string.toUpperCase();
7860
* });
7861
*
7862
* upperCase('fred');
7863
* // => 'FRED'
7864
*
7865
* // modifying the result cache
7866
* upperCase.cache.set('fred', 'BARNEY');
7867
* upperCase('fred');
7868
* // => 'BARNEY'
7869
*
7870
* // replacing `_.memoize.Cache`
7871
* var object = { 'user': 'fred' };
7872
* var other = { 'user': 'barney' };
7873
* var identity = _.memoize(_.identity);
7874
*
7875
* identity(object);
7876
* // => { 'user': 'fred' }
7877
* identity(other);
7878
* // => { 'user': 'fred' }
7879
*
7880
* _.memoize.Cache = WeakMap;
7881
* var identity = _.memoize(_.identity);
7882
*
7883
* identity(object);
7884
* // => { 'user': 'fred' }
7885
* identity(other);
7886
* // => { 'user': 'barney' }
7887
*/
7888
function memoize(func, resolver) {
7889
if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
7890
throw new TypeError(FUNC_ERROR_TEXT);
7891
}
7892
var memoized = function() {
7893
var args = arguments,
7894
key = resolver ? resolver.apply(this, args) : args[0],
7895
cache = memoized.cache;
7896
7897
if (cache.has(key)) {
7898
return cache.get(key);
7899
}
7900
var result = func.apply(this, args);
7901
memoized.cache = cache.set(key, result);
7902
return result;
7903
};
7904
memoized.cache = new memoize.Cache;
7905
return memoized;
7906
}
7907
7908
/**
7909
* Creates a function that negates the result of the predicate `func`. The
7910
* `func` predicate is invoked with the `this` binding and arguments of the
7911
* created function.
7912
*
7913
* @static
7914
* @memberOf _
7915
* @category Function
7916
* @param {Function} predicate The predicate to negate.
7917
* @returns {Function} Returns the new function.
7918
* @example
7919
*
7920
* function isEven(n) {
7921
* return n % 2 == 0;
7922
* }
7923
*
7924
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
7925
* // => [1, 3, 5]
7926
*/
7927
function negate(predicate) {
7928
if (typeof predicate != 'function') {
7929
throw new TypeError(FUNC_ERROR_TEXT);
7930
}
7931
return function() {
7932
return !predicate.apply(this, arguments);
7933
};
7934
}
7935
7936
/**
7937
* Creates a function that is restricted to invoking `func` once. Repeat calls
7938
* to the function return the value of the first call. The `func` is invoked
7939
* with the `this` binding and arguments of the created function.
7940
*
7941
* @static
7942
* @memberOf _
7943
* @category Function
7944
* @param {Function} func The function to restrict.
7945
* @returns {Function} Returns the new restricted function.
7946
* @example
7947
*
7948
* var initialize = _.once(createApplication);
7949
* initialize();
7950
* initialize();
7951
* // `initialize` invokes `createApplication` once
7952
*/
7953
function once(func) {
7954
return before(2, func);
7955
}
7956
7957
/**
7958
* Creates a function that invokes `func` with `partial` arguments prepended
7959
* to those provided to the new function. This method is like `_.bind` except
7960
* it does **not** alter the `this` binding.
7961
*
7962
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
7963
* builds, may be used as a placeholder for partially applied arguments.
7964
*
7965
* **Note:** This method does not set the "length" property of partially
7966
* applied functions.
7967
*
7968
* @static
7969
* @memberOf _
7970
* @category Function
7971
* @param {Function} func The function to partially apply arguments to.
7972
* @param {...*} [partials] The arguments to be partially applied.
7973
* @returns {Function} Returns the new partially applied function.
7974
* @example
7975
*
7976
* var greet = function(greeting, name) {
7977
* return greeting + ' ' + name;
7978
* };
7979
*
7980
* var sayHelloTo = _.partial(greet, 'hello');
7981
* sayHelloTo('fred');
7982
* // => 'hello fred'
7983
*
7984
* // using placeholders
7985
* var greetFred = _.partial(greet, _, 'fred');
7986
* greetFred('hi');
7987
* // => 'hi fred'
7988
*/
7989
var partial = createPartial(PARTIAL_FLAG);
7990
7991
/**
7992
* This method is like `_.partial` except that partially applied arguments
7993
* are appended to those provided to the new function.
7994
*
7995
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
7996
* builds, may be used as a placeholder for partially applied arguments.
7997
*
7998
* **Note:** This method does not set the "length" property of partially
7999
* applied functions.
8000
*
8001
* @static
8002
* @memberOf _
8003
* @category Function
8004
* @param {Function} func The function to partially apply arguments to.
8005
* @param {...*} [partials] The arguments to be partially applied.
8006
* @returns {Function} Returns the new partially applied function.
8007
* @example
8008
*
8009
* var greet = function(greeting, name) {
8010
* return greeting + ' ' + name;
8011
* };
8012
*
8013
* var greetFred = _.partialRight(greet, 'fred');
8014
* greetFred('hi');
8015
* // => 'hi fred'
8016
*
8017
* // using placeholders
8018
* var sayHelloTo = _.partialRight(greet, 'hello', _);
8019
* sayHelloTo('fred');
8020
* // => 'hello fred'
8021
*/
8022
var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
8023
8024
/**
8025
* Creates a function that invokes `func` with arguments arranged according
8026
* to the specified indexes where the argument value at the first index is
8027
* provided as the first argument, the argument value at the second index is
8028
* provided as the second argument, and so on.
8029
*
8030
* @static
8031
* @memberOf _
8032
* @category Function
8033
* @param {Function} func The function to rearrange arguments for.
8034
* @param {...(number|number[])} indexes The arranged argument indexes,
8035
* specified as individual indexes or arrays of indexes.
8036
* @returns {Function} Returns the new function.
8037
* @example
8038
*
8039
* var rearged = _.rearg(function(a, b, c) {
8040
* return [a, b, c];
8041
* }, 2, 0, 1);
8042
*
8043
* rearged('b', 'c', 'a')
8044
* // => ['a', 'b', 'c']
8045
*
8046
* var map = _.rearg(_.map, [1, 0]);
8047
* map(function(n) {
8048
* return n * 3;
8049
* }, [1, 2, 3]);
8050
* // => [3, 6, 9]
8051
*/
8052
var rearg = restParam(function(func, indexes) {
8053
return createWrapper(func, REARG_FLAG, null, null, null, baseFlatten(indexes));
8054
});
8055
8056
/**
8057
* Creates a function that invokes `func` with the `this` binding of the
8058
* created function and arguments from `start` and beyond provided as an array.
8059
*
8060
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
8061
*
8062
* @static
8063
* @memberOf _
8064
* @category Function
8065
* @param {Function} func The function to apply a rest parameter to.
8066
* @param {number} [start=func.length-1] The start position of the rest parameter.
8067
* @returns {Function} Returns the new function.
8068
* @example
8069
*
8070
* var say = _.restParam(function(what, names) {
8071
* return what + ' ' + _.initial(names).join(', ') +
8072
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
8073
* });
8074
*
8075
* say('hello', 'fred', 'barney', 'pebbles');
8076
* // => 'hello fred, barney, & pebbles'
8077
*/
8078
function restParam(func, start) {
8079
if (typeof func != 'function') {
8080
throw new TypeError(FUNC_ERROR_TEXT);
8081
}
8082
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
8083
return function() {
8084
var args = arguments,
8085
index = -1,
8086
length = nativeMax(args.length - start, 0),
8087
rest = Array(length);
8088
8089
while (++index < length) {
8090
rest[index] = args[start + index];
8091
}
8092
switch (start) {
8093
case 0: return func.call(this, rest);
8094
case 1: return func.call(this, args[0], rest);
8095
case 2: return func.call(this, args[0], args[1], rest);
8096
}
8097
var otherArgs = Array(start + 1);
8098
index = -1;
8099
while (++index < start) {
8100
otherArgs[index] = args[index];
8101
}
8102
otherArgs[start] = rest;
8103
return func.apply(this, otherArgs);
8104
};
8105
}
8106
8107
/**
8108
* Creates a function that invokes `func` with the `this` binding of the created
8109
* function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
8110
*
8111
* **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).
8112
*
8113
* @static
8114
* @memberOf _
8115
* @category Function
8116
* @param {Function} func The function to spread arguments over.
8117
* @returns {Function} Returns the new function.
8118
* @example
8119
*
8120
* var say = _.spread(function(who, what) {
8121
* return who + ' says ' + what;
8122
* });
8123
*
8124
* say(['fred', 'hello']);
8125
* // => 'fred says hello'
8126
*
8127
* // with a Promise
8128
* var numbers = Promise.all([
8129
* Promise.resolve(40),
8130
* Promise.resolve(36)
8131
* ]);
8132
*
8133
* numbers.then(_.spread(function(x, y) {
8134
* return x + y;
8135
* }));
8136
* // => a Promise of 76
8137
*/
8138
function spread(func) {
8139
if (typeof func != 'function') {
8140
throw new TypeError(FUNC_ERROR_TEXT);
8141
}
8142
return function(array) {
8143
return func.apply(this, array);
8144
};
8145
}
8146
8147
/**
8148
* Creates a throttled function that only invokes `func` at most once per
8149
* every `wait` milliseconds. The throttled function comes with a `cancel`
8150
* method to cancel delayed invocations. Provide an options object to indicate
8151
* that `func` should be invoked on the leading and/or trailing edge of the
8152
* `wait` timeout. Subsequent calls to the throttled function return the
8153
* result of the last `func` call.
8154
*
8155
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
8156
* on the trailing edge of the timeout only if the the throttled function is
8157
* invoked more than once during the `wait` timeout.
8158
*
8159
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
8160
* for details over the differences between `_.throttle` and `_.debounce`.
8161
*
8162
* @static
8163
* @memberOf _
8164
* @category Function
8165
* @param {Function} func The function to throttle.
8166
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
8167
* @param {Object} [options] The options object.
8168
* @param {boolean} [options.leading=true] Specify invoking on the leading
8169
* edge of the timeout.
8170
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
8171
* edge of the timeout.
8172
* @returns {Function} Returns the new throttled function.
8173
* @example
8174
*
8175
* // avoid excessively updating the position while scrolling
8176
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
8177
*
8178
* // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
8179
* jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
8180
* 'trailing': false
8181
* }));
8182
*
8183
* // cancel a trailing throttled call
8184
* jQuery(window).on('popstate', throttled.cancel);
8185
*/
8186
function throttle(func, wait, options) {
8187
var leading = true,
8188
trailing = true;
8189
8190
if (typeof func != 'function') {
8191
throw new TypeError(FUNC_ERROR_TEXT);
8192
}
8193
if (options === false) {
8194
leading = false;
8195
} else if (isObject(options)) {
8196
leading = 'leading' in options ? !!options.leading : leading;
8197
trailing = 'trailing' in options ? !!options.trailing : trailing;
8198
}
8199
debounceOptions.leading = leading;
8200
debounceOptions.maxWait = +wait;
8201
debounceOptions.trailing = trailing;
8202
return debounce(func, wait, debounceOptions);
8203
}
8204
8205
/**
8206
* Creates a function that provides `value` to the wrapper function as its
8207
* first argument. Any additional arguments provided to the function are
8208
* appended to those provided to the wrapper function. The wrapper is invoked
8209
* with the `this` binding of the created function.
8210
*
8211
* @static
8212
* @memberOf _
8213
* @category Function
8214
* @param {*} value The value to wrap.
8215
* @param {Function} wrapper The wrapper function.
8216
* @returns {Function} Returns the new function.
8217
* @example
8218
*
8219
* var p = _.wrap(_.escape, function(func, text) {
8220
* return '<p>' + func(text) + '</p>';
8221
* });
8222
*
8223
* p('fred, barney, & pebbles');
8224
* // => '<p>fred, barney, &amp; pebbles</p>'
8225
*/
8226
function wrap(value, wrapper) {
8227
wrapper = wrapper == null ? identity : wrapper;
8228
return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []);
8229
}
8230
8231
/*------------------------------------------------------------------------*/
8232
8233
/**
8234
* Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
8235
* otherwise they are assigned by reference. If `customizer` is provided it is
8236
* invoked to produce the cloned values. If `customizer` returns `undefined`
8237
* cloning is handled by the method instead. The `customizer` is bound to
8238
* `thisArg` and invoked with two argument; (value [, index|key, object]).
8239
*
8240
* **Note:** This method is loosely based on the
8241
* [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
8242
* The enumerable properties of `arguments` objects and objects created by
8243
* constructors other than `Object` are cloned to plain `Object` objects. An
8244
* empty object is returned for uncloneable values such as functions, DOM nodes,
8245
* Maps, Sets, and WeakMaps.
8246
*
8247
* @static
8248
* @memberOf _
8249
* @category Lang
8250
* @param {*} value The value to clone.
8251
* @param {boolean} [isDeep] Specify a deep clone.
8252
* @param {Function} [customizer] The function to customize cloning values.
8253
* @param {*} [thisArg] The `this` binding of `customizer`.
8254
* @returns {*} Returns the cloned value.
8255
* @example
8256
*
8257
* var users = [
8258
* { 'user': 'barney' },
8259
* { 'user': 'fred' }
8260
* ];
8261
*
8262
* var shallow = _.clone(users);
8263
* shallow[0] === users[0];
8264
* // => true
8265
*
8266
* var deep = _.clone(users, true);
8267
* deep[0] === users[0];
8268
* // => false
8269
*
8270
* // using a customizer callback
8271
* var el = _.clone(document.body, function(value) {
8272
* if (_.isElement(value)) {
8273
* return value.cloneNode(false);
8274
* }
8275
* });
8276
*
8277
* el === document.body
8278
* // => false
8279
* el.nodeName
8280
* // => BODY
8281
* el.childNodes.length;
8282
* // => 0
8283
*/
8284
function clone(value, isDeep, customizer, thisArg) {
8285
if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
8286
isDeep = false;
8287
}
8288
else if (typeof isDeep == 'function') {
8289
thisArg = customizer;
8290
customizer = isDeep;
8291
isDeep = false;
8292
}
8293
return typeof customizer == 'function'
8294
? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1))
8295
: baseClone(value, isDeep);
8296
}
8297
8298
/**
8299
* Creates a deep clone of `value`. If `customizer` is provided it is invoked
8300
* to produce the cloned values. If `customizer` returns `undefined` cloning
8301
* is handled by the method instead. The `customizer` is bound to `thisArg`
8302
* and invoked with two argument; (value [, index|key, object]).
8303
*
8304
* **Note:** This method is loosely based on the
8305
* [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
8306
* The enumerable properties of `arguments` objects and objects created by
8307
* constructors other than `Object` are cloned to plain `Object` objects. An
8308
* empty object is returned for uncloneable values such as functions, DOM nodes,
8309
* Maps, Sets, and WeakMaps.
8310
*
8311
* @static
8312
* @memberOf _
8313
* @category Lang
8314
* @param {*} value The value to deep clone.
8315
* @param {Function} [customizer] The function to customize cloning values.
8316
* @param {*} [thisArg] The `this` binding of `customizer`.
8317
* @returns {*} Returns the deep cloned value.
8318
* @example
8319
*
8320
* var users = [
8321
* { 'user': 'barney' },
8322
* { 'user': 'fred' }
8323
* ];
8324
*
8325
* var deep = _.cloneDeep(users);
8326
* deep[0] === users[0];
8327
* // => false
8328
*
8329
* // using a customizer callback
8330
* var el = _.cloneDeep(document.body, function(value) {
8331
* if (_.isElement(value)) {
8332
* return value.cloneNode(true);
8333
* }
8334
* });
8335
*
8336
* el === document.body
8337
* // => false
8338
* el.nodeName
8339
* // => BODY
8340
* el.childNodes.length;
8341
* // => 20
8342
*/
8343
function cloneDeep(value, customizer, thisArg) {
8344
return typeof customizer == 'function'
8345
? baseClone(value, true, bindCallback(customizer, thisArg, 1))
8346
: baseClone(value, true);
8347
}
8348
8349
/**
8350
* Checks if `value` is greater than `other`.
8351
*
8352
* @static
8353
* @memberOf _
8354
* @category Lang
8355
* @param {*} value The value to compare.
8356
* @param {*} other The other value to compare.
8357
* @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`.
8358
* @example
8359
*
8360
* _.gt(3, 1);
8361
* // => true
8362
*
8363
* _.gt(3, 3);
8364
* // => false
8365
*
8366
* _.gt(1, 3);
8367
* // => false
8368
*/
8369
function gt(value, other) {
8370
return value > other;
8371
}
8372
8373
/**
8374
* Checks if `value` is greater than or equal to `other`.
8375
*
8376
* @static
8377
* @memberOf _
8378
* @category Lang
8379
* @param {*} value The value to compare.
8380
* @param {*} other The other value to compare.
8381
* @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`.
8382
* @example
8383
*
8384
* _.gte(3, 1);
8385
* // => true
8386
*
8387
* _.gte(3, 3);
8388
* // => true
8389
*
8390
* _.gte(1, 3);
8391
* // => false
8392
*/
8393
function gte(value, other) {
8394
return value >= other;
8395
}
8396
8397
/**
8398
* Checks if `value` is classified as an `arguments` object.
8399
*
8400
* @static
8401
* @memberOf _
8402
* @category Lang
8403
* @param {*} value The value to check.
8404
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8405
* @example
8406
*
8407
* _.isArguments(function() { return arguments; }());
8408
* // => true
8409
*
8410
* _.isArguments([1, 2, 3]);
8411
* // => false
8412
*/
8413
function isArguments(value) {
8414
return isObjectLike(value) && isArrayLike(value) && objToString.call(value) == argsTag;
8415
}
8416
8417
/**
8418
* Checks if `value` is classified as an `Array` object.
8419
*
8420
* @static
8421
* @memberOf _
8422
* @category Lang
8423
* @param {*} value The value to check.
8424
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8425
* @example
8426
*
8427
* _.isArray([1, 2, 3]);
8428
* // => true
8429
*
8430
* _.isArray(function() { return arguments; }());
8431
* // => false
8432
*/
8433
var isArray = nativeIsArray || function(value) {
8434
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
8435
};
8436
8437
/**
8438
* Checks if `value` is classified as a boolean primitive or object.
8439
*
8440
* @static
8441
* @memberOf _
8442
* @category Lang
8443
* @param {*} value The value to check.
8444
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8445
* @example
8446
*
8447
* _.isBoolean(false);
8448
* // => true
8449
*
8450
* _.isBoolean(null);
8451
* // => false
8452
*/
8453
function isBoolean(value) {
8454
return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag);
8455
}
8456
8457
/**
8458
* Checks if `value` is classified as a `Date` object.
8459
*
8460
* @static
8461
* @memberOf _
8462
* @category Lang
8463
* @param {*} value The value to check.
8464
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8465
* @example
8466
*
8467
* _.isDate(new Date);
8468
* // => true
8469
*
8470
* _.isDate('Mon April 23 2012');
8471
* // => false
8472
*/
8473
function isDate(value) {
8474
return isObjectLike(value) && objToString.call(value) == dateTag;
8475
}
8476
8477
/**
8478
* Checks if `value` is a DOM element.
8479
*
8480
* @static
8481
* @memberOf _
8482
* @category Lang
8483
* @param {*} value The value to check.
8484
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
8485
* @example
8486
*
8487
* _.isElement(document.body);
8488
* // => true
8489
*
8490
* _.isElement('<body>');
8491
* // => false
8492
*/
8493
function isElement(value) {
8494
return !!value && value.nodeType === 1 && isObjectLike(value) &&
8495
(objToString.call(value).indexOf('Element') > -1);
8496
}
8497
// Fallback for environments without DOM support.
8498
if (!support.dom) {
8499
isElement = function(value) {
8500
return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
8501
};
8502
}
8503
8504
/**
8505
* Checks if `value` is empty. A value is considered empty unless it is an
8506
* `arguments` object, array, string, or jQuery-like collection with a length
8507
* greater than `0` or an object with own enumerable properties.
8508
*
8509
* @static
8510
* @memberOf _
8511
* @category Lang
8512
* @param {Array|Object|string} value The value to inspect.
8513
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
8514
* @example
8515
*
8516
* _.isEmpty(null);
8517
* // => true
8518
*
8519
* _.isEmpty(true);
8520
* // => true
8521
*
8522
* _.isEmpty(1);
8523
* // => true
8524
*
8525
* _.isEmpty([1, 2, 3]);
8526
* // => false
8527
*
8528
* _.isEmpty({ 'a': 1 });
8529
* // => false
8530
*/
8531
function isEmpty(value) {
8532
if (value == null) {
8533
return true;
8534
}
8535
if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
8536
(isObjectLike(value) && isFunction(value.splice)))) {
8537
return !value.length;
8538
}
8539
return !keys(value).length;
8540
}
8541
8542
/**
8543
* Performs a deep comparison between two values to determine if they are
8544
* equivalent. If `customizer` is provided it is invoked to compare values.
8545
* If `customizer` returns `undefined` comparisons are handled by the method
8546
* instead. The `customizer` is bound to `thisArg` and invoked with three
8547
* arguments: (value, other [, index|key]).
8548
*
8549
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
8550
* numbers, `Object` objects, regexes, and strings. Objects are compared by
8551
* their own, not inherited, enumerable properties. Functions and DOM nodes
8552
* are **not** supported. Provide a customizer function to extend support
8553
* for comparing other values.
8554
*
8555
* @static
8556
* @memberOf _
8557
* @alias eq
8558
* @category Lang
8559
* @param {*} value The value to compare.
8560
* @param {*} other The other value to compare.
8561
* @param {Function} [customizer] The function to customize value comparisons.
8562
* @param {*} [thisArg] The `this` binding of `customizer`.
8563
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
8564
* @example
8565
*
8566
* var object = { 'user': 'fred' };
8567
* var other = { 'user': 'fred' };
8568
*
8569
* object == other;
8570
* // => false
8571
*
8572
* _.isEqual(object, other);
8573
* // => true
8574
*
8575
* // using a customizer callback
8576
* var array = ['hello', 'goodbye'];
8577
* var other = ['hi', 'goodbye'];
8578
*
8579
* _.isEqual(array, other, function(value, other) {
8580
* if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
8581
* return true;
8582
* }
8583
* });
8584
* // => true
8585
*/
8586
function isEqual(value, other, customizer, thisArg) {
8587
customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
8588
var result = customizer ? customizer(value, other) : undefined;
8589
return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
8590
}
8591
8592
/**
8593
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
8594
* `SyntaxError`, `TypeError`, or `URIError` object.
8595
*
8596
* @static
8597
* @memberOf _
8598
* @category Lang
8599
* @param {*} value The value to check.
8600
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
8601
* @example
8602
*
8603
* _.isError(new Error);
8604
* // => true
8605
*
8606
* _.isError(Error);
8607
* // => false
8608
*/
8609
function isError(value) {
8610
return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
8611
}
8612
8613
/**
8614
* Checks if `value` is a finite primitive number.
8615
*
8616
* **Note:** This method is based on [`Number.isFinite`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite).
8617
*
8618
* @static
8619
* @memberOf _
8620
* @category Lang
8621
* @param {*} value The value to check.
8622
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
8623
* @example
8624
*
8625
* _.isFinite(10);
8626
* // => true
8627
*
8628
* _.isFinite('10');
8629
* // => false
8630
*
8631
* _.isFinite(true);
8632
* // => false
8633
*
8634
* _.isFinite(Object(10));
8635
* // => false
8636
*
8637
* _.isFinite(Infinity);
8638
* // => false
8639
*/
8640
var isFinite = nativeNumIsFinite || function(value) {
8641
return typeof value == 'number' && nativeIsFinite(value);
8642
};
8643
8644
/**
8645
* Checks if `value` is classified as a `Function` object.
8646
*
8647
* @static
8648
* @memberOf _
8649
* @category Lang
8650
* @param {*} value The value to check.
8651
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8652
* @example
8653
*
8654
* _.isFunction(_);
8655
* // => true
8656
*
8657
* _.isFunction(/abc/);
8658
* // => false
8659
*/
8660
var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) {
8661
// The use of `Object#toString` avoids issues with the `typeof` operator
8662
// in older versions of Chrome and Safari which return 'function' for regexes
8663
// and Safari 8 equivalents which return 'object' for typed array constructors.
8664
return objToString.call(value) == funcTag;
8665
};
8666
8667
/**
8668
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
8669
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
8670
*
8671
* @static
8672
* @memberOf _
8673
* @category Lang
8674
* @param {*} value The value to check.
8675
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
8676
* @example
8677
*
8678
* _.isObject({});
8679
* // => true
8680
*
8681
* _.isObject([1, 2, 3]);
8682
* // => true
8683
*
8684
* _.isObject(1);
8685
* // => false
8686
*/
8687
function isObject(value) {
8688
// Avoid a V8 JIT bug in Chrome 19-20.
8689
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
8690
var type = typeof value;
8691
return !!value && (type == 'object' || type == 'function');
8692
}
8693
8694
/**
8695
* Performs a deep comparison between `object` and `source` to determine if
8696
* `object` contains equivalent property values. If `customizer` is provided
8697
* it is invoked to compare values. If `customizer` returns `undefined`
8698
* comparisons are handled by the method instead. The `customizer` is bound
8699
* to `thisArg` and invoked with three arguments: (value, other, index|key).
8700
*
8701
* **Note:** This method supports comparing properties of arrays, booleans,
8702
* `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
8703
* and DOM nodes are **not** supported. Provide a customizer function to extend
8704
* support for comparing other values.
8705
*
8706
* @static
8707
* @memberOf _
8708
* @category Lang
8709
* @param {Object} object The object to inspect.
8710
* @param {Object} source The object of property values to match.
8711
* @param {Function} [customizer] The function to customize value comparisons.
8712
* @param {*} [thisArg] The `this` binding of `customizer`.
8713
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
8714
* @example
8715
*
8716
* var object = { 'user': 'fred', 'age': 40 };
8717
*
8718
* _.isMatch(object, { 'age': 40 });
8719
* // => true
8720
*
8721
* _.isMatch(object, { 'age': 36 });
8722
* // => false
8723
*
8724
* // using a customizer callback
8725
* var object = { 'greeting': 'hello' };
8726
* var source = { 'greeting': 'hi' };
8727
*
8728
* _.isMatch(object, source, function(value, other) {
8729
* return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
8730
* });
8731
* // => true
8732
*/
8733
function isMatch(object, source, customizer, thisArg) {
8734
customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
8735
return baseIsMatch(object, getMatchData(source), customizer);
8736
}
8737
8738
/**
8739
* Checks if `value` is `NaN`.
8740
*
8741
* **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
8742
* which returns `true` for `undefined` and other non-numeric values.
8743
*
8744
* @static
8745
* @memberOf _
8746
* @category Lang
8747
* @param {*} value The value to check.
8748
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
8749
* @example
8750
*
8751
* _.isNaN(NaN);
8752
* // => true
8753
*
8754
* _.isNaN(new Number(NaN));
8755
* // => true
8756
*
8757
* isNaN(undefined);
8758
* // => true
8759
*
8760
* _.isNaN(undefined);
8761
* // => false
8762
*/
8763
function isNaN(value) {
8764
// An `NaN` primitive is the only value that is not equal to itself.
8765
// Perform the `toStringTag` check first to avoid errors with some host objects in IE.
8766
return isNumber(value) && value != +value;
8767
}
8768
8769
/**
8770
* Checks if `value` is a native function.
8771
*
8772
* @static
8773
* @memberOf _
8774
* @category Lang
8775
* @param {*} value The value to check.
8776
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
8777
* @example
8778
*
8779
* _.isNative(Array.prototype.push);
8780
* // => true
8781
*
8782
* _.isNative(_);
8783
* // => false
8784
*/
8785
function isNative(value) {
8786
if (value == null) {
8787
return false;
8788
}
8789
if (objToString.call(value) == funcTag) {
8790
return reIsNative.test(fnToString.call(value));
8791
}
8792
return isObjectLike(value) && reIsHostCtor.test(value);
8793
}
8794
8795
/**
8796
* Checks if `value` is `null`.
8797
*
8798
* @static
8799
* @memberOf _
8800
* @category Lang
8801
* @param {*} value The value to check.
8802
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
8803
* @example
8804
*
8805
* _.isNull(null);
8806
* // => true
8807
*
8808
* _.isNull(void 0);
8809
* // => false
8810
*/
8811
function isNull(value) {
8812
return value === null;
8813
}
8814
8815
/**
8816
* Checks if `value` is classified as a `Number` primitive or object.
8817
*
8818
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
8819
* as numbers, use the `_.isFinite` method.
8820
*
8821
* @static
8822
* @memberOf _
8823
* @category Lang
8824
* @param {*} value The value to check.
8825
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8826
* @example
8827
*
8828
* _.isNumber(8.4);
8829
* // => true
8830
*
8831
* _.isNumber(NaN);
8832
* // => true
8833
*
8834
* _.isNumber('8.4');
8835
* // => false
8836
*/
8837
function isNumber(value) {
8838
return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag);
8839
}
8840
8841
/**
8842
* Checks if `value` is a plain object, that is, an object created by the
8843
* `Object` constructor or one with a `[[Prototype]]` of `null`.
8844
*
8845
* **Note:** This method assumes objects created by the `Object` constructor
8846
* have no inherited enumerable properties.
8847
*
8848
* @static
8849
* @memberOf _
8850
* @category Lang
8851
* @param {*} value The value to check.
8852
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
8853
* @example
8854
*
8855
* function Foo() {
8856
* this.a = 1;
8857
* }
8858
*
8859
* _.isPlainObject(new Foo);
8860
* // => false
8861
*
8862
* _.isPlainObject([1, 2, 3]);
8863
* // => false
8864
*
8865
* _.isPlainObject({ 'x': 0, 'y': 0 });
8866
* // => true
8867
*
8868
* _.isPlainObject(Object.create(null));
8869
* // => true
8870
*/
8871
var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
8872
if (!(value && objToString.call(value) == objectTag)) {
8873
return false;
8874
}
8875
var valueOf = getNative(value, 'valueOf'),
8876
objProto = valueOf && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
8877
8878
return objProto
8879
? (value == objProto || getPrototypeOf(value) == objProto)
8880
: shimIsPlainObject(value);
8881
};
8882
8883
/**
8884
* Checks if `value` is classified as a `RegExp` object.
8885
*
8886
* @static
8887
* @memberOf _
8888
* @category Lang
8889
* @param {*} value The value to check.
8890
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8891
* @example
8892
*
8893
* _.isRegExp(/abc/);
8894
* // => true
8895
*
8896
* _.isRegExp('/abc/');
8897
* // => false
8898
*/
8899
function isRegExp(value) {
8900
return isObjectLike(value) && objToString.call(value) == regexpTag;
8901
}
8902
8903
/**
8904
* Checks if `value` is classified as a `String` primitive or object.
8905
*
8906
* @static
8907
* @memberOf _
8908
* @category Lang
8909
* @param {*} value The value to check.
8910
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8911
* @example
8912
*
8913
* _.isString('abc');
8914
* // => true
8915
*
8916
* _.isString(1);
8917
* // => false
8918
*/
8919
function isString(value) {
8920
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
8921
}
8922
8923
/**
8924
* Checks if `value` is classified as a typed array.
8925
*
8926
* @static
8927
* @memberOf _
8928
* @category Lang
8929
* @param {*} value The value to check.
8930
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8931
* @example
8932
*
8933
* _.isTypedArray(new Uint8Array);
8934
* // => true
8935
*
8936
* _.isTypedArray([]);
8937
* // => false
8938
*/
8939
function isTypedArray(value) {
8940
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
8941
}
8942
8943
/**
8944
* Checks if `value` is `undefined`.
8945
*
8946
* @static
8947
* @memberOf _
8948
* @category Lang
8949
* @param {*} value The value to check.
8950
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
8951
* @example
8952
*
8953
* _.isUndefined(void 0);
8954
* // => true
8955
*
8956
* _.isUndefined(null);
8957
* // => false
8958
*/
8959
function isUndefined(value) {
8960
return value === undefined;
8961
}
8962
8963
/**
8964
* Checks if `value` is less than `other`.
8965
*
8966
* @static
8967
* @memberOf _
8968
* @category Lang
8969
* @param {*} value The value to compare.
8970
* @param {*} other The other value to compare.
8971
* @returns {boolean} Returns `true` if `value` is less than `other`, else `false`.
8972
* @example
8973
*
8974
* _.lt(1, 3);
8975
* // => true
8976
*
8977
* _.lt(3, 3);
8978
* // => false
8979
*
8980
* _.lt(3, 1);
8981
* // => false
8982
*/
8983
function lt(value, other) {
8984
return value < other;
8985
}
8986
8987
/**
8988
* Checks if `value` is less than or equal to `other`.
8989
*
8990
* @static
8991
* @memberOf _
8992
* @category Lang
8993
* @param {*} value The value to compare.
8994
* @param {*} other The other value to compare.
8995
* @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`.
8996
* @example
8997
*
8998
* _.lte(1, 3);
8999
* // => true
9000
*
9001
* _.lte(3, 3);
9002
* // => true
9003
*
9004
* _.lte(3, 1);
9005
* // => false
9006
*/
9007
function lte(value, other) {
9008
return value <= other;
9009
}
9010
9011
/**
9012
* Converts `value` to an array.
9013
*
9014
* @static
9015
* @memberOf _
9016
* @category Lang
9017
* @param {*} value The value to convert.
9018
* @returns {Array} Returns the converted array.
9019
* @example
9020
*
9021
* (function() {
9022
* return _.toArray(arguments).slice(1);
9023
* }(1, 2, 3));
9024
* // => [2, 3]
9025
*/
9026
function toArray(value) {
9027
var length = value ? getLength(value) : 0;
9028
if (!isLength(length)) {
9029
return values(value);
9030
}
9031
if (!length) {
9032
return [];
9033
}
9034
return arrayCopy(value);
9035
}
9036
9037
/**
9038
* Converts `value` to a plain object flattening inherited enumerable
9039
* properties of `value` to own properties of the plain object.
9040
*
9041
* @static
9042
* @memberOf _
9043
* @category Lang
9044
* @param {*} value The value to convert.
9045
* @returns {Object} Returns the converted plain object.
9046
* @example
9047
*
9048
* function Foo() {
9049
* this.b = 2;
9050
* }
9051
*
9052
* Foo.prototype.c = 3;
9053
*
9054
* _.assign({ 'a': 1 }, new Foo);
9055
* // => { 'a': 1, 'b': 2 }
9056
*
9057
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
9058
* // => { 'a': 1, 'b': 2, 'c': 3 }
9059
*/
9060
function toPlainObject(value) {
9061
return baseCopy(value, keysIn(value));
9062
}
9063
9064
/*------------------------------------------------------------------------*/
9065
9066
/**
9067
* Assigns own enumerable properties of source object(s) to the destination
9068
* object. Subsequent sources overwrite property assignments of previous sources.
9069
* If `customizer` is provided it is invoked to produce the assigned values.
9070
* The `customizer` is bound to `thisArg` and invoked with five arguments:
9071
* (objectValue, sourceValue, key, object, source).
9072
*
9073
* **Note:** This method mutates `object` and is based on
9074
* [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign).
9075
*
9076
* @static
9077
* @memberOf _
9078
* @alias extend
9079
* @category Object
9080
* @param {Object} object The destination object.
9081
* @param {...Object} [sources] The source objects.
9082
* @param {Function} [customizer] The function to customize assigned values.
9083
* @param {*} [thisArg] The `this` binding of `customizer`.
9084
* @returns {Object} Returns `object`.
9085
* @example
9086
*
9087
* _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
9088
* // => { 'user': 'fred', 'age': 40 }
9089
*
9090
* // using a customizer callback
9091
* var defaults = _.partialRight(_.assign, function(value, other) {
9092
* return _.isUndefined(value) ? other : value;
9093
* });
9094
*
9095
* defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
9096
* // => { 'user': 'barney', 'age': 36 }
9097
*/
9098
var assign = createAssigner(function(object, source, customizer) {
9099
return customizer
9100
? assignWith(object, source, customizer)
9101
: baseAssign(object, source);
9102
});
9103
9104
/**
9105
* Creates an object that inherits from the given `prototype` object. If a
9106
* `properties` object is provided its own enumerable properties are assigned
9107
* to the created object.
9108
*
9109
* @static
9110
* @memberOf _
9111
* @category Object
9112
* @param {Object} prototype The object to inherit from.
9113
* @param {Object} [properties] The properties to assign to the object.
9114
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
9115
* @returns {Object} Returns the new object.
9116
* @example
9117
*
9118
* function Shape() {
9119
* this.x = 0;
9120
* this.y = 0;
9121
* }
9122
*
9123
* function Circle() {
9124
* Shape.call(this);
9125
* }
9126
*
9127
* Circle.prototype = _.create(Shape.prototype, {
9128
* 'constructor': Circle
9129
* });
9130
*
9131
* var circle = new Circle;
9132
* circle instanceof Circle;
9133
* // => true
9134
*
9135
* circle instanceof Shape;
9136
* // => true
9137
*/
9138
function create(prototype, properties, guard) {
9139
var result = baseCreate(prototype);
9140
if (guard && isIterateeCall(prototype, properties, guard)) {
9141
properties = null;
9142
}
9143
return properties ? baseAssign(result, properties) : result;
9144
}
9145
9146
/**
9147
* Assigns own enumerable properties of source object(s) to the destination
9148
* object for all destination properties that resolve to `undefined`. Once a
9149
* property is set, additional values of the same property are ignored.
9150
*
9151
* **Note:** This method mutates `object`.
9152
*
9153
* @static
9154
* @memberOf _
9155
* @category Object
9156
* @param {Object} object The destination object.
9157
* @param {...Object} [sources] The source objects.
9158
* @returns {Object} Returns `object`.
9159
* @example
9160
*
9161
* _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
9162
* // => { 'user': 'barney', 'age': 36 }
9163
*/
9164
var defaults = restParam(function(args) {
9165
var object = args[0];
9166
if (object == null) {
9167
return object;
9168
}
9169
args.push(assignDefaults);
9170
return assign.apply(undefined, args);
9171
});
9172
9173
/**
9174
* This method is like `_.find` except that it returns the key of the first
9175
* element `predicate` returns truthy for instead of the element itself.
9176
*
9177
* If a property name is provided for `predicate` the created `_.property`
9178
* style callback returns the property value of the given element.
9179
*
9180
* If a value is also provided for `thisArg` the created `_.matchesProperty`
9181
* style callback returns `true` for elements that have a matching property
9182
* value, else `false`.
9183
*
9184
* If an object is provided for `predicate` the created `_.matches` style
9185
* callback returns `true` for elements that have the properties of the given
9186
* object, else `false`.
9187
*
9188
* @static
9189
* @memberOf _
9190
* @category Object
9191
* @param {Object} object The object to search.
9192
* @param {Function|Object|string} [predicate=_.identity] The function invoked
9193
* per iteration.
9194
* @param {*} [thisArg] The `this` binding of `predicate`.
9195
* @returns {string|undefined} Returns the key of the matched element, else `undefined`.
9196
* @example
9197
*
9198
* var users = {
9199
* 'barney': { 'age': 36, 'active': true },
9200
* 'fred': { 'age': 40, 'active': false },
9201
* 'pebbles': { 'age': 1, 'active': true }
9202
* };
9203
*
9204
* _.findKey(users, function(chr) {
9205
* return chr.age < 40;
9206
* });
9207
* // => 'barney' (iteration order is not guaranteed)
9208
*
9209
* // using the `_.matches` callback shorthand
9210
* _.findKey(users, { 'age': 1, 'active': true });
9211
* // => 'pebbles'
9212
*
9213
* // using the `_.matchesProperty` callback shorthand
9214
* _.findKey(users, 'active', false);
9215
* // => 'fred'
9216
*
9217
* // using the `_.property` callback shorthand
9218
* _.findKey(users, 'active');
9219
* // => 'barney'
9220
*/
9221
var findKey = createFindKey(baseForOwn);
9222
9223
/**
9224
* This method is like `_.findKey` except that it iterates over elements of
9225
* a collection in the opposite order.
9226
*
9227
* If a property name is provided for `predicate` the created `_.property`
9228
* style callback returns the property value of the given element.
9229
*
9230
* If a value is also provided for `thisArg` the created `_.matchesProperty`
9231
* style callback returns `true` for elements that have a matching property
9232
* value, else `false`.
9233
*
9234
* If an object is provided for `predicate` the created `_.matches` style
9235
* callback returns `true` for elements that have the properties of the given
9236
* object, else `false`.
9237
*
9238
* @static
9239
* @memberOf _
9240
* @category Object
9241
* @param {Object} object The object to search.
9242
* @param {Function|Object|string} [predicate=_.identity] The function invoked
9243
* per iteration.
9244
* @param {*} [thisArg] The `this` binding of `predicate`.
9245
* @returns {string|undefined} Returns the key of the matched element, else `undefined`.
9246
* @example
9247
*
9248
* var users = {
9249
* 'barney': { 'age': 36, 'active': true },
9250
* 'fred': { 'age': 40, 'active': false },
9251
* 'pebbles': { 'age': 1, 'active': true }
9252
* };
9253
*
9254
* _.findLastKey(users, function(chr) {
9255
* return chr.age < 40;
9256
* });
9257
* // => returns `pebbles` assuming `_.findKey` returns `barney`
9258
*
9259
* // using the `_.matches` callback shorthand
9260
* _.findLastKey(users, { 'age': 36, 'active': true });
9261
* // => 'barney'
9262
*
9263
* // using the `_.matchesProperty` callback shorthand
9264
* _.findLastKey(users, 'active', false);
9265
* // => 'fred'
9266
*
9267
* // using the `_.property` callback shorthand
9268
* _.findLastKey(users, 'active');
9269
* // => 'pebbles'
9270
*/
9271
var findLastKey = createFindKey(baseForOwnRight);
9272
9273
/**
9274
* Iterates over own and inherited enumerable properties of an object invoking
9275
* `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
9276
* with three arguments: (value, key, object). Iteratee functions may exit
9277
* iteration early by explicitly returning `false`.
9278
*
9279
* @static
9280
* @memberOf _
9281
* @category Object
9282
* @param {Object} object The object to iterate over.
9283
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
9284
* @param {*} [thisArg] The `this` binding of `iteratee`.
9285
* @returns {Object} Returns `object`.
9286
* @example
9287
*
9288
* function Foo() {
9289
* this.a = 1;
9290
* this.b = 2;
9291
* }
9292
*
9293
* Foo.prototype.c = 3;
9294
*
9295
* _.forIn(new Foo, function(value, key) {
9296
* console.log(key);
9297
* });
9298
* // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
9299
*/
9300
var forIn = createForIn(baseFor);
9301
9302
/**
9303
* This method is like `_.forIn` except that it iterates over properties of
9304
* `object` in the opposite order.
9305
*
9306
* @static
9307
* @memberOf _
9308
* @category Object
9309
* @param {Object} object The object to iterate over.
9310
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
9311
* @param {*} [thisArg] The `this` binding of `iteratee`.
9312
* @returns {Object} Returns `object`.
9313
* @example
9314
*
9315
* function Foo() {
9316
* this.a = 1;
9317
* this.b = 2;
9318
* }
9319
*
9320
* Foo.prototype.c = 3;
9321
*
9322
* _.forInRight(new Foo, function(value, key) {
9323
* console.log(key);
9324
* });
9325
* // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
9326
*/
9327
var forInRight = createForIn(baseForRight);
9328
9329
/**
9330
* Iterates over own enumerable properties of an object invoking `iteratee`
9331
* for each property. The `iteratee` is bound to `thisArg` and invoked with
9332
* three arguments: (value, key, object). Iteratee functions may exit iteration
9333
* early by explicitly returning `false`.
9334
*
9335
* @static
9336
* @memberOf _
9337
* @category Object
9338
* @param {Object} object The object to iterate over.
9339
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
9340
* @param {*} [thisArg] The `this` binding of `iteratee`.
9341
* @returns {Object} Returns `object`.
9342
* @example
9343
*
9344
* function Foo() {
9345
* this.a = 1;
9346
* this.b = 2;
9347
* }
9348
*
9349
* Foo.prototype.c = 3;
9350
*
9351
* _.forOwn(new Foo, function(value, key) {
9352
* console.log(key);
9353
* });
9354
* // => logs 'a' and 'b' (iteration order is not guaranteed)
9355
*/
9356
var forOwn = createForOwn(baseForOwn);
9357
9358
/**
9359
* This method is like `_.forOwn` except that it iterates over properties of
9360
* `object` in the opposite order.
9361
*
9362
* @static
9363
* @memberOf _
9364
* @category Object
9365
* @param {Object} object The object to iterate over.
9366
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
9367
* @param {*} [thisArg] The `this` binding of `iteratee`.
9368
* @returns {Object} Returns `object`.
9369
* @example
9370
*
9371
* function Foo() {
9372
* this.a = 1;
9373
* this.b = 2;
9374
* }
9375
*
9376
* Foo.prototype.c = 3;
9377
*
9378
* _.forOwnRight(new Foo, function(value, key) {
9379
* console.log(key);
9380
* });
9381
* // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
9382
*/
9383
var forOwnRight = createForOwn(baseForOwnRight);
9384
9385
/**
9386
* Creates an array of function property names from all enumerable properties,
9387
* own and inherited, of `object`.
9388
*
9389
* @static
9390
* @memberOf _
9391
* @alias methods
9392
* @category Object
9393
* @param {Object} object The object to inspect.
9394
* @returns {Array} Returns the new array of property names.
9395
* @example
9396
*
9397
* _.functions(_);
9398
* // => ['after', 'ary', 'assign', ...]
9399
*/
9400
function functions(object) {
9401
return baseFunctions(object, keysIn(object));
9402
}
9403
9404
/**
9405
* Gets the property value at `path` of `object`. If the resolved value is
9406
* `undefined` the `defaultValue` is used in its place.
9407
*
9408
* @static
9409
* @memberOf _
9410
* @category Object
9411
* @param {Object} object The object to query.
9412
* @param {Array|string} path The path of the property to get.
9413
* @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
9414
* @returns {*} Returns the resolved value.
9415
* @example
9416
*
9417
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
9418
*
9419
* _.get(object, 'a[0].b.c');
9420
* // => 3
9421
*
9422
* _.get(object, ['a', '0', 'b', 'c']);
9423
* // => 3
9424
*
9425
* _.get(object, 'a.b.c', 'default');
9426
* // => 'default'
9427
*/
9428
function get(object, path, defaultValue) {
9429
var result = object == null ? undefined : baseGet(object, toPath(path), path + '');
9430
return result === undefined ? defaultValue : result;
9431
}
9432
9433
/**
9434
* Checks if `path` is a direct property.
9435
*
9436
* @static
9437
* @memberOf _
9438
* @category Object
9439
* @param {Object} object The object to query.
9440
* @param {Array|string} path The path to check.
9441
* @returns {boolean} Returns `true` if `path` is a direct property, else `false`.
9442
* @example
9443
*
9444
* var object = { 'a': { 'b': { 'c': 3 } } };
9445
*
9446
* _.has(object, 'a');
9447
* // => true
9448
*
9449
* _.has(object, 'a.b.c');
9450
* // => true
9451
*
9452
* _.has(object, ['a', 'b', 'c']);
9453
* // => true
9454
*/
9455
function has(object, path) {
9456
if (object == null) {
9457
return false;
9458
}
9459
var result = hasOwnProperty.call(object, path);
9460
if (!result && !isKey(path)) {
9461
path = toPath(path);
9462
object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
9463
if (object == null) {
9464
return false;
9465
}
9466
path = last(path);
9467
result = hasOwnProperty.call(object, path);
9468
}
9469
return result || (isLength(object.length) && isIndex(path, object.length) &&
9470
(isArray(object) || isArguments(object)));
9471
}
9472
9473
/**
9474
* Creates an object composed of the inverted keys and values of `object`.
9475
* If `object` contains duplicate values, subsequent values overwrite property
9476
* assignments of previous values unless `multiValue` is `true`.
9477
*
9478
* @static
9479
* @memberOf _
9480
* @category Object
9481
* @param {Object} object The object to invert.
9482
* @param {boolean} [multiValue] Allow multiple values per key.
9483
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
9484
* @returns {Object} Returns the new inverted object.
9485
* @example
9486
*
9487
* var object = { 'a': 1, 'b': 2, 'c': 1 };
9488
*
9489
* _.invert(object);
9490
* // => { '1': 'c', '2': 'b' }
9491
*
9492
* // with `multiValue`
9493
* _.invert(object, true);
9494
* // => { '1': ['a', 'c'], '2': ['b'] }
9495
*/
9496
function invert(object, multiValue, guard) {
9497
if (guard && isIterateeCall(object, multiValue, guard)) {
9498
multiValue = null;
9499
}
9500
var index = -1,
9501
props = keys(object),
9502
length = props.length,
9503
result = {};
9504
9505
while (++index < length) {
9506
var key = props[index],
9507
value = object[key];
9508
9509
if (multiValue) {
9510
if (hasOwnProperty.call(result, value)) {
9511
result[value].push(key);
9512
} else {
9513
result[value] = [key];
9514
}
9515
}
9516
else {
9517
result[value] = key;
9518
}
9519
}
9520
return result;
9521
}
9522
9523
/**
9524
* Creates an array of the own enumerable property names of `object`.
9525
*
9526
* **Note:** Non-object values are coerced to objects. See the
9527
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys)
9528
* for more details.
9529
*
9530
* @static
9531
* @memberOf _
9532
* @category Object
9533
* @param {Object} object The object to query.
9534
* @returns {Array} Returns the array of property names.
9535
* @example
9536
*
9537
* function Foo() {
9538
* this.a = 1;
9539
* this.b = 2;
9540
* }
9541
*
9542
* Foo.prototype.c = 3;
9543
*
9544
* _.keys(new Foo);
9545
* // => ['a', 'b'] (iteration order is not guaranteed)
9546
*
9547
* _.keys('hi');
9548
* // => ['0', '1']
9549
*/
9550
var keys = !nativeKeys ? shimKeys : function(object) {
9551
var Ctor = object == null ? null : object.constructor;
9552
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
9553
(typeof object != 'function' && isArrayLike(object))) {
9554
return shimKeys(object);
9555
}
9556
return isObject(object) ? nativeKeys(object) : [];
9557
};
9558
9559
/**
9560
* Creates an array of the own and inherited enumerable property names of `object`.
9561
*
9562
* **Note:** Non-object values are coerced to objects.
9563
*
9564
* @static
9565
* @memberOf _
9566
* @category Object
9567
* @param {Object} object The object to query.
9568
* @returns {Array} Returns the array of property names.
9569
* @example
9570
*
9571
* function Foo() {
9572
* this.a = 1;
9573
* this.b = 2;
9574
* }
9575
*
9576
* Foo.prototype.c = 3;
9577
*
9578
* _.keysIn(new Foo);
9579
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
9580
*/
9581
function keysIn(object) {
9582
if (object == null) {
9583
return [];
9584
}
9585
if (!isObject(object)) {
9586
object = Object(object);
9587
}
9588
var length = object.length;
9589
length = (length && isLength(length) &&
9590
(isArray(object) || isArguments(object)) && length) || 0;
9591
9592
var Ctor = object.constructor,
9593
index = -1,
9594
isProto = typeof Ctor == 'function' && Ctor.prototype === object,
9595
result = Array(length),
9596
skipIndexes = length > 0;
9597
9598
while (++index < length) {
9599
result[index] = (index + '');
9600
}
9601
for (var key in object) {
9602
if (!(skipIndexes && isIndex(key, length)) &&
9603
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
9604
result.push(key);
9605
}
9606
}
9607
return result;
9608
}
9609
9610
/**
9611
* The opposite of `_.mapValues`; this method creates an object with the
9612
* same values as `object` and keys generated by running each own enumerable
9613
* property of `object` through `iteratee`.
9614
*
9615
* @static
9616
* @memberOf _
9617
* @category Object
9618
* @param {Object} object The object to iterate over.
9619
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
9620
* per iteration.
9621
* @param {*} [thisArg] The `this` binding of `iteratee`.
9622
* @returns {Object} Returns the new mapped object.
9623
* @example
9624
*
9625
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
9626
* return key + value;
9627
* });
9628
* // => { 'a1': 1, 'b2': 2 }
9629
*/
9630
var mapKeys = createObjectMapper(true);
9631
9632
/**
9633
* Creates an object with the same keys as `object` and values generated by
9634
* running each own enumerable property of `object` through `iteratee`. The
9635
* iteratee function is bound to `thisArg` and invoked with three arguments:
9636
* (value, key, object).
9637
*
9638
* If a property name is provided for `iteratee` the created `_.property`
9639
* style callback returns the property value of the given element.
9640
*
9641
* If a value is also provided for `thisArg` the created `_.matchesProperty`
9642
* style callback returns `true` for elements that have a matching property
9643
* value, else `false`.
9644
*
9645
* If an object is provided for `iteratee` the created `_.matches` style
9646
* callback returns `true` for elements that have the properties of the given
9647
* object, else `false`.
9648
*
9649
* @static
9650
* @memberOf _
9651
* @category Object
9652
* @param {Object} object The object to iterate over.
9653
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
9654
* per iteration.
9655
* @param {*} [thisArg] The `this` binding of `iteratee`.
9656
* @returns {Object} Returns the new mapped object.
9657
* @example
9658
*
9659
* _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
9660
* return n * 3;
9661
* });
9662
* // => { 'a': 3, 'b': 6 }
9663
*
9664
* var users = {
9665
* 'fred': { 'user': 'fred', 'age': 40 },
9666
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
9667
* };
9668
*
9669
* // using the `_.property` callback shorthand
9670
* _.mapValues(users, 'age');
9671
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
9672
*/
9673
var mapValues = createObjectMapper();
9674
9675
/**
9676
* Recursively merges own enumerable properties of the source object(s), that
9677
* don't resolve to `undefined` into the destination object. Subsequent sources
9678
* overwrite property assignments of previous sources. If `customizer` is
9679
* provided it is invoked to produce the merged values of the destination and
9680
* source properties. If `customizer` returns `undefined` merging is handled
9681
* by the method instead. The `customizer` is bound to `thisArg` and invoked
9682
* with five arguments: (objectValue, sourceValue, key, object, source).
9683
*
9684
* @static
9685
* @memberOf _
9686
* @category Object
9687
* @param {Object} object The destination object.
9688
* @param {...Object} [sources] The source objects.
9689
* @param {Function} [customizer] The function to customize assigned values.
9690
* @param {*} [thisArg] The `this` binding of `customizer`.
9691
* @returns {Object} Returns `object`.
9692
* @example
9693
*
9694
* var users = {
9695
* 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
9696
* };
9697
*
9698
* var ages = {
9699
* 'data': [{ 'age': 36 }, { 'age': 40 }]
9700
* };
9701
*
9702
* _.merge(users, ages);
9703
* // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
9704
*
9705
* // using a customizer callback
9706
* var object = {
9707
* 'fruits': ['apple'],
9708
* 'vegetables': ['beet']
9709
* };
9710
*
9711
* var other = {
9712
* 'fruits': ['banana'],
9713
* 'vegetables': ['carrot']
9714
* };
9715
*
9716
* _.merge(object, other, function(a, b) {
9717
* if (_.isArray(a)) {
9718
* return a.concat(b);
9719
* }
9720
* });
9721
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
9722
*/
9723
var merge = createAssigner(baseMerge);
9724
9725
/**
9726
* The opposite of `_.pick`; this method creates an object composed of the
9727
* own and inherited enumerable properties of `object` that are not omitted.
9728
*
9729
* @static
9730
* @memberOf _
9731
* @category Object
9732
* @param {Object} object The source object.
9733
* @param {Function|...(string|string[])} [predicate] The function invoked per
9734
* iteration or property names to omit, specified as individual property
9735
* names or arrays of property names.
9736
* @param {*} [thisArg] The `this` binding of `predicate`.
9737
* @returns {Object} Returns the new object.
9738
* @example
9739
*
9740
* var object = { 'user': 'fred', 'age': 40 };
9741
*
9742
* _.omit(object, 'age');
9743
* // => { 'user': 'fred' }
9744
*
9745
* _.omit(object, _.isNumber);
9746
* // => { 'user': 'fred' }
9747
*/
9748
var omit = restParam(function(object, props) {
9749
if (object == null) {
9750
return {};
9751
}
9752
if (typeof props[0] != 'function') {
9753
var props = arrayMap(baseFlatten(props), String);
9754
return pickByArray(object, baseDifference(keysIn(object), props));
9755
}
9756
var predicate = bindCallback(props[0], props[1], 3);
9757
return pickByCallback(object, function(value, key, object) {
9758
return !predicate(value, key, object);
9759
});
9760
});
9761
9762
/**
9763
* Creates a two dimensional array of the key-value pairs for `object`,
9764
* e.g. `[[key1, value1], [key2, value2]]`.
9765
*
9766
* @static
9767
* @memberOf _
9768
* @category Object
9769
* @param {Object} object The object to query.
9770
* @returns {Array} Returns the new array of key-value pairs.
9771
* @example
9772
*
9773
* _.pairs({ 'barney': 36, 'fred': 40 });
9774
* // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
9775
*/
9776
function pairs(object) {
9777
object = toObject(object);
9778
9779
var index = -1,
9780
props = keys(object),
9781
length = props.length,
9782
result = Array(length);
9783
9784
while (++index < length) {
9785
var key = props[index];
9786
result[index] = [key, object[key]];
9787
}
9788
return result;
9789
}
9790
9791
/**
9792
* Creates an object composed of the picked `object` properties. Property
9793
* names may be specified as individual arguments or as arrays of property
9794
* names. If `predicate` is provided it is invoked for each property of `object`
9795
* picking the properties `predicate` returns truthy for. The predicate is
9796
* bound to `thisArg` and invoked with three arguments: (value, key, object).
9797
*
9798
* @static
9799
* @memberOf _
9800
* @category Object
9801
* @param {Object} object The source object.
9802
* @param {Function|...(string|string[])} [predicate] The function invoked per
9803
* iteration or property names to pick, specified as individual property
9804
* names or arrays of property names.
9805
* @param {*} [thisArg] The `this` binding of `predicate`.
9806
* @returns {Object} Returns the new object.
9807
* @example
9808
*
9809
* var object = { 'user': 'fred', 'age': 40 };
9810
*
9811
* _.pick(object, 'user');
9812
* // => { 'user': 'fred' }
9813
*
9814
* _.pick(object, _.isString);
9815
* // => { 'user': 'fred' }
9816
*/
9817
var pick = restParam(function(object, props) {
9818
if (object == null) {
9819
return {};
9820
}
9821
return typeof props[0] == 'function'
9822
? pickByCallback(object, bindCallback(props[0], props[1], 3))
9823
: pickByArray(object, baseFlatten(props));
9824
});
9825
9826
/**
9827
* This method is like `_.get` except that if the resolved value is a function
9828
* it is invoked with the `this` binding of its parent object and its result
9829
* is returned.
9830
*
9831
* @static
9832
* @memberOf _
9833
* @category Object
9834
* @param {Object} object The object to query.
9835
* @param {Array|string} path The path of the property to resolve.
9836
* @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
9837
* @returns {*} Returns the resolved value.
9838
* @example
9839
*
9840
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
9841
*
9842
* _.result(object, 'a[0].b.c1');
9843
* // => 3
9844
*
9845
* _.result(object, 'a[0].b.c2');
9846
* // => 4
9847
*
9848
* _.result(object, 'a.b.c', 'default');
9849
* // => 'default'
9850
*
9851
* _.result(object, 'a.b.c', _.constant('default'));
9852
* // => 'default'
9853
*/
9854
function result(object, path, defaultValue) {
9855
var result = object == null ? undefined : object[path];
9856
if (result === undefined) {
9857
if (object != null && !isKey(path, object)) {
9858
path = toPath(path);
9859
object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
9860
result = object == null ? undefined : object[last(path)];
9861
}
9862
result = result === undefined ? defaultValue : result;
9863
}
9864
return isFunction(result) ? result.call(object) : result;
9865
}
9866
9867
/**
9868
* Sets the property value of `path` on `object`. If a portion of `path`
9869
* does not exist it is created.
9870
*
9871
* @static
9872
* @memberOf _
9873
* @category Object
9874
* @param {Object} object The object to augment.
9875
* @param {Array|string} path The path of the property to set.
9876
* @param {*} value The value to set.
9877
* @returns {Object} Returns `object`.
9878
* @example
9879
*
9880
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
9881
*
9882
* _.set(object, 'a[0].b.c', 4);
9883
* console.log(object.a[0].b.c);
9884
* // => 4
9885
*
9886
* _.set(object, 'x[0].y.z', 5);
9887
* console.log(object.x[0].y.z);
9888
* // => 5
9889
*/
9890
function set(object, path, value) {
9891
if (object == null) {
9892
return object;
9893
}
9894
var pathKey = (path + '');
9895
path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
9896
9897
var index = -1,
9898
length = path.length,
9899
lastIndex = length - 1,
9900
nested = object;
9901
9902
while (nested != null && ++index < length) {
9903
var key = path[index];
9904
if (isObject(nested)) {
9905
if (index == lastIndex) {
9906
nested[key] = value;
9907
} else if (nested[key] == null) {
9908
nested[key] = isIndex(path[index + 1]) ? [] : {};
9909
}
9910
}
9911
nested = nested[key];
9912
}
9913
return object;
9914
}
9915
9916
/**
9917
* An alternative to `_.reduce`; this method transforms `object` to a new
9918
* `accumulator` object which is the result of running each of its own enumerable
9919
* properties through `iteratee`, with each invocation potentially mutating
9920
* the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
9921
* with four arguments: (accumulator, value, key, object). Iteratee functions
9922
* may exit iteration early by explicitly returning `false`.
9923
*
9924
* @static
9925
* @memberOf _
9926
* @category Object
9927
* @param {Array|Object} object The object to iterate over.
9928
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
9929
* @param {*} [accumulator] The custom accumulator value.
9930
* @param {*} [thisArg] The `this` binding of `iteratee`.
9931
* @returns {*} Returns the accumulated value.
9932
* @example
9933
*
9934
* _.transform([2, 3, 4], function(result, n) {
9935
* result.push(n *= n);
9936
* return n % 2 == 0;
9937
* });
9938
* // => [4, 9]
9939
*
9940
* _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
9941
* result[key] = n * 3;
9942
* });
9943
* // => { 'a': 3, 'b': 6 }
9944
*/
9945
function transform(object, iteratee, accumulator, thisArg) {
9946
var isArr = isArray(object) || isTypedArray(object);
9947
iteratee = getCallback(iteratee, thisArg, 4);
9948
9949
if (accumulator == null) {
9950
if (isArr || isObject(object)) {
9951
var Ctor = object.constructor;
9952
if (isArr) {
9953
accumulator = isArray(object) ? new Ctor : [];
9954
} else {
9955
accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : null);
9956
}
9957
} else {
9958
accumulator = {};
9959
}
9960
}
9961
(isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
9962
return iteratee(accumulator, value, index, object);
9963
});
9964
return accumulator;
9965
}
9966
9967
/**
9968
* Creates an array of the own enumerable property values of `object`.
9969
*
9970
* **Note:** Non-object values are coerced to objects.
9971
*
9972
* @static
9973
* @memberOf _
9974
* @category Object
9975
* @param {Object} object The object to query.
9976
* @returns {Array} Returns the array of property values.
9977
* @example
9978
*
9979
* function Foo() {
9980
* this.a = 1;
9981
* this.b = 2;
9982
* }
9983
*
9984
* Foo.prototype.c = 3;
9985
*
9986
* _.values(new Foo);
9987
* // => [1, 2] (iteration order is not guaranteed)
9988
*
9989
* _.values('hi');
9990
* // => ['h', 'i']
9991
*/
9992
function values(object) {
9993
return baseValues(object, keys(object));
9994
}
9995
9996
/**
9997
* Creates an array of the own and inherited enumerable property values
9998
* of `object`.
9999
*
10000
* **Note:** Non-object values are coerced to objects.
10001
*
10002
* @static
10003
* @memberOf _
10004
* @category Object
10005
* @param {Object} object The object to query.
10006
* @returns {Array} Returns the array of property values.
10007
* @example
10008
*
10009
* function Foo() {
10010
* this.a = 1;
10011
* this.b = 2;
10012
* }
10013
*
10014
* Foo.prototype.c = 3;
10015
*
10016
* _.valuesIn(new Foo);
10017
* // => [1, 2, 3] (iteration order is not guaranteed)
10018
*/
10019
function valuesIn(object) {
10020
return baseValues(object, keysIn(object));
10021
}
10022
10023
/*------------------------------------------------------------------------*/
10024
10025
/**
10026
* Checks if `n` is between `start` and up to but not including, `end`. If
10027
* `end` is not specified it is set to `start` with `start` then set to `0`.
10028
*
10029
* @static
10030
* @memberOf _
10031
* @category Number
10032
* @param {number} n The number to check.
10033
* @param {number} [start=0] The start of the range.
10034
* @param {number} end The end of the range.
10035
* @returns {boolean} Returns `true` if `n` is in the range, else `false`.
10036
* @example
10037
*
10038
* _.inRange(3, 2, 4);
10039
* // => true
10040
*
10041
* _.inRange(4, 8);
10042
* // => true
10043
*
10044
* _.inRange(4, 2);
10045
* // => false
10046
*
10047
* _.inRange(2, 2);
10048
* // => false
10049
*
10050
* _.inRange(1.2, 2);
10051
* // => true
10052
*
10053
* _.inRange(5.2, 4);
10054
* // => false
10055
*/
10056
function inRange(value, start, end) {
10057
start = +start || 0;
10058
if (typeof end === 'undefined') {
10059
end = start;
10060
start = 0;
10061
} else {
10062
end = +end || 0;
10063
}
10064
return value >= nativeMin(start, end) && value < nativeMax(start, end);
10065
}
10066
10067
/**
10068
* Produces a random number between `min` and `max` (inclusive). If only one
10069
* argument is provided a number between `0` and the given number is returned.
10070
* If `floating` is `true`, or either `min` or `max` are floats, a floating-point
10071
* number is returned instead of an integer.
10072
*
10073
* @static
10074
* @memberOf _
10075
* @category Number
10076
* @param {number} [min=0] The minimum possible value.
10077
* @param {number} [max=1] The maximum possible value.
10078
* @param {boolean} [floating] Specify returning a floating-point number.
10079
* @returns {number} Returns the random number.
10080
* @example
10081
*
10082
* _.random(0, 5);
10083
* // => an integer between 0 and 5
10084
*
10085
* _.random(5);
10086
* // => also an integer between 0 and 5
10087
*
10088
* _.random(5, true);
10089
* // => a floating-point number between 0 and 5
10090
*
10091
* _.random(1.2, 5.2);
10092
* // => a floating-point number between 1.2 and 5.2
10093
*/
10094
function random(min, max, floating) {
10095
if (floating && isIterateeCall(min, max, floating)) {
10096
max = floating = null;
10097
}
10098
var noMin = min == null,
10099
noMax = max == null;
10100
10101
if (floating == null) {
10102
if (noMax && typeof min == 'boolean') {
10103
floating = min;
10104
min = 1;
10105
}
10106
else if (typeof max == 'boolean') {
10107
floating = max;
10108
noMax = true;
10109
}
10110
}
10111
if (noMin && noMax) {
10112
max = 1;
10113
noMax = false;
10114
}
10115
min = +min || 0;
10116
if (noMax) {
10117
max = min;
10118
min = 0;
10119
} else {
10120
max = +max || 0;
10121
}
10122
if (floating || min % 1 || max % 1) {
10123
var rand = nativeRandom();
10124
return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
10125
}
10126
return baseRandom(min, max);
10127
}
10128
10129
/*------------------------------------------------------------------------*/
10130
10131
/**
10132
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
10133
*
10134
* @static
10135
* @memberOf _
10136
* @category String
10137
* @param {string} [string=''] The string to convert.
10138
* @returns {string} Returns the camel cased string.
10139
* @example
10140
*
10141
* _.camelCase('Foo Bar');
10142
* // => 'fooBar'
10143
*
10144
* _.camelCase('--foo-bar');
10145
* // => 'fooBar'
10146
*
10147
* _.camelCase('__foo_bar__');
10148
* // => 'fooBar'
10149
*/
10150
var camelCase = createCompounder(function(result, word, index) {
10151
word = word.toLowerCase();
10152
return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);
10153
});
10154
10155
/**
10156
* Capitalizes the first character of `string`.
10157
*
10158
* @static
10159
* @memberOf _
10160
* @category String
10161
* @param {string} [string=''] The string to capitalize.
10162
* @returns {string} Returns the capitalized string.
10163
* @example
10164
*
10165
* _.capitalize('fred');
10166
* // => 'Fred'
10167
*/
10168
function capitalize(string) {
10169
string = baseToString(string);
10170
return string && (string.charAt(0).toUpperCase() + string.slice(1));
10171
}
10172
10173
/**
10174
* Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
10175
* to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
10176
*
10177
* @static
10178
* @memberOf _
10179
* @category String
10180
* @param {string} [string=''] The string to deburr.
10181
* @returns {string} Returns the deburred string.
10182
* @example
10183
*
10184
* _.deburr('déjà vu');
10185
* // => 'deja vu'
10186
*/
10187
function deburr(string) {
10188
string = baseToString(string);
10189
return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
10190
}
10191
10192
/**
10193
* Checks if `string` ends with the given target string.
10194
*
10195
* @static
10196
* @memberOf _
10197
* @category String
10198
* @param {string} [string=''] The string to search.
10199
* @param {string} [target] The string to search for.
10200
* @param {number} [position=string.length] The position to search from.
10201
* @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
10202
* @example
10203
*
10204
* _.endsWith('abc', 'c');
10205
* // => true
10206
*
10207
* _.endsWith('abc', 'b');
10208
* // => false
10209
*
10210
* _.endsWith('abc', 'b', 2);
10211
* // => true
10212
*/
10213
function endsWith(string, target, position) {
10214
string = baseToString(string);
10215
target = (target + '');
10216
10217
var length = string.length;
10218
position = position === undefined
10219
? length
10220
: nativeMin(position < 0 ? 0 : (+position || 0), length);
10221
10222
position -= target.length;
10223
return position >= 0 && string.indexOf(target, position) == position;
10224
}
10225
10226
/**
10227
* Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
10228
* their corresponding HTML entities.
10229
*
10230
* **Note:** No other characters are escaped. To escape additional characters
10231
* use a third-party library like [_he_](https://mths.be/he).
10232
*
10233
* Though the ">" character is escaped for symmetry, characters like
10234
* ">" and "/" don't need escaping in HTML and have no special meaning
10235
* unless they're part of a tag or unquoted attribute value.
10236
* See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
10237
* (under "semi-related fun fact") for more details.
10238
*
10239
* Backticks are escaped because in Internet Explorer < 9, they can break out
10240
* of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
10241
* [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
10242
* [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
10243
* for more details.
10244
*
10245
* When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
10246
* to reduce XSS vectors.
10247
*
10248
* @static
10249
* @memberOf _
10250
* @category String
10251
* @param {string} [string=''] The string to escape.
10252
* @returns {string} Returns the escaped string.
10253
* @example
10254
*
10255
* _.escape('fred, barney, & pebbles');
10256
* // => 'fred, barney, &amp; pebbles'
10257
*/
10258
function escape(string) {
10259
// Reset `lastIndex` because in IE < 9 `String#replace` does not.
10260
string = baseToString(string);
10261
return (string && reHasUnescapedHtml.test(string))
10262
? string.replace(reUnescapedHtml, escapeHtmlChar)
10263
: string;
10264
}
10265
10266
/**
10267
* Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
10268
* "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
10269
*
10270
* @static
10271
* @memberOf _
10272
* @category String
10273
* @param {string} [string=''] The string to escape.
10274
* @returns {string} Returns the escaped string.
10275
* @example
10276
*
10277
* _.escapeRegExp('[lodash](https://lodash.com/)');
10278
* // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
10279
*/
10280
function escapeRegExp(string) {
10281
string = baseToString(string);
10282
return (string && reHasRegExpChars.test(string))
10283
? string.replace(reRegExpChars, '\\$&')
10284
: string;
10285
}
10286
10287
/**
10288
* Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
10289
*
10290
* @static
10291
* @memberOf _
10292
* @category String
10293
* @param {string} [string=''] The string to convert.
10294
* @returns {string} Returns the kebab cased string.
10295
* @example
10296
*
10297
* _.kebabCase('Foo Bar');
10298
* // => 'foo-bar'
10299
*
10300
* _.kebabCase('fooBar');
10301
* // => 'foo-bar'
10302
*
10303
* _.kebabCase('__foo_bar__');
10304
* // => 'foo-bar'
10305
*/
10306
var kebabCase = createCompounder(function(result, word, index) {
10307
return result + (index ? '-' : '') + word.toLowerCase();
10308
});
10309
10310
/**
10311
* Pads `string` on the left and right sides if it's shorter than `length`.
10312
* Padding characters are truncated if they can't be evenly divided by `length`.
10313
*
10314
* @static
10315
* @memberOf _
10316
* @category String
10317
* @param {string} [string=''] The string to pad.
10318
* @param {number} [length=0] The padding length.
10319
* @param {string} [chars=' '] The string used as padding.
10320
* @returns {string} Returns the padded string.
10321
* @example
10322
*
10323
* _.pad('abc', 8);
10324
* // => ' abc '
10325
*
10326
* _.pad('abc', 8, '_-');
10327
* // => '_-abc_-_'
10328
*
10329
* _.pad('abc', 3);
10330
* // => 'abc'
10331
*/
10332
function pad(string, length, chars) {
10333
string = baseToString(string);
10334
length = +length;
10335
10336
var strLength = string.length;
10337
if (strLength >= length || !nativeIsFinite(length)) {
10338
return string;
10339
}
10340
var mid = (length - strLength) / 2,
10341
leftLength = floor(mid),
10342
rightLength = ceil(mid);
10343
10344
chars = createPadding('', rightLength, chars);
10345
return chars.slice(0, leftLength) + string + chars;
10346
}
10347
10348
/**
10349
* Pads `string` on the left side if it's shorter than `length`. Padding
10350
* characters are truncated if they exceed `length`.
10351
*
10352
* @static
10353
* @memberOf _
10354
* @category String
10355
* @param {string} [string=''] The string to pad.
10356
* @param {number} [length=0] The padding length.
10357
* @param {string} [chars=' '] The string used as padding.
10358
* @returns {string} Returns the padded string.
10359
* @example
10360
*
10361
* _.padLeft('abc', 6);
10362
* // => ' abc'
10363
*
10364
* _.padLeft('abc', 6, '_-');
10365
* // => '_-_abc'
10366
*
10367
* _.padLeft('abc', 3);
10368
* // => 'abc'
10369
*/
10370
var padLeft = createPadDir();
10371
10372
/**
10373
* Pads `string` on the right side if it's shorter than `length`. Padding
10374
* characters are truncated if they exceed `length`.
10375
*
10376
* @static
10377
* @memberOf _
10378
* @category String
10379
* @param {string} [string=''] The string to pad.
10380
* @param {number} [length=0] The padding length.
10381
* @param {string} [chars=' '] The string used as padding.
10382
* @returns {string} Returns the padded string.
10383
* @example
10384
*
10385
* _.padRight('abc', 6);
10386
* // => 'abc '
10387
*
10388
* _.padRight('abc', 6, '_-');
10389
* // => 'abc_-_'
10390
*
10391
* _.padRight('abc', 3);
10392
* // => 'abc'
10393
*/
10394
var padRight = createPadDir(true);
10395
10396
/**
10397
* Converts `string` to an integer of the specified radix. If `radix` is
10398
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
10399
* in which case a `radix` of `16` is used.
10400
*
10401
* **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
10402
* of `parseInt`.
10403
*
10404
* @static
10405
* @memberOf _
10406
* @category String
10407
* @param {string} string The string to convert.
10408
* @param {number} [radix] The radix to interpret `value` by.
10409
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
10410
* @returns {number} Returns the converted integer.
10411
* @example
10412
*
10413
* _.parseInt('08');
10414
* // => 8
10415
*
10416
* _.map(['6', '08', '10'], _.parseInt);
10417
* // => [6, 8, 10]
10418
*/
10419
function parseInt(string, radix, guard) {
10420
if (guard && isIterateeCall(string, radix, guard)) {
10421
radix = 0;
10422
}
10423
return nativeParseInt(string, radix);
10424
}
10425
// Fallback for environments with pre-ES5 implementations.
10426
if (nativeParseInt(whitespace + '08') != 8) {
10427
parseInt = function(string, radix, guard) {
10428
// Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
10429
// Chrome fails to trim leading <BOM> whitespace characters.
10430
// See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
10431
if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
10432
radix = 0;
10433
} else if (radix) {
10434
radix = +radix;
10435
}
10436
string = trim(string);
10437
return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
10438
};
10439
}
10440
10441
/**
10442
* Repeats the given string `n` times.
10443
*
10444
* @static
10445
* @memberOf _
10446
* @category String
10447
* @param {string} [string=''] The string to repeat.
10448
* @param {number} [n=0] The number of times to repeat the string.
10449
* @returns {string} Returns the repeated string.
10450
* @example
10451
*
10452
* _.repeat('*', 3);
10453
* // => '***'
10454
*
10455
* _.repeat('abc', 2);
10456
* // => 'abcabc'
10457
*
10458
* _.repeat('abc', 0);
10459
* // => ''
10460
*/
10461
function repeat(string, n) {
10462
var result = '';
10463
string = baseToString(string);
10464
n = +n;
10465
if (n < 1 || !string || !nativeIsFinite(n)) {
10466
return result;
10467
}
10468
// Leverage the exponentiation by squaring algorithm for a faster repeat.
10469
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
10470
do {
10471
if (n % 2) {
10472
result += string;
10473
}
10474
n = floor(n / 2);
10475
string += string;
10476
} while (n);
10477
10478
return result;
10479
}
10480
10481
/**
10482
* Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
10483
*
10484
* @static
10485
* @memberOf _
10486
* @category String
10487
* @param {string} [string=''] The string to convert.
10488
* @returns {string} Returns the snake cased string.
10489
* @example
10490
*
10491
* _.snakeCase('Foo Bar');
10492
* // => 'foo_bar'
10493
*
10494
* _.snakeCase('fooBar');
10495
* // => 'foo_bar'
10496
*
10497
* _.snakeCase('--foo-bar');
10498
* // => 'foo_bar'
10499
*/
10500
var snakeCase = createCompounder(function(result, word, index) {
10501
return result + (index ? '_' : '') + word.toLowerCase();
10502
});
10503
10504
/**
10505
* Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
10506
*
10507
* @static
10508
* @memberOf _
10509
* @category String
10510
* @param {string} [string=''] The string to convert.
10511
* @returns {string} Returns the start cased string.
10512
* @example
10513
*
10514
* _.startCase('--foo-bar');
10515
* // => 'Foo Bar'
10516
*
10517
* _.startCase('fooBar');
10518
* // => 'Foo Bar'
10519
*
10520
* _.startCase('__foo_bar__');
10521
* // => 'Foo Bar'
10522
*/
10523
var startCase = createCompounder(function(result, word, index) {
10524
return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
10525
});
10526
10527
/**
10528
* Checks if `string` starts with the given target string.
10529
*
10530
* @static
10531
* @memberOf _
10532
* @category String
10533
* @param {string} [string=''] The string to search.
10534
* @param {string} [target] The string to search for.
10535
* @param {number} [position=0] The position to search from.
10536
* @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
10537
* @example
10538
*
10539
* _.startsWith('abc', 'a');
10540
* // => true
10541
*
10542
* _.startsWith('abc', 'b');
10543
* // => false
10544
*
10545
* _.startsWith('abc', 'b', 1);
10546
* // => true
10547
*/
10548
function startsWith(string, target, position) {
10549
string = baseToString(string);
10550
position = position == null
10551
? 0
10552
: nativeMin(position < 0 ? 0 : (+position || 0), string.length);
10553
10554
return string.lastIndexOf(target, position) == position;
10555
}
10556
10557
/**
10558
* Creates a compiled template function that can interpolate data properties
10559
* in "interpolate" delimiters, HTML-escape interpolated data properties in
10560
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
10561
* properties may be accessed as free variables in the template. If a setting
10562
* object is provided it takes precedence over `_.templateSettings` values.
10563
*
10564
* **Note:** In the development build `_.template` utilizes
10565
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
10566
* for easier debugging.
10567
*
10568
* For more information on precompiling templates see
10569
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
10570
*
10571
* For more information on Chrome extension sandboxes see
10572
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
10573
*
10574
* @static
10575
* @memberOf _
10576
* @category String
10577
* @param {string} [string=''] The template string.
10578
* @param {Object} [options] The options object.
10579
* @param {RegExp} [options.escape] The HTML "escape" delimiter.
10580
* @param {RegExp} [options.evaluate] The "evaluate" delimiter.
10581
* @param {Object} [options.imports] An object to import into the template as free variables.
10582
* @param {RegExp} [options.interpolate] The "interpolate" delimiter.
10583
* @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
10584
* @param {string} [options.variable] The data object variable name.
10585
* @param- {Object} [otherOptions] Enables the legacy `options` param signature.
10586
* @returns {Function} Returns the compiled template function.
10587
* @example
10588
*
10589
* // using the "interpolate" delimiter to create a compiled template
10590
* var compiled = _.template('hello <%= user %>!');
10591
* compiled({ 'user': 'fred' });
10592
* // => 'hello fred!'
10593
*
10594
* // using the HTML "escape" delimiter to escape data property values
10595
* var compiled = _.template('<b><%- value %></b>');
10596
* compiled({ 'value': '<script>' });
10597
* // => '<b>&lt;script&gt;</b>'
10598
*
10599
* // using the "evaluate" delimiter to execute JavaScript and generate HTML
10600
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
10601
* compiled({ 'users': ['fred', 'barney'] });
10602
* // => '<li>fred</li><li>barney</li>'
10603
*
10604
* // using the internal `print` function in "evaluate" delimiters
10605
* var compiled = _.template('<% print("hello " + user); %>!');
10606
* compiled({ 'user': 'barney' });
10607
* // => 'hello barney!'
10608
*
10609
* // using the ES delimiter as an alternative to the default "interpolate" delimiter
10610
* var compiled = _.template('hello ${ user }!');
10611
* compiled({ 'user': 'pebbles' });
10612
* // => 'hello pebbles!'
10613
*
10614
* // using custom template delimiters
10615
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
10616
* var compiled = _.template('hello {{ user }}!');
10617
* compiled({ 'user': 'mustache' });
10618
* // => 'hello mustache!'
10619
*
10620
* // using backslashes to treat delimiters as plain text
10621
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
10622
* compiled({ 'value': 'ignored' });
10623
* // => '<%- value %>'
10624
*
10625
* // using the `imports` option to import `jQuery` as `jq`
10626
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
10627
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
10628
* compiled({ 'users': ['fred', 'barney'] });
10629
* // => '<li>fred</li><li>barney</li>'
10630
*
10631
* // using the `sourceURL` option to specify a custom sourceURL for the template
10632
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
10633
* compiled(data);
10634
* // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
10635
*
10636
* // using the `variable` option to ensure a with-statement isn't used in the compiled template
10637
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
10638
* compiled.source;
10639
* // => function(data) {
10640
* // var __t, __p = '';
10641
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
10642
* // return __p;
10643
* // }
10644
*
10645
* // using the `source` property to inline compiled templates for meaningful
10646
* // line numbers in error messages and a stack trace
10647
* fs.writeFileSync(path.join(cwd, 'jst.js'), '\
10648
* var JST = {\
10649
* "main": ' + _.template(mainText).source + '\
10650
* };\
10651
* ');
10652
*/
10653
function template(string, options, otherOptions) {
10654
// Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
10655
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
10656
var settings = lodash.templateSettings;
10657
10658
if (otherOptions && isIterateeCall(string, options, otherOptions)) {
10659
options = otherOptions = null;
10660
}
10661
string = baseToString(string);
10662
options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
10663
10664
var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
10665
importsKeys = keys(imports),
10666
importsValues = baseValues(imports, importsKeys);
10667
10668
var isEscaping,
10669
isEvaluating,
10670
index = 0,
10671
interpolate = options.interpolate || reNoMatch,
10672
source = "__p += '";
10673
10674
// Compile the regexp to match each delimiter.
10675
var reDelimiters = RegExp(
10676
(options.escape || reNoMatch).source + '|' +
10677
interpolate.source + '|' +
10678
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
10679
(options.evaluate || reNoMatch).source + '|$'
10680
, 'g');
10681
10682
// Use a sourceURL for easier debugging.
10683
var sourceURL = '//# sourceURL=' +
10684
('sourceURL' in options
10685
? options.sourceURL
10686
: ('lodash.templateSources[' + (++templateCounter) + ']')
10687
) + '\n';
10688
10689
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
10690
interpolateValue || (interpolateValue = esTemplateValue);
10691
10692
// Escape characters that can't be included in string literals.
10693
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
10694
10695
// Replace delimiters with snippets.
10696
if (escapeValue) {
10697
isEscaping = true;
10698
source += "' +\n__e(" + escapeValue + ") +\n'";
10699
}
10700
if (evaluateValue) {
10701
isEvaluating = true;
10702
source += "';\n" + evaluateValue + ";\n__p += '";
10703
}
10704
if (interpolateValue) {
10705
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
10706
}
10707
index = offset + match.length;
10708
10709
// The JS engine embedded in Adobe products requires returning the `match`
10710
// string in order to produce the correct `offset` value.
10711
return match;
10712
});
10713
10714
source += "';\n";
10715
10716
// If `variable` is not specified wrap a with-statement around the generated
10717
// code to add the data object to the top of the scope chain.
10718
var variable = options.variable;
10719
if (!variable) {
10720
source = 'with (obj) {\n' + source + '\n}\n';
10721
}
10722
// Cleanup code by stripping empty strings.
10723
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
10724
.replace(reEmptyStringMiddle, '$1')
10725
.replace(reEmptyStringTrailing, '$1;');
10726
10727
// Frame code as the function body.
10728
source = 'function(' + (variable || 'obj') + ') {\n' +
10729
(variable
10730
? ''
10731
: 'obj || (obj = {});\n'
10732
) +
10733
"var __t, __p = ''" +
10734
(isEscaping
10735
? ', __e = _.escape'
10736
: ''
10737
) +
10738
(isEvaluating
10739
? ', __j = Array.prototype.join;\n' +
10740
"function print() { __p += __j.call(arguments, '') }\n"
10741
: ';\n'
10742
) +
10743
source +
10744
'return __p\n}';
10745
10746
var result = attempt(function() {
10747
return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
10748
});
10749
10750
// Provide the compiled function's source by its `toString` method or
10751
// the `source` property as a convenience for inlining compiled templates.
10752
result.source = source;
10753
if (isError(result)) {
10754
throw result;
10755
}
10756
return result;
10757
}
10758
10759
/**
10760
* Removes leading and trailing whitespace or specified characters from `string`.
10761
*
10762
* @static
10763
* @memberOf _
10764
* @category String
10765
* @param {string} [string=''] The string to trim.
10766
* @param {string} [chars=whitespace] The characters to trim.
10767
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
10768
* @returns {string} Returns the trimmed string.
10769
* @example
10770
*
10771
* _.trim(' abc ');
10772
* // => 'abc'
10773
*
10774
* _.trim('-_-abc-_-', '_-');
10775
* // => 'abc'
10776
*
10777
* _.map([' foo ', ' bar '], _.trim);
10778
* // => ['foo', 'bar']
10779
*/
10780
function trim(string, chars, guard) {
10781
var value = string;
10782
string = baseToString(string);
10783
if (!string) {
10784
return string;
10785
}
10786
if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
10787
return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
10788
}
10789
chars = (chars + '');
10790
return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
10791
}
10792
10793
/**
10794
* Removes leading whitespace or specified characters from `string`.
10795
*
10796
* @static
10797
* @memberOf _
10798
* @category String
10799
* @param {string} [string=''] The string to trim.
10800
* @param {string} [chars=whitespace] The characters to trim.
10801
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
10802
* @returns {string} Returns the trimmed string.
10803
* @example
10804
*
10805
* _.trimLeft(' abc ');
10806
* // => 'abc '
10807
*
10808
* _.trimLeft('-_-abc-_-', '_-');
10809
* // => 'abc-_-'
10810
*/
10811
function trimLeft(string, chars, guard) {
10812
var value = string;
10813
string = baseToString(string);
10814
if (!string) {
10815
return string;
10816
}
10817
if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
10818
return string.slice(trimmedLeftIndex(string));
10819
}
10820
return string.slice(charsLeftIndex(string, (chars + '')));
10821
}
10822
10823
/**
10824
* Removes trailing whitespace or specified characters from `string`.
10825
*
10826
* @static
10827
* @memberOf _
10828
* @category String
10829
* @param {string} [string=''] The string to trim.
10830
* @param {string} [chars=whitespace] The characters to trim.
10831
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
10832
* @returns {string} Returns the trimmed string.
10833
* @example
10834
*
10835
* _.trimRight(' abc ');
10836
* // => ' abc'
10837
*
10838
* _.trimRight('-_-abc-_-', '_-');
10839
* // => '-_-abc'
10840
*/
10841
function trimRight(string, chars, guard) {
10842
var value = string;
10843
string = baseToString(string);
10844
if (!string) {
10845
return string;
10846
}
10847
if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
10848
return string.slice(0, trimmedRightIndex(string) + 1);
10849
}
10850
return string.slice(0, charsRightIndex(string, (chars + '')) + 1);
10851
}
10852
10853
/**
10854
* Truncates `string` if it's longer than the given maximum string length.
10855
* The last characters of the truncated string are replaced with the omission
10856
* string which defaults to "...".
10857
*
10858
* @static
10859
* @memberOf _
10860
* @category String
10861
* @param {string} [string=''] The string to truncate.
10862
* @param {Object|number} [options] The options object or maximum string length.
10863
* @param {number} [options.length=30] The maximum string length.
10864
* @param {string} [options.omission='...'] The string to indicate text is omitted.
10865
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
10866
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
10867
* @returns {string} Returns the truncated string.
10868
* @example
10869
*
10870
* _.trunc('hi-diddly-ho there, neighborino');
10871
* // => 'hi-diddly-ho there, neighbo...'
10872
*
10873
* _.trunc('hi-diddly-ho there, neighborino', 24);
10874
* // => 'hi-diddly-ho there, n...'
10875
*
10876
* _.trunc('hi-diddly-ho there, neighborino', {
10877
* 'length': 24,
10878
* 'separator': ' '
10879
* });
10880
* // => 'hi-diddly-ho there,...'
10881
*
10882
* _.trunc('hi-diddly-ho there, neighborino', {
10883
* 'length': 24,
10884
* 'separator': /,? +/
10885
* });
10886
* // => 'hi-diddly-ho there...'
10887
*
10888
* _.trunc('hi-diddly-ho there, neighborino', {
10889
* 'omission': ' [...]'
10890
* });
10891
* // => 'hi-diddly-ho there, neig [...]'
10892
*/
10893
function trunc(string, options, guard) {
10894
if (guard && isIterateeCall(string, options, guard)) {
10895
options = null;
10896
}
10897
var length = DEFAULT_TRUNC_LENGTH,
10898
omission = DEFAULT_TRUNC_OMISSION;
10899
10900
if (options != null) {
10901
if (isObject(options)) {
10902
var separator = 'separator' in options ? options.separator : separator;
10903
length = 'length' in options ? (+options.length || 0) : length;
10904
omission = 'omission' in options ? baseToString(options.omission) : omission;
10905
} else {
10906
length = +options || 0;
10907
}
10908
}
10909
string = baseToString(string);
10910
if (length >= string.length) {
10911
return string;
10912
}
10913
var end = length - omission.length;
10914
if (end < 1) {
10915
return omission;
10916
}
10917
var result = string.slice(0, end);
10918
if (separator == null) {
10919
return result + omission;
10920
}
10921
if (isRegExp(separator)) {
10922
if (string.slice(end).search(separator)) {
10923
var match,
10924
newEnd,
10925
substring = string.slice(0, end);
10926
10927
if (!separator.global) {
10928
separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
10929
}
10930
separator.lastIndex = 0;
10931
while ((match = separator.exec(substring))) {
10932
newEnd = match.index;
10933
}
10934
result = result.slice(0, newEnd == null ? end : newEnd);
10935
}
10936
} else if (string.indexOf(separator, end) != end) {
10937
var index = result.lastIndexOf(separator);
10938
if (index > -1) {
10939
result = result.slice(0, index);
10940
}
10941
}
10942
return result + omission;
10943
}
10944
10945
/**
10946
* The inverse of `_.escape`; this method converts the HTML entities
10947
* `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to their
10948
* corresponding characters.
10949
*
10950
* **Note:** No other HTML entities are unescaped. To unescape additional HTML
10951
* entities use a third-party library like [_he_](https://mths.be/he).
10952
*
10953
* @static
10954
* @memberOf _
10955
* @category String
10956
* @param {string} [string=''] The string to unescape.
10957
* @returns {string} Returns the unescaped string.
10958
* @example
10959
*
10960
* _.unescape('fred, barney, &amp; pebbles');
10961
* // => 'fred, barney, & pebbles'
10962
*/
10963
function unescape(string) {
10964
string = baseToString(string);
10965
return (string && reHasEscapedHtml.test(string))
10966
? string.replace(reEscapedHtml, unescapeHtmlChar)
10967
: string;
10968
}
10969
10970
/**
10971
* Splits `string` into an array of its words.
10972
*
10973
* @static
10974
* @memberOf _
10975
* @category String
10976
* @param {string} [string=''] The string to inspect.
10977
* @param {RegExp|string} [pattern] The pattern to match words.
10978
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
10979
* @returns {Array} Returns the words of `string`.
10980
* @example
10981
*
10982
* _.words('fred, barney, & pebbles');
10983
* // => ['fred', 'barney', 'pebbles']
10984
*
10985
* _.words('fred, barney, & pebbles', /[^, ]+/g);
10986
* // => ['fred', 'barney', '&', 'pebbles']
10987
*/
10988
function words(string, pattern, guard) {
10989
if (guard && isIterateeCall(string, pattern, guard)) {
10990
pattern = null;
10991
}
10992
string = baseToString(string);
10993
return string.match(pattern || reWords) || [];
10994
}
10995
10996
/*------------------------------------------------------------------------*/
10997
10998
/**
10999
* Attempts to invoke `func`, returning either the result or the caught error
11000
* object. Any additional arguments are provided to `func` when it is invoked.
11001
*
11002
* @static
11003
* @memberOf _
11004
* @category Utility
11005
* @param {Function} func The function to attempt.
11006
* @returns {*} Returns the `func` result or error object.
11007
* @example
11008
*
11009
* // avoid throwing errors for invalid selectors
11010
* var elements = _.attempt(function(selector) {
11011
* return document.querySelectorAll(selector);
11012
* }, '>_>');
11013
*
11014
* if (_.isError(elements)) {
11015
* elements = [];
11016
* }
11017
*/
11018
var attempt = restParam(function(func, args) {
11019
try {
11020
return func.apply(undefined, args);
11021
} catch(e) {
11022
return isError(e) ? e : new Error(e);
11023
}
11024
});
11025
11026
/**
11027
* Creates a function that invokes `func` with the `this` binding of `thisArg`
11028
* and arguments of the created function. If `func` is a property name the
11029
* created callback returns the property value for a given element. If `func`
11030
* is an object the created callback returns `true` for elements that contain
11031
* the equivalent object properties, otherwise it returns `false`.
11032
*
11033
* @static
11034
* @memberOf _
11035
* @alias iteratee
11036
* @category Utility
11037
* @param {*} [func=_.identity] The value to convert to a callback.
11038
* @param {*} [thisArg] The `this` binding of `func`.
11039
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
11040
* @returns {Function} Returns the callback.
11041
* @example
11042
*
11043
* var users = [
11044
* { 'user': 'barney', 'age': 36 },
11045
* { 'user': 'fred', 'age': 40 }
11046
* ];
11047
*
11048
* // wrap to create custom callback shorthands
11049
* _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
11050
* var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
11051
* if (!match) {
11052
* return callback(func, thisArg);
11053
* }
11054
* return function(object) {
11055
* return match[2] == 'gt'
11056
* ? object[match[1]] > match[3]
11057
* : object[match[1]] < match[3];
11058
* };
11059
* });
11060
*
11061
* _.filter(users, 'age__gt36');
11062
* // => [{ 'user': 'fred', 'age': 40 }]
11063
*/
11064
function callback(func, thisArg, guard) {
11065
if (guard && isIterateeCall(func, thisArg, guard)) {
11066
thisArg = null;
11067
}
11068
return isObjectLike(func)
11069
? matches(func)
11070
: baseCallback(func, thisArg);
11071
}
11072
11073
/**
11074
* Creates a function that returns `value`.
11075
*
11076
* @static
11077
* @memberOf _
11078
* @category Utility
11079
* @param {*} value The value to return from the new function.
11080
* @returns {Function} Returns the new function.
11081
* @example
11082
*
11083
* var object = { 'user': 'fred' };
11084
* var getter = _.constant(object);
11085
*
11086
* getter() === object;
11087
* // => true
11088
*/
11089
function constant(value) {
11090
return function() {
11091
return value;
11092
};
11093
}
11094
11095
/**
11096
* This method returns the first argument provided to it.
11097
*
11098
* @static
11099
* @memberOf _
11100
* @category Utility
11101
* @param {*} value Any value.
11102
* @returns {*} Returns `value`.
11103
* @example
11104
*
11105
* var object = { 'user': 'fred' };
11106
*
11107
* _.identity(object) === object;
11108
* // => true
11109
*/
11110
function identity(value) {
11111
return value;
11112
}
11113
11114
/**
11115
* Creates a function that performs a deep comparison between a given object
11116
* and `source`, returning `true` if the given object has equivalent property
11117
* values, else `false`.
11118
*
11119
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
11120
* numbers, `Object` objects, regexes, and strings. Objects are compared by
11121
* their own, not inherited, enumerable properties. For comparing a single
11122
* own or inherited property value see `_.matchesProperty`.
11123
*
11124
* @static
11125
* @memberOf _
11126
* @category Utility
11127
* @param {Object} source The object of property values to match.
11128
* @returns {Function} Returns the new function.
11129
* @example
11130
*
11131
* var users = [
11132
* { 'user': 'barney', 'age': 36, 'active': true },
11133
* { 'user': 'fred', 'age': 40, 'active': false }
11134
* ];
11135
*
11136
* _.filter(users, _.matches({ 'age': 40, 'active': false }));
11137
* // => [{ 'user': 'fred', 'age': 40, 'active': false }]
11138
*/
11139
function matches(source) {
11140
return baseMatches(baseClone(source, true));
11141
}
11142
11143
/**
11144
* Creates a function that compares the property value of `path` on a given
11145
* object to `value`.
11146
*
11147
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
11148
* numbers, `Object` objects, regexes, and strings. Objects are compared by
11149
* their own, not inherited, enumerable properties.
11150
*
11151
* @static
11152
* @memberOf _
11153
* @category Utility
11154
* @param {Array|string} path The path of the property to get.
11155
* @param {*} srcValue The value to match.
11156
* @returns {Function} Returns the new function.
11157
* @example
11158
*
11159
* var users = [
11160
* { 'user': 'barney' },
11161
* { 'user': 'fred' }
11162
* ];
11163
*
11164
* _.find(users, _.matchesProperty('user', 'fred'));
11165
* // => { 'user': 'fred' }
11166
*/
11167
function matchesProperty(path, srcValue) {
11168
return baseMatchesProperty(path, baseClone(srcValue, true));
11169
}
11170
11171
/**
11172
* Creates a function that invokes the method at `path` on a given object.
11173
* Any additional arguments are provided to the invoked method.
11174
*
11175
* @static
11176
* @memberOf _
11177
* @category Utility
11178
* @param {Array|string} path The path of the method to invoke.
11179
* @param {...*} [args] The arguments to invoke the method with.
11180
* @returns {Function} Returns the new function.
11181
* @example
11182
*
11183
* var objects = [
11184
* { 'a': { 'b': { 'c': _.constant(2) } } },
11185
* { 'a': { 'b': { 'c': _.constant(1) } } }
11186
* ];
11187
*
11188
* _.map(objects, _.method('a.b.c'));
11189
* // => [2, 1]
11190
*
11191
* _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
11192
* // => [1, 2]
11193
*/
11194
var method = restParam(function(path, args) {
11195
return function(object) {
11196
return invokePath(object, path, args);
11197
};
11198
});
11199
11200
/**
11201
* The opposite of `_.method`; this method creates a function that invokes
11202
* the method at a given path on `object`. Any additional arguments are
11203
* provided to the invoked method.
11204
*
11205
* @static
11206
* @memberOf _
11207
* @category Utility
11208
* @param {Object} object The object to query.
11209
* @param {...*} [args] The arguments to invoke the method with.
11210
* @returns {Function} Returns the new function.
11211
* @example
11212
*
11213
* var array = _.times(3, _.constant),
11214
* object = { 'a': array, 'b': array, 'c': array };
11215
*
11216
* _.map(['a[2]', 'c[0]'], _.methodOf(object));
11217
* // => [2, 0]
11218
*
11219
* _.map([['a', '2'], ['c', '0']], _.methodOf(object));
11220
* // => [2, 0]
11221
*/
11222
var methodOf = restParam(function(object, args) {
11223
return function(path) {
11224
return invokePath(object, path, args);
11225
};
11226
});
11227
11228
/**
11229
* Adds all own enumerable function properties of a source object to the
11230
* destination object. If `object` is a function then methods are added to
11231
* its prototype as well.
11232
*
11233
* **Note:** Use `_.runInContext` to create a pristine `lodash` function to
11234
* avoid conflicts caused by modifying the original.
11235
*
11236
* @static
11237
* @memberOf _
11238
* @category Utility
11239
* @param {Function|Object} [object=lodash] The destination object.
11240
* @param {Object} source The object of functions to add.
11241
* @param {Object} [options] The options object.
11242
* @param {boolean} [options.chain=true] Specify whether the functions added
11243
* are chainable.
11244
* @returns {Function|Object} Returns `object`.
11245
* @example
11246
*
11247
* function vowels(string) {
11248
* return _.filter(string, function(v) {
11249
* return /[aeiou]/i.test(v);
11250
* });
11251
* }
11252
*
11253
* _.mixin({ 'vowels': vowels });
11254
* _.vowels('fred');
11255
* // => ['e']
11256
*
11257
* _('fred').vowels().value();
11258
* // => ['e']
11259
*
11260
* _.mixin({ 'vowels': vowels }, { 'chain': false });
11261
* _('fred').vowels();
11262
* // => ['e']
11263
*/
11264
function mixin(object, source, options) {
11265
if (options == null) {
11266
var isObj = isObject(source),
11267
props = isObj ? keys(source) : null,
11268
methodNames = (props && props.length) ? baseFunctions(source, props) : null;
11269
11270
if (!(methodNames ? methodNames.length : isObj)) {
11271
methodNames = false;
11272
options = source;
11273
source = object;
11274
object = this;
11275
}
11276
}
11277
if (!methodNames) {
11278
methodNames = baseFunctions(source, keys(source));
11279
}
11280
var chain = true,
11281
index = -1,
11282
isFunc = isFunction(object),
11283
length = methodNames.length;
11284
11285
if (options === false) {
11286
chain = false;
11287
} else if (isObject(options) && 'chain' in options) {
11288
chain = options.chain;
11289
}
11290
while (++index < length) {
11291
var methodName = methodNames[index],
11292
func = source[methodName];
11293
11294
object[methodName] = func;
11295
if (isFunc) {
11296
object.prototype[methodName] = (function(func) {
11297
return function() {
11298
var chainAll = this.__chain__;
11299
if (chain || chainAll) {
11300
var result = object(this.__wrapped__),
11301
actions = result.__actions__ = arrayCopy(this.__actions__);
11302
11303
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
11304
result.__chain__ = chainAll;
11305
return result;
11306
}
11307
var args = [this.value()];
11308
push.apply(args, arguments);
11309
return func.apply(object, args);
11310
};
11311
}(func));
11312
}
11313
}
11314
return object;
11315
}
11316
11317
/**
11318
* Reverts the `_` variable to its previous value and returns a reference to
11319
* the `lodash` function.
11320
*
11321
* @static
11322
* @memberOf _
11323
* @category Utility
11324
* @returns {Function} Returns the `lodash` function.
11325
* @example
11326
*
11327
* var lodash = _.noConflict();
11328
*/
11329
function noConflict() {
11330
context._ = oldDash;
11331
return this;
11332
}
11333
11334
/**
11335
* A no-operation function that returns `undefined` regardless of the
11336
* arguments it receives.
11337
*
11338
* @static
11339
* @memberOf _
11340
* @category Utility
11341
* @example
11342
*
11343
* var object = { 'user': 'fred' };
11344
*
11345
* _.noop(object) === undefined;
11346
* // => true
11347
*/
11348
function noop() {
11349
// No operation performed.
11350
}
11351
11352
/**
11353
* Creates a function that returns the property value at `path` on a
11354
* given object.
11355
*
11356
* @static
11357
* @memberOf _
11358
* @category Utility
11359
* @param {Array|string} path The path of the property to get.
11360
* @returns {Function} Returns the new function.
11361
* @example
11362
*
11363
* var objects = [
11364
* { 'a': { 'b': { 'c': 2 } } },
11365
* { 'a': { 'b': { 'c': 1 } } }
11366
* ];
11367
*
11368
* _.map(objects, _.property('a.b.c'));
11369
* // => [2, 1]
11370
*
11371
* _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
11372
* // => [1, 2]
11373
*/
11374
function property(path) {
11375
return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
11376
}
11377
11378
/**
11379
* The opposite of `_.property`; this method creates a function that returns
11380
* the property value at a given path on `object`.
11381
*
11382
* @static
11383
* @memberOf _
11384
* @category Utility
11385
* @param {Object} object The object to query.
11386
* @returns {Function} Returns the new function.
11387
* @example
11388
*
11389
* var array = [0, 1, 2],
11390
* object = { 'a': array, 'b': array, 'c': array };
11391
*
11392
* _.map(['a[2]', 'c[0]'], _.propertyOf(object));
11393
* // => [2, 0]
11394
*
11395
* _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
11396
* // => [2, 0]
11397
*/
11398
function propertyOf(object) {
11399
return function(path) {
11400
return baseGet(object, toPath(path), path + '');
11401
};
11402
}
11403
11404
/**
11405
* Creates an array of numbers (positive and/or negative) progressing from
11406
* `start` up to, but not including, `end`. If `end` is not specified it is
11407
* set to `start` with `start` then set to `0`. If `end` is less than `start`
11408
* a zero-length range is created unless a negative `step` is specified.
11409
*
11410
* @static
11411
* @memberOf _
11412
* @category Utility
11413
* @param {number} [start=0] The start of the range.
11414
* @param {number} end The end of the range.
11415
* @param {number} [step=1] The value to increment or decrement by.
11416
* @returns {Array} Returns the new array of numbers.
11417
* @example
11418
*
11419
* _.range(4);
11420
* // => [0, 1, 2, 3]
11421
*
11422
* _.range(1, 5);
11423
* // => [1, 2, 3, 4]
11424
*
11425
* _.range(0, 20, 5);
11426
* // => [0, 5, 10, 15]
11427
*
11428
* _.range(0, -4, -1);
11429
* // => [0, -1, -2, -3]
11430
*
11431
* _.range(1, 4, 0);
11432
* // => [1, 1, 1]
11433
*
11434
* _.range(0);
11435
* // => []
11436
*/
11437
function range(start, end, step) {
11438
if (step && isIterateeCall(start, end, step)) {
11439
end = step = null;
11440
}
11441
start = +start || 0;
11442
step = step == null ? 1 : (+step || 0);
11443
11444
if (end == null) {
11445
end = start;
11446
start = 0;
11447
} else {
11448
end = +end || 0;
11449
}
11450
// Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
11451
// See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
11452
var index = -1,
11453
length = nativeMax(ceil((end - start) / (step || 1)), 0),
11454
result = Array(length);
11455
11456
while (++index < length) {
11457
result[index] = start;
11458
start += step;
11459
}
11460
return result;
11461
}
11462
11463
/**
11464
* Invokes the iteratee function `n` times, returning an array of the results
11465
* of each invocation. The `iteratee` is bound to `thisArg` and invoked with
11466
* one argument; (index).
11467
*
11468
* @static
11469
* @memberOf _
11470
* @category Utility
11471
* @param {number} n The number of times to invoke `iteratee`.
11472
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
11473
* @param {*} [thisArg] The `this` binding of `iteratee`.
11474
* @returns {Array} Returns the array of results.
11475
* @example
11476
*
11477
* var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
11478
* // => [3, 6, 4]
11479
*
11480
* _.times(3, function(n) {
11481
* mage.castSpell(n);
11482
* });
11483
* // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
11484
*
11485
* _.times(3, function(n) {
11486
* this.cast(n);
11487
* }, mage);
11488
* // => also invokes `mage.castSpell(n)` three times
11489
*/
11490
function times(n, iteratee, thisArg) {
11491
n = floor(n);
11492
11493
// Exit early to avoid a JSC JIT bug in Safari 8
11494
// where `Array(0)` is treated as `Array(1)`.
11495
if (n < 1 || !nativeIsFinite(n)) {
11496
return [];
11497
}
11498
var index = -1,
11499
result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
11500
11501
iteratee = bindCallback(iteratee, thisArg, 1);
11502
while (++index < n) {
11503
if (index < MAX_ARRAY_LENGTH) {
11504
result[index] = iteratee(index);
11505
} else {
11506
iteratee(index);
11507
}
11508
}
11509
return result;
11510
}
11511
11512
/**
11513
* Generates a unique ID. If `prefix` is provided the ID is appended to it.
11514
*
11515
* @static
11516
* @memberOf _
11517
* @category Utility
11518
* @param {string} [prefix] The value to prefix the ID with.
11519
* @returns {string} Returns the unique ID.
11520
* @example
11521
*
11522
* _.uniqueId('contact_');
11523
* // => 'contact_104'
11524
*
11525
* _.uniqueId();
11526
* // => '105'
11527
*/
11528
function uniqueId(prefix) {
11529
var id = ++idCounter;
11530
return baseToString(prefix) + id;
11531
}
11532
11533
/*------------------------------------------------------------------------*/
11534
11535
/**
11536
* Adds two numbers.
11537
*
11538
* @static
11539
* @memberOf _
11540
* @category Math
11541
* @param {number} augend The first number to add.
11542
* @param {number} addend The second number to add.
11543
* @returns {number} Returns the sum.
11544
* @example
11545
*
11546
* _.add(6, 4);
11547
* // => 10
11548
*/
11549
function add(augend, addend) {
11550
return (+augend || 0) + (+addend || 0);
11551
}
11552
11553
/**
11554
* Gets the maximum value of `collection`. If `collection` is empty or falsey
11555
* `-Infinity` is returned. If an iteratee function is provided it is invoked
11556
* for each value in `collection` to generate the criterion by which the value
11557
* is ranked. The `iteratee` is bound to `thisArg` and invoked with three
11558
* arguments: (value, index, collection).
11559
*
11560
* If a property name is provided for `iteratee` the created `_.property`
11561
* style callback returns the property value of the given element.
11562
*
11563
* If a value is also provided for `thisArg` the created `_.matchesProperty`
11564
* style callback returns `true` for elements that have a matching property
11565
* value, else `false`.
11566
*
11567
* If an object is provided for `iteratee` the created `_.matches` style
11568
* callback returns `true` for elements that have the properties of the given
11569
* object, else `false`.
11570
*
11571
* @static
11572
* @memberOf _
11573
* @category Math
11574
* @param {Array|Object|string} collection The collection to iterate over.
11575
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
11576
* @param {*} [thisArg] The `this` binding of `iteratee`.
11577
* @returns {*} Returns the maximum value.
11578
* @example
11579
*
11580
* _.max([4, 2, 8, 6]);
11581
* // => 8
11582
*
11583
* _.max([]);
11584
* // => -Infinity
11585
*
11586
* var users = [
11587
* { 'user': 'barney', 'age': 36 },
11588
* { 'user': 'fred', 'age': 40 }
11589
* ];
11590
*
11591
* _.max(users, function(chr) {
11592
* return chr.age;
11593
* });
11594
* // => { 'user': 'fred', 'age': 40 }
11595
*
11596
* // using the `_.property` callback shorthand
11597
* _.max(users, 'age');
11598
* // => { 'user': 'fred', 'age': 40 }
11599
*/
11600
var max = createExtremum(gt, NEGATIVE_INFINITY);
11601
11602
/**
11603
* Gets the minimum value of `collection`. If `collection` is empty or falsey
11604
* `Infinity` is returned. If an iteratee function is provided it is invoked
11605
* for each value in `collection` to generate the criterion by which the value
11606
* is ranked. The `iteratee` is bound to `thisArg` and invoked with three
11607
* arguments: (value, index, collection).
11608
*
11609
* If a property name is provided for `iteratee` the created `_.property`
11610
* style callback returns the property value of the given element.
11611
*
11612
* If a value is also provided for `thisArg` the created `_.matchesProperty`
11613
* style callback returns `true` for elements that have a matching property
11614
* value, else `false`.
11615
*
11616
* If an object is provided for `iteratee` the created `_.matches` style
11617
* callback returns `true` for elements that have the properties of the given
11618
* object, else `false`.
11619
*
11620
* @static
11621
* @memberOf _
11622
* @category Math
11623
* @param {Array|Object|string} collection The collection to iterate over.
11624
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
11625
* @param {*} [thisArg] The `this` binding of `iteratee`.
11626
* @returns {*} Returns the minimum value.
11627
* @example
11628
*
11629
* _.min([4, 2, 8, 6]);
11630
* // => 2
11631
*
11632
* _.min([]);
11633
* // => Infinity
11634
*
11635
* var users = [
11636
* { 'user': 'barney', 'age': 36 },
11637
* { 'user': 'fred', 'age': 40 }
11638
* ];
11639
*
11640
* _.min(users, function(chr) {
11641
* return chr.age;
11642
* });
11643
* // => { 'user': 'barney', 'age': 36 }
11644
*
11645
* // using the `_.property` callback shorthand
11646
* _.min(users, 'age');
11647
* // => { 'user': 'barney', 'age': 36 }
11648
*/
11649
var min = createExtremum(lt, POSITIVE_INFINITY);
11650
11651
/**
11652
* Gets the sum of the values in `collection`.
11653
*
11654
* @static
11655
* @memberOf _
11656
* @category Math
11657
* @param {Array|Object|string} collection The collection to iterate over.
11658
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
11659
* @param {*} [thisArg] The `this` binding of `iteratee`.
11660
* @returns {number} Returns the sum.
11661
* @example
11662
*
11663
* _.sum([4, 6]);
11664
* // => 10
11665
*
11666
* _.sum({ 'a': 4, 'b': 6 });
11667
* // => 10
11668
*
11669
* var objects = [
11670
* { 'n': 4 },
11671
* { 'n': 6 }
11672
* ];
11673
*
11674
* _.sum(objects, function(object) {
11675
* return object.n;
11676
* });
11677
* // => 10
11678
*
11679
* // using the `_.property` callback shorthand
11680
* _.sum(objects, 'n');
11681
* // => 10
11682
*/
11683
function sum(collection, iteratee, thisArg) {
11684
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
11685
iteratee = null;
11686
}
11687
var callback = getCallback(),
11688
noIteratee = iteratee == null;
11689
11690
if (!(noIteratee && callback === baseCallback)) {
11691
noIteratee = false;
11692
iteratee = callback(iteratee, thisArg, 3);
11693
}
11694
return noIteratee
11695
? arraySum(isArray(collection) ? collection : toIterable(collection))
11696
: baseSum(collection, iteratee);
11697
}
11698
11699
/*------------------------------------------------------------------------*/
11700
11701
// Ensure wrappers are instances of `baseLodash`.
11702
lodash.prototype = baseLodash.prototype;
11703
11704
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
11705
LodashWrapper.prototype.constructor = LodashWrapper;
11706
11707
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
11708
LazyWrapper.prototype.constructor = LazyWrapper;
11709
11710
// Add functions to the `Map` cache.
11711
MapCache.prototype['delete'] = mapDelete;
11712
MapCache.prototype.get = mapGet;
11713
MapCache.prototype.has = mapHas;
11714
MapCache.prototype.set = mapSet;
11715
11716
// Add functions to the `Set` cache.
11717
SetCache.prototype.push = cachePush;
11718
11719
// Assign cache to `_.memoize`.
11720
memoize.Cache = MapCache;
11721
11722
// Add functions that return wrapped values when chaining.
11723
lodash.after = after;
11724
lodash.ary = ary;
11725
lodash.assign = assign;
11726
lodash.at = at;
11727
lodash.before = before;
11728
lodash.bind = bind;
11729
lodash.bindAll = bindAll;
11730
lodash.bindKey = bindKey;
11731
lodash.callback = callback;
11732
lodash.chain = chain;
11733
lodash.chunk = chunk;
11734
lodash.compact = compact;
11735
lodash.constant = constant;
11736
lodash.countBy = countBy;
11737
lodash.create = create;
11738
lodash.curry = curry;
11739
lodash.curryRight = curryRight;
11740
lodash.debounce = debounce;
11741
lodash.defaults = defaults;
11742
lodash.defer = defer;
11743
lodash.delay = delay;
11744
lodash.difference = difference;
11745
lodash.drop = drop;
11746
lodash.dropRight = dropRight;
11747
lodash.dropRightWhile = dropRightWhile;
11748
lodash.dropWhile = dropWhile;
11749
lodash.fill = fill;
11750
lodash.filter = filter;
11751
lodash.flatten = flatten;
11752
lodash.flattenDeep = flattenDeep;
11753
lodash.flow = flow;
11754
lodash.flowRight = flowRight;
11755
lodash.forEach = forEach;
11756
lodash.forEachRight = forEachRight;
11757
lodash.forIn = forIn;
11758
lodash.forInRight = forInRight;
11759
lodash.forOwn = forOwn;
11760
lodash.forOwnRight = forOwnRight;
11761
lodash.functions = functions;
11762
lodash.groupBy = groupBy;
11763
lodash.indexBy = indexBy;
11764
lodash.initial = initial;
11765
lodash.intersection = intersection;
11766
lodash.invert = invert;
11767
lodash.invoke = invoke;
11768
lodash.keys = keys;
11769
lodash.keysIn = keysIn;
11770
lodash.map = map;
11771
lodash.mapKeys = mapKeys;
11772
lodash.mapValues = mapValues;
11773
lodash.matches = matches;
11774
lodash.matchesProperty = matchesProperty;
11775
lodash.memoize = memoize;
11776
lodash.merge = merge;
11777
lodash.method = method;
11778
lodash.methodOf = methodOf;
11779
lodash.mixin = mixin;
11780
lodash.negate = negate;
11781
lodash.omit = omit;
11782
lodash.once = once;
11783
lodash.pairs = pairs;
11784
lodash.partial = partial;
11785
lodash.partialRight = partialRight;
11786
lodash.partition = partition;
11787
lodash.pick = pick;
11788
lodash.pluck = pluck;
11789
lodash.property = property;
11790
lodash.propertyOf = propertyOf;
11791
lodash.pull = pull;
11792
lodash.pullAt = pullAt;
11793
lodash.range = range;
11794
lodash.rearg = rearg;
11795
lodash.reject = reject;
11796
lodash.remove = remove;
11797
lodash.rest = rest;
11798
lodash.restParam = restParam;
11799
lodash.set = set;
11800
lodash.shuffle = shuffle;
11801
lodash.slice = slice;
11802
lodash.sortBy = sortBy;
11803
lodash.sortByAll = sortByAll;
11804
lodash.sortByOrder = sortByOrder;
11805
lodash.spread = spread;
11806
lodash.take = take;
11807
lodash.takeRight = takeRight;
11808
lodash.takeRightWhile = takeRightWhile;
11809
lodash.takeWhile = takeWhile;
11810
lodash.tap = tap;
11811
lodash.throttle = throttle;
11812
lodash.thru = thru;
11813
lodash.times = times;
11814
lodash.toArray = toArray;
11815
lodash.toPlainObject = toPlainObject;
11816
lodash.transform = transform;
11817
lodash.union = union;
11818
lodash.uniq = uniq;
11819
lodash.unzip = unzip;
11820
lodash.unzipWith = unzipWith;
11821
lodash.values = values;
11822
lodash.valuesIn = valuesIn;
11823
lodash.where = where;
11824
lodash.without = without;
11825
lodash.wrap = wrap;
11826
lodash.xor = xor;
11827
lodash.zip = zip;
11828
lodash.zipObject = zipObject;
11829
lodash.zipWith = zipWith;
11830
11831
// Add aliases.
11832
lodash.backflow = flowRight;
11833
lodash.collect = map;
11834
lodash.compose = flowRight;
11835
lodash.each = forEach;
11836
lodash.eachRight = forEachRight;
11837
lodash.extend = assign;
11838
lodash.iteratee = callback;
11839
lodash.methods = functions;
11840
lodash.object = zipObject;
11841
lodash.select = filter;
11842
lodash.tail = rest;
11843
lodash.unique = uniq;
11844
11845
// Add functions to `lodash.prototype`.
11846
mixin(lodash, lodash);
11847
11848
/*------------------------------------------------------------------------*/
11849
11850
// Add functions that return unwrapped values when chaining.
11851
lodash.add = add;
11852
lodash.attempt = attempt;
11853
lodash.camelCase = camelCase;
11854
lodash.capitalize = capitalize;
11855
lodash.clone = clone;
11856
lodash.cloneDeep = cloneDeep;
11857
lodash.deburr = deburr;
11858
lodash.endsWith = endsWith;
11859
lodash.escape = escape;
11860
lodash.escapeRegExp = escapeRegExp;
11861
lodash.every = every;
11862
lodash.find = find;
11863
lodash.findIndex = findIndex;
11864
lodash.findKey = findKey;
11865
lodash.findLast = findLast;
11866
lodash.findLastIndex = findLastIndex;
11867
lodash.findLastKey = findLastKey;
11868
lodash.findWhere = findWhere;
11869
lodash.first = first;
11870
lodash.get = get;
11871
lodash.gt = gt;
11872
lodash.gte = gte;
11873
lodash.has = has;
11874
lodash.identity = identity;
11875
lodash.includes = includes;
11876
lodash.indexOf = indexOf;
11877
lodash.inRange = inRange;
11878
lodash.isArguments = isArguments;
11879
lodash.isArray = isArray;
11880
lodash.isBoolean = isBoolean;
11881
lodash.isDate = isDate;
11882
lodash.isElement = isElement;
11883
lodash.isEmpty = isEmpty;
11884
lodash.isEqual = isEqual;
11885
lodash.isError = isError;
11886
lodash.isFinite = isFinite;
11887
lodash.isFunction = isFunction;
11888
lodash.isMatch = isMatch;
11889
lodash.isNaN = isNaN;
11890
lodash.isNative = isNative;
11891
lodash.isNull = isNull;
11892
lodash.isNumber = isNumber;
11893
lodash.isObject = isObject;
11894
lodash.isPlainObject = isPlainObject;
11895
lodash.isRegExp = isRegExp;
11896
lodash.isString = isString;
11897
lodash.isTypedArray = isTypedArray;
11898
lodash.isUndefined = isUndefined;
11899
lodash.kebabCase = kebabCase;
11900
lodash.last = last;
11901
lodash.lastIndexOf = lastIndexOf;
11902
lodash.lt = lt;
11903
lodash.lte = lte;
11904
lodash.max = max;
11905
lodash.min = min;
11906
lodash.noConflict = noConflict;
11907
lodash.noop = noop;
11908
lodash.now = now;
11909
lodash.pad = pad;
11910
lodash.padLeft = padLeft;
11911
lodash.padRight = padRight;
11912
lodash.parseInt = parseInt;
11913
lodash.random = random;
11914
lodash.reduce = reduce;
11915
lodash.reduceRight = reduceRight;
11916
lodash.repeat = repeat;
11917
lodash.result = result;
11918
lodash.runInContext = runInContext;
11919
lodash.size = size;
11920
lodash.snakeCase = snakeCase;
11921
lodash.some = some;
11922
lodash.sortedIndex = sortedIndex;
11923
lodash.sortedLastIndex = sortedLastIndex;
11924
lodash.startCase = startCase;
11925
lodash.startsWith = startsWith;
11926
lodash.sum = sum;
11927
lodash.template = template;
11928
lodash.trim = trim;
11929
lodash.trimLeft = trimLeft;
11930
lodash.trimRight = trimRight;
11931
lodash.trunc = trunc;
11932
lodash.unescape = unescape;
11933
lodash.uniqueId = uniqueId;
11934
lodash.words = words;
11935
11936
// Add aliases.
11937
lodash.all = every;
11938
lodash.any = some;
11939
lodash.contains = includes;
11940
lodash.eq = isEqual;
11941
lodash.detect = find;
11942
lodash.foldl = reduce;
11943
lodash.foldr = reduceRight;
11944
lodash.head = first;
11945
lodash.include = includes;
11946
lodash.inject = reduce;
11947
11948
mixin(lodash, (function() {
11949
var source = {};
11950
baseForOwn(lodash, function(func, methodName) {
11951
if (!lodash.prototype[methodName]) {
11952
source[methodName] = func;
11953
}
11954
});
11955
return source;
11956
}()), false);
11957
11958
/*------------------------------------------------------------------------*/
11959
11960
// Add functions capable of returning wrapped and unwrapped values when chaining.
11961
lodash.sample = sample;
11962
11963
lodash.prototype.sample = function(n) {
11964
if (!this.__chain__ && n == null) {
11965
return sample(this.value());
11966
}
11967
return this.thru(function(value) {
11968
return sample(value, n);
11969
});
11970
};
11971
11972
/*------------------------------------------------------------------------*/
11973
11974
/**
11975
* The semantic version number.
11976
*
11977
* @static
11978
* @memberOf _
11979
* @type string
11980
*/
11981
lodash.VERSION = VERSION;
11982
11983
// Assign default placeholders.
11984
arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
11985
lodash[methodName].placeholder = lodash;
11986
});
11987
11988
// Add `LazyWrapper` methods that accept an `iteratee` value.
11989
arrayEach(['dropWhile', 'filter', 'map', 'takeWhile'], function(methodName, type) {
11990
var isFilter = type != LAZY_MAP_FLAG,
11991
isDropWhile = type == LAZY_DROP_WHILE_FLAG;
11992
11993
LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
11994
var filtered = this.__filtered__,
11995
result = (filtered && isDropWhile) ? new LazyWrapper(this) : this.clone(),
11996
iteratees = result.__iteratees__ || (result.__iteratees__ = []);
11997
11998
iteratees.push({
11999
'done': false,
12000
'count': 0,
12001
'index': 0,
12002
'iteratee': getCallback(iteratee, thisArg, 1),
12003
'limit': -1,
12004
'type': type
12005
});
12006
12007
result.__filtered__ = filtered || isFilter;
12008
return result;
12009
};
12010
});
12011
12012
// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
12013
arrayEach(['drop', 'take'], function(methodName, index) {
12014
var whileName = methodName + 'While';
12015
12016
LazyWrapper.prototype[methodName] = function(n) {
12017
var filtered = this.__filtered__,
12018
result = (filtered && !index) ? this.dropWhile() : this.clone();
12019
12020
n = n == null ? 1 : nativeMax(floor(n) || 0, 0);
12021
if (filtered) {
12022
if (index) {
12023
result.__takeCount__ = nativeMin(result.__takeCount__, n);
12024
} else {
12025
last(result.__iteratees__).limit = n;
12026
}
12027
} else {
12028
var views = result.__views__ || (result.__views__ = []);
12029
views.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') });
12030
}
12031
return result;
12032
};
12033
12034
LazyWrapper.prototype[methodName + 'Right'] = function(n) {
12035
return this.reverse()[methodName](n).reverse();
12036
};
12037
12038
LazyWrapper.prototype[methodName + 'RightWhile'] = function(predicate, thisArg) {
12039
return this.reverse()[whileName](predicate, thisArg).reverse();
12040
};
12041
});
12042
12043
// Add `LazyWrapper` methods for `_.first` and `_.last`.
12044
arrayEach(['first', 'last'], function(methodName, index) {
12045
var takeName = 'take' + (index ? 'Right' : '');
12046
12047
LazyWrapper.prototype[methodName] = function() {
12048
return this[takeName](1).value()[0];
12049
};
12050
});
12051
12052
// Add `LazyWrapper` methods for `_.initial` and `_.rest`.
12053
arrayEach(['initial', 'rest'], function(methodName, index) {
12054
var dropName = 'drop' + (index ? '' : 'Right');
12055
12056
LazyWrapper.prototype[methodName] = function() {
12057
return this[dropName](1);
12058
};
12059
});
12060
12061
// Add `LazyWrapper` methods for `_.pluck` and `_.where`.
12062
arrayEach(['pluck', 'where'], function(methodName, index) {
12063
var operationName = index ? 'filter' : 'map',
12064
createCallback = index ? baseMatches : property;
12065
12066
LazyWrapper.prototype[methodName] = function(value) {
12067
return this[operationName](createCallback(value));
12068
};
12069
});
12070
12071
LazyWrapper.prototype.compact = function() {
12072
return this.filter(identity);
12073
};
12074
12075
LazyWrapper.prototype.reject = function(predicate, thisArg) {
12076
predicate = getCallback(predicate, thisArg, 1);
12077
return this.filter(function(value) {
12078
return !predicate(value);
12079
});
12080
};
12081
12082
LazyWrapper.prototype.slice = function(start, end) {
12083
start = start == null ? 0 : (+start || 0);
12084
12085
var result = this;
12086
if (start < 0) {
12087
result = this.takeRight(-start);
12088
} else if (start) {
12089
result = this.drop(start);
12090
}
12091
if (end !== undefined) {
12092
end = (+end || 0);
12093
result = end < 0 ? result.dropRight(-end) : result.take(end - start);
12094
}
12095
return result;
12096
};
12097
12098
LazyWrapper.prototype.toArray = function() {
12099
return this.drop(0);
12100
};
12101
12102
// Add `LazyWrapper` methods to `lodash.prototype`.
12103
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
12104
var lodashFunc = lodash[methodName];
12105
if (!lodashFunc) {
12106
return;
12107
}
12108
var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName),
12109
retUnwrapped = /^(?:first|last)$/.test(methodName);
12110
12111
lodash.prototype[methodName] = function() {
12112
var args = arguments,
12113
chainAll = this.__chain__,
12114
value = this.__wrapped__,
12115
isHybrid = !!this.__actions__.length,
12116
isLazy = value instanceof LazyWrapper,
12117
iteratee = args[0],
12118
useLazy = isLazy || isArray(value);
12119
12120
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
12121
// avoid lazy use if the iteratee has a "length" value other than `1`
12122
isLazy = useLazy = false;
12123
}
12124
var onlyLazy = isLazy && !isHybrid;
12125
if (retUnwrapped && !chainAll) {
12126
return onlyLazy
12127
? func.call(value)
12128
: lodashFunc.call(lodash, this.value());
12129
}
12130
var interceptor = function(value) {
12131
var otherArgs = [value];
12132
push.apply(otherArgs, args);
12133
return lodashFunc.apply(lodash, otherArgs);
12134
};
12135
if (useLazy) {
12136
var wrapper = onlyLazy ? value : new LazyWrapper(this),
12137
result = func.apply(wrapper, args);
12138
12139
if (!retUnwrapped && (isHybrid || result.__actions__)) {
12140
var actions = result.__actions__ || (result.__actions__ = []);
12141
actions.push({ 'func': thru, 'args': [interceptor], 'thisArg': lodash });
12142
}
12143
return new LodashWrapper(result, chainAll);
12144
}
12145
return this.thru(interceptor);
12146
};
12147
});
12148
12149
// Add `Array` and `String` methods to `lodash.prototype`.
12150
arrayEach(['concat', 'join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) {
12151
var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName],
12152
chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
12153
retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
12154
12155
lodash.prototype[methodName] = function() {
12156
var args = arguments;
12157
if (retUnwrapped && !this.__chain__) {
12158
return func.apply(this.value(), args);
12159
}
12160
return this[chainName](function(value) {
12161
return func.apply(value, args);
12162
});
12163
};
12164
});
12165
12166
// Map minified function names to their real names.
12167
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
12168
var lodashFunc = lodash[methodName];
12169
if (lodashFunc) {
12170
var key = lodashFunc.name,
12171
names = realNames[key] || (realNames[key] = []);
12172
12173
names.push({ 'name': methodName, 'func': lodashFunc });
12174
}
12175
});
12176
12177
realNames[createHybridWrapper(null, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': null }];
12178
12179
// Add functions to the lazy wrapper.
12180
LazyWrapper.prototype.clone = lazyClone;
12181
LazyWrapper.prototype.reverse = lazyReverse;
12182
LazyWrapper.prototype.value = lazyValue;
12183
12184
// Add chaining functions to the `lodash` wrapper.
12185
lodash.prototype.chain = wrapperChain;
12186
lodash.prototype.commit = wrapperCommit;
12187
lodash.prototype.plant = wrapperPlant;
12188
lodash.prototype.reverse = wrapperReverse;
12189
lodash.prototype.toString = wrapperToString;
12190
lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
12191
12192
// Add function aliases to the `lodash` wrapper.
12193
lodash.prototype.collect = lodash.prototype.map;
12194
lodash.prototype.head = lodash.prototype.first;
12195
lodash.prototype.select = lodash.prototype.filter;
12196
lodash.prototype.tail = lodash.prototype.rest;
12197
12198
return lodash;
12199
}
12200
12201
/*--------------------------------------------------------------------------*/
12202
12203
// Export lodash.
12204
var _ = runInContext();
12205
12206
// Some AMD build optimizers like r.js check for condition patterns like the following:
12207
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
12208
// Expose lodash to the global object when an AMD loader is present to avoid
12209
// errors in cases where lodash is loaded by a script tag and not intended
12210
// as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
12211
// more details.
12212
root._ = _;
12213
12214
// Define as an anonymous module so, through path mapping, it can be
12215
// referenced as the "underscore" module.
12216
define(function() {
12217
return _;
12218
});
12219
}
12220
// Check for `exports` after `define` in case a build optimizer adds an `exports` object.
12221
else if (freeExports && freeModule) {
12222
// Export for Node.js or RingoJS.
12223
if (moduleExports) {
12224
(freeModule.exports = _)._ = _;
12225
}
12226
// Export for Rhino with CommonJS support.
12227
else {
12228
freeExports._ = _;
12229
}
12230
}
12231
else {
12232
// Export for a browser or Rhino.
12233
root._ = _;
12234
}
12235
}.call(this));
12236
12237