· 7 years ago · May 02, 2018, 02:40 PM
1// Underscore.js 1.9.0
2// http://underscorejs.org
3// (c) 2009-2018 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
4// Underscore may be freely distributed under the MIT license.
5
6(function() {
7
8 // Baseline setup
9 // --------------
10
11 // Establish the root object, `window` (`self`) in the browser, `global`
12 // on the server, or `this` in some virtual machines. We use `self`
13 // instead of `window` for `WebWorker` support.
14 var root = typeof self == 'object' && self.self === self && self ||
15 typeof global == 'object' && global.global === global && global ||
16 this ||
17 {};
18
19 // Save the previous value of the `_` variable.
20 var previousUnderscore = root._;
21
22 // Save bytes in the minified (but not gzipped) version:
23 var ArrayProto = Array.prototype, ObjProto = Object.prototype;
24 var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
25
26 // Create quick reference variables for speed access to core prototypes.
27 var push = ArrayProto.push,
28 slice = ArrayProto.slice,
29 toString = ObjProto.toString,
30 hasOwnProperty = ObjProto.hasOwnProperty;
31
32 // All **ECMAScript 5** native function implementations that we hope to use
33 // are declared here.
34 var nativeIsArray = Array.isArray,
35 nativeKeys = Object.keys,
36 nativeCreate = Object.create;
37
38 // Naked function reference for surrogate-prototype-swapping.
39 var Ctor = function(){};
40
41 // Create a safe reference to the Underscore object for use below.
42 var _ = function(obj) {
43 if (obj instanceof _) return obj;
44 if (!(this instanceof _)) return new _(obj);
45 this._wrapped = obj;
46 };
47
48 // Export the Underscore object for **Node.js**, with
49 // backwards-compatibility for their old module API. If we're in
50 // the browser, add `_` as a global object.
51 // (`nodeType` is checked to ensure that `module`
52 // and `exports` are not HTML elements.)
53 if (typeof exports != 'undefined' && !exports.nodeType) {
54 if (typeof module != 'undefined' && !module.nodeType && module.exports) {
55 exports = module.exports = _;
56 }
57 exports._ = _;
58 } else {
59 root._ = _;
60 }
61
62 // Current version.
63 _.VERSION = '1.9.0';
64
65 // Internal function that returns an efficient (for current engines) version
66 // of the passed-in callback, to be repeatedly applied in other Underscore
67 // functions.
68 var optimizeCb = function(func, context, argCount) {
69 if (context === void 0) return func;
70 switch (argCount == null ? 3 : argCount) {
71 case 1: return function(value) {
72 return func.call(context, value);
73 };
74 // The 2-argument case is omitted because we’re not using it.
75 case 3: return function(value, index, collection) {
76 return func.call(context, value, index, collection);
77 };
78 case 4: return function(accumulator, value, index, collection) {
79 return func.call(context, accumulator, value, index, collection);
80 };
81 }
82 return function() {
83 return func.apply(context, arguments);
84 };
85 };
86
87 var builtinIteratee;
88
89 // An internal function to generate callbacks that can be applied to each
90 // element in a collection, returning the desired result — either `identity`,
91 // an arbitrary callback, a property matcher, or a property accessor.
92 var cb = function(value, context, argCount) {
93 if (_.iteratee !== builtinIteratee) return _.iteratee(value, context);
94 if (value == null) return _.identity;
95 if (_.isFunction(value)) return optimizeCb(value, context, argCount);
96 if (_.isObject(value) && !_.isArray(value)) return _.matcher(value);
97 return _.property(value);
98 };
99
100 // External wrapper for our callback generator. Users may customize
101 // `_.iteratee` if they want additional predicate/iteratee shorthand styles.
102 // This abstraction hides the internal-only argCount argument.
103 _.iteratee = builtinIteratee = function(value, context) {
104 return cb(value, context, Infinity);
105 };
106
107 // Some functions take a variable number of arguments, or a few expected
108 // arguments at the beginning and then a variable number of values to operate
109 // on. This helper accumulates all remaining arguments past the function’s
110 // argument length (or an explicit `startIndex`), into an array that becomes
111 // the last argument. Similar to ES6’s "rest parameter".
112 var restArguments = function(func, startIndex) {
113 startIndex = startIndex == null ? func.length - 1 : +startIndex;
114 return function() {
115 var length = Math.max(arguments.length - startIndex, 0),
116 rest = Array(length),
117 index = 0;
118 for (; index < length; index++) {
119 rest[index] = arguments[index + startIndex];
120 }
121 switch (startIndex) {
122 case 0: return func.call(this, rest);
123 case 1: return func.call(this, arguments[0], rest);
124 case 2: return func.call(this, arguments[0], arguments[1], rest);
125 }
126 var args = Array(startIndex + 1);
127 for (index = 0; index < startIndex; index++) {
128 args[index] = arguments[index];
129 }
130 args[startIndex] = rest;
131 return func.apply(this, args);
132 };
133 };
134
135 // An internal function for creating a new object that inherits from another.
136 var baseCreate = function(prototype) {
137 if (!_.isObject(prototype)) return {};
138 if (nativeCreate) return nativeCreate(prototype);
139 Ctor.prototype = prototype;
140 var result = new Ctor;
141 Ctor.prototype = null;
142 return result;
143 };
144
145 var shallowProperty = function(key) {
146 return function(obj) {
147 return obj == null ? void 0 : obj[key];
148 };
149 };
150
151 var deepGet = function(obj, path) {
152 var length = path.length;
153 for (var i = 0; i < length; i++) {
154 if (obj == null) return void 0;
155 obj = obj[path[i]];
156 }
157 return length ? obj : void 0;
158 };
159
160 // Helper for collection methods to determine whether a collection
161 // should be iterated as an array or as an object.
162 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
163 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
164 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
165 var getLength = shallowProperty('length');
166 var isArrayLike = function(collection) {
167 var length = getLength(collection);
168 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
169 };
170
171 // Collection Functions
172 // --------------------
173
174 // The cornerstone, an `each` implementation, aka `forEach`.
175 // Handles raw objects in addition to array-likes. Treats all
176 // sparse array-likes as if they were dense.
177 _.each = _.forEach = function(obj, iteratee, context) {
178 iteratee = optimizeCb(iteratee, context);
179 var i, length;
180 if (isArrayLike(obj)) {
181 for (i = 0, length = obj.length; i < length; i++) {
182 iteratee(obj[i], i, obj);
183 }
184 } else {
185 var keys = _.keys(obj);
186 for (i = 0, length = keys.length; i < length; i++) {
187 iteratee(obj[keys[i]], keys[i], obj);
188 }
189 }
190 return obj;
191 };
192
193 // Return the results of applying the iteratee to each element.
194 _.map = _.collect = function(obj, iteratee, context) {
195 iteratee = cb(iteratee, context);
196 var keys = !isArrayLike(obj) && _.keys(obj),
197 length = (keys || obj).length,
198 results = Array(length);
199 for (var index = 0; index < length; index++) {
200 var currentKey = keys ? keys[index] : index;
201 results[index] = iteratee(obj[currentKey], currentKey, obj);
202 }
203 return results;
204 };
205
206 // Create a reducing function iterating left or right.
207 var createReduce = function(dir) {
208 // Wrap code that reassigns argument variables in a separate function than
209 // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
210 var reducer = function(obj, iteratee, memo, initial) {
211 var keys = !isArrayLike(obj) && _.keys(obj),
212 length = (keys || obj).length,
213 index = dir > 0 ? 0 : length - 1;
214 if (!initial) {
215 memo = obj[keys ? keys[index] : index];
216 index += dir;
217 }
218 for (; index >= 0 && index < length; index += dir) {
219 var currentKey = keys ? keys[index] : index;
220 memo = iteratee(memo, obj[currentKey], currentKey, obj);
221 }
222 return memo;
223 };
224
225 return function(obj, iteratee, memo, context) {
226 var initial = arguments.length >= 3;
227 return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
228 };
229 };
230
231 // **Reduce** builds up a single result from a list of values, aka `inject`,
232 // or `foldl`.
233 _.reduce = _.foldl = _.inject = createReduce(1);
234
235 // The right-associative version of reduce, also known as `foldr`.
236 _.reduceRight = _.foldr = createReduce(-1);
237
238 // Return the first value which passes a truth test. Aliased as `detect`.
239 _.find = _.detect = function(obj, predicate, context) {
240 var keyFinder = isArrayLike(obj) ? _.findIndex : _.findKey;
241 var key = keyFinder(obj, predicate, context);
242 if (key !== void 0 && key !== -1) return obj[key];
243 };
244
245 // Return all the elements that pass a truth test.
246 // Aliased as `select`.
247 _.filter = _.select = function(obj, predicate, context) {
248 var results = [];
249 predicate = cb(predicate, context);
250 _.each(obj, function(value, index, list) {
251 if (predicate(value, index, list)) results.push(value);
252 });
253 return results;
254 };
255
256 // Return all the elements for which a truth test fails.
257 _.reject = function(obj, predicate, context) {
258 return _.filter(obj, _.negate(cb(predicate)), context);
259 };
260
261 // Determine whether all of the elements match a truth test.
262 // Aliased as `all`.
263 _.every = _.all = function(obj, predicate, context) {
264 predicate = cb(predicate, context);
265 var keys = !isArrayLike(obj) && _.keys(obj),
266 length = (keys || obj).length;
267 for (var index = 0; index < length; index++) {
268 var currentKey = keys ? keys[index] : index;
269 if (!predicate(obj[currentKey], currentKey, obj)) return false;
270 }
271 return true;
272 };
273
274 // Determine if at least one element in the object matches a truth test.
275 // Aliased as `any`.
276 _.some = _.any = function(obj, predicate, context) {
277 predicate = cb(predicate, context);
278 var keys = !isArrayLike(obj) && _.keys(obj),
279 length = (keys || obj).length;
280 for (var index = 0; index < length; index++) {
281 var currentKey = keys ? keys[index] : index;
282 if (predicate(obj[currentKey], currentKey, obj)) return true;
283 }
284 return false;
285 };
286
287 // Determine if the array or object contains a given item (using `===`).
288 // Aliased as `includes` and `include`.
289 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
290 if (!isArrayLike(obj)) obj = _.values(obj);
291 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
292 return _.indexOf(obj, item, fromIndex) >= 0;
293 };
294
295 // Invoke a method (with arguments) on every item in a collection.
296 _.invoke = restArguments(function(obj, path, args) {
297 var contextPath, func;
298 if (_.isFunction(path)) {
299 func = path;
300 } else if (_.isArray(path)) {
301 contextPath = path.slice(0, -1);
302 path = path[path.length - 1];
303 }
304 return _.map(obj, function(context) {
305 var method = func;
306 if (!method) {
307 if (contextPath && contextPath.length) {
308 context = deepGet(context, contextPath);
309 }
310 if (context == null) return void 0;
311 method = context[path];
312 }
313 return method == null ? method : method.apply(context, args);
314 });
315 });
316
317 // Convenience version of a common use case of `map`: fetching a property.
318 _.pluck = function(obj, key) {
319 return _.map(obj, _.property(key));
320 };
321
322 // Convenience version of a common use case of `filter`: selecting only objects
323 // containing specific `key:value` pairs.
324 _.where = function(obj, attrs) {
325 return _.filter(obj, _.matcher(attrs));
326 };
327
328 // Convenience version of a common use case of `find`: getting the first object
329 // containing specific `key:value` pairs.
330 _.findWhere = function(obj, attrs) {
331 return _.find(obj, _.matcher(attrs));
332 };
333
334 // Return the maximum element (or element-based computation).
335 _.max = function(obj, iteratee, context) {
336 var result = -Infinity, lastComputed = -Infinity,
337 value, computed;
338 if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
339 obj = isArrayLike(obj) ? obj : _.values(obj);
340 for (var i = 0, length = obj.length; i < length; i++) {
341 value = obj[i];
342 if (value != null && value > result) {
343 result = value;
344 }
345 }
346 } else {
347 iteratee = cb(iteratee, context);
348 _.each(obj, function(v, index, list) {
349 computed = iteratee(v, index, list);
350 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
351 result = v;
352 lastComputed = computed;
353 }
354 });
355 }
356 return result;
357 };
358
359 // Return the minimum element (or element-based computation).
360 _.min = function(obj, iteratee, context) {
361 var result = Infinity, lastComputed = Infinity,
362 value, computed;
363 if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
364 obj = isArrayLike(obj) ? obj : _.values(obj);
365 for (var i = 0, length = obj.length; i < length; i++) {
366 value = obj[i];
367 if (value != null && value < result) {
368 result = value;
369 }
370 }
371 } else {
372 iteratee = cb(iteratee, context);
373 _.each(obj, function(v, index, list) {
374 computed = iteratee(v, index, list);
375 if (computed < lastComputed || computed === Infinity && result === Infinity) {
376 result = v;
377 lastComputed = computed;
378 }
379 });
380 }
381 return result;
382 };
383
384 // Shuffle a collection.
385 _.shuffle = function(obj) {
386 return _.sample(obj, Infinity);
387 };
388
389 // Sample **n** random values from a collection using the modern version of the
390 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
391 // If **n** is not specified, returns a single random element.
392 // The internal `guard` argument allows it to work with `map`.
393 _.sample = function(obj, n, guard) {
394 if (n == null || guard) {
395 if (!isArrayLike(obj)) obj = _.values(obj);
396 return obj[_.random(obj.length - 1)];
397 }
398 var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj);
399 var length = getLength(sample);
400 n = Math.max(Math.min(n, length), 0);
401 var last = length - 1;
402 for (var index = 0; index < n; index++) {
403 var rand = _.random(index, last);
404 var temp = sample[index];
405 sample[index] = sample[rand];
406 sample[rand] = temp;
407 }
408 return sample.slice(0, n);
409 };
410
411 // Sort the object's values by a criterion produced by an iteratee.
412 _.sortBy = function(obj, iteratee, context) {
413 var index = 0;
414 iteratee = cb(iteratee, context);
415 return _.pluck(_.map(obj, function(value, key, list) {
416 return {
417 value: value,
418 index: index++,
419 criteria: iteratee(value, key, list)
420 };
421 }).sort(function(left, right) {
422 var a = left.criteria;
423 var b = right.criteria;
424 if (a !== b) {
425 if (a > b || a === void 0) return 1;
426 if (a < b || b === void 0) return -1;
427 }
428 return left.index - right.index;
429 }), 'value');
430 };
431
432 // An internal function used for aggregate "group by" operations.
433 var group = function(behavior, partition) {
434 return function(obj, iteratee, context) {
435 var result = partition ? [[], []] : {};
436 iteratee = cb(iteratee, context);
437 _.each(obj, function(value, index) {
438 var key = iteratee(value, index, obj);
439 behavior(result, value, key);
440 });
441 return result;
442 };
443 };
444
445 // Groups the object's values by a criterion. Pass either a string attribute
446 // to group by, or a function that returns the criterion.
447 _.groupBy = group(function(result, value, key) {
448 if (_.has(result, key)) result[key].push(value); else result[key] = [value];
449 });
450
451 // Indexes the object's values by a criterion, similar to `groupBy`, but for
452 // when you know that your index values will be unique.
453 _.indexBy = group(function(result, value, key) {
454 result[key] = value;
455 });
456
457 // Counts instances of an object that group by a certain criterion. Pass
458 // either a string attribute to count by, or a function that returns the
459 // criterion.
460 _.countBy = group(function(result, value, key) {
461 if (_.has(result, key)) result[key]++; else result[key] = 1;
462 });
463
464 var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
465 // Safely create a real, live array from anything iterable.
466 _.toArray = function(obj) {
467 if (!obj) return [];
468 if (_.isArray(obj)) return slice.call(obj);
469 if (_.isString(obj)) {
470 // Keep surrogate pair characters together
471 return obj.match(reStrSymbol);
472 }
473 if (isArrayLike(obj)) return _.map(obj, _.identity);
474 return _.values(obj);
475 };
476
477 // Return the number of elements in an object.
478 _.size = function(obj) {
479 if (obj == null) return 0;
480 return isArrayLike(obj) ? obj.length : _.keys(obj).length;
481 };
482
483 // Split a collection into two arrays: one whose elements all satisfy the given
484 // predicate, and one whose elements all do not satisfy the predicate.
485 _.partition = group(function(result, value, pass) {
486 result[pass ? 0 : 1].push(value);
487 }, true);
488
489 // Array Functions
490 // ---------------
491
492 // Get the first element of an array. Passing **n** will return the first N
493 // values in the array. Aliased as `head` and `take`. The **guard** check
494 // allows it to work with `_.map`.
495 _.first = _.head = _.take = function(array, n, guard) {
496 if (array == null || array.length < 1) return void 0;
497 if (n == null || guard) return array[0];
498 return _.initial(array, array.length - n);
499 };
500
501 // Returns everything but the last entry of the array. Especially useful on
502 // the arguments object. Passing **n** will return all the values in
503 // the array, excluding the last N.
504 _.initial = function(array, n, guard) {
505 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
506 };
507
508 // Get the last element of an array. Passing **n** will return the last N
509 // values in the array.
510 _.last = function(array, n, guard) {
511 if (array == null || array.length < 1) return void 0;
512 if (n == null || guard) return array[array.length - 1];
513 return _.rest(array, Math.max(0, array.length - n));
514 };
515
516 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
517 // Especially useful on the arguments object. Passing an **n** will return
518 // the rest N values in the array.
519 _.rest = _.tail = _.drop = function(array, n, guard) {
520 return slice.call(array, n == null || guard ? 1 : n);
521 };
522
523 // Trim out all falsy values from an array.
524 _.compact = function(array) {
525 return _.filter(array, Boolean);
526 };
527
528 // Internal implementation of a recursive `flatten` function.
529 var flatten = function(input, shallow, strict, output) {
530 output = output || [];
531 var idx = output.length;
532 for (var i = 0, length = getLength(input); i < length; i++) {
533 var value = input[i];
534 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
535 // Flatten current level of array or arguments object.
536 if (shallow) {
537 var j = 0, len = value.length;
538 while (j < len) output[idx++] = value[j++];
539 } else {
540 flatten(value, shallow, strict, output);
541 idx = output.length;
542 }
543 } else if (!strict) {
544 output[idx++] = value;
545 }
546 }
547 return output;
548 };
549
550 // Flatten out an array, either recursively (by default), or just one level.
551 _.flatten = function(array, shallow) {
552 return flatten(array, shallow, false);
553 };
554
555 // Return a version of the array that does not contain the specified value(s).
556 _.without = restArguments(function(array, otherArrays) {
557 return _.difference(array, otherArrays);
558 });
559
560 // Produce a duplicate-free version of the array. If the array has already
561 // been sorted, you have the option of using a faster algorithm.
562 // The faster algorithm will not work with an iteratee if the iteratee
563 // is not a one-to-one function, so providing an iteratee will disable
564 // the faster algorithm.
565 // Aliased as `unique`.
566 _.uniq = _.unique = function(array, isSorted, iteratee, context) {
567 if (!_.isBoolean(isSorted)) {
568 context = iteratee;
569 iteratee = isSorted;
570 isSorted = false;
571 }
572 if (iteratee != null) iteratee = cb(iteratee, context);
573 var result = [];
574 var seen = [];
575 for (var i = 0, length = getLength(array); i < length; i++) {
576 var value = array[i],
577 computed = iteratee ? iteratee(value, i, array) : value;
578 if (isSorted && !iteratee) {
579 if (!i || seen !== computed) result.push(value);
580 seen = computed;
581 } else if (iteratee) {
582 if (!_.contains(seen, computed)) {
583 seen.push(computed);
584 result.push(value);
585 }
586 } else if (!_.contains(result, value)) {
587 result.push(value);
588 }
589 }
590 return result;
591 };
592
593 // Produce an array that contains the union: each distinct element from all of
594 // the passed-in arrays.
595 _.union = restArguments(function(arrays) {
596 return _.uniq(flatten(arrays, true, true));
597 });
598
599 // Produce an array that contains every item shared between all the
600 // passed-in arrays.
601 _.intersection = function(array) {
602 var result = [];
603 var argsLength = arguments.length;
604 for (var i = 0, length = getLength(array); i < length; i++) {
605 var item = array[i];
606 if (_.contains(result, item)) continue;
607 var j;
608 for (j = 1; j < argsLength; j++) {
609 if (!_.contains(arguments[j], item)) break;
610 }
611 if (j === argsLength) result.push(item);
612 }
613 return result;
614 };
615
616 // Take the difference between one array and a number of other arrays.
617 // Only the elements present in just the first array will remain.
618 _.difference = restArguments(function(array, rest) {
619 rest = flatten(rest, true, true);
620 return _.filter(array, function(value){
621 return !_.contains(rest, value);
622 });
623 });
624
625 // Complement of _.zip. Unzip accepts an array of arrays and groups
626 // each array's elements on shared indices.
627 _.unzip = function(array) {
628 var length = array && _.max(array, getLength).length || 0;
629 var result = Array(length);
630
631 for (var index = 0; index < length; index++) {
632 result[index] = _.pluck(array, index);
633 }
634 return result;
635 };
636
637 // Zip together multiple lists into a single array -- elements that share
638 // an index go together.
639 _.zip = restArguments(_.unzip);
640
641 // Converts lists into objects. Pass either a single array of `[key, value]`
642 // pairs, or two parallel arrays of the same length -- one of keys, and one of
643 // the corresponding values. Passing by pairs is the reverse of _.pairs.
644 _.object = function(list, values) {
645 var result = {};
646 for (var i = 0, length = getLength(list); i < length; i++) {
647 if (values) {
648 result[list[i]] = values[i];
649 } else {
650 result[list[i][0]] = list[i][1];
651 }
652 }
653 return result;
654 };
655
656 // Generator function to create the findIndex and findLastIndex functions.
657 var createPredicateIndexFinder = function(dir) {
658 return function(array, predicate, context) {
659 predicate = cb(predicate, context);
660 var length = getLength(array);
661 var index = dir > 0 ? 0 : length - 1;
662 for (; index >= 0 && index < length; index += dir) {
663 if (predicate(array[index], index, array)) return index;
664 }
665 return -1;
666 };
667 };
668
669 // Returns the first index on an array-like that passes a predicate test.
670 _.findIndex = createPredicateIndexFinder(1);
671 _.findLastIndex = createPredicateIndexFinder(-1);
672
673 // Use a comparator function to figure out the smallest index at which
674 // an object should be inserted so as to maintain order. Uses binary search.
675 _.sortedIndex = function(array, obj, iteratee, context) {
676 iteratee = cb(iteratee, context, 1);
677 var value = iteratee(obj);
678 var low = 0, high = getLength(array);
679 while (low < high) {
680 var mid = Math.floor((low + high) / 2);
681 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
682 }
683 return low;
684 };
685
686 // Generator function to create the indexOf and lastIndexOf functions.
687 var createIndexFinder = function(dir, predicateFind, sortedIndex) {
688 return function(array, item, idx) {
689 var i = 0, length = getLength(array);
690 if (typeof idx == 'number') {
691 if (dir > 0) {
692 i = idx >= 0 ? idx : Math.max(idx + length, i);
693 } else {
694 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
695 }
696 } else if (sortedIndex && idx && length) {
697 idx = sortedIndex(array, item);
698 return array[idx] === item ? idx : -1;
699 }
700 if (item !== item) {
701 idx = predicateFind(slice.call(array, i, length), _.isNaN);
702 return idx >= 0 ? idx + i : -1;
703 }
704 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
705 if (array[idx] === item) return idx;
706 }
707 return -1;
708 };
709 };
710
711 // Return the position of the first occurrence of an item in an array,
712 // or -1 if the item is not included in the array.
713 // If the array is large and already in sort order, pass `true`
714 // for **isSorted** to use binary search.
715 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
716 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
717
718 // Generate an integer Array containing an arithmetic progression. A port of
719 // the native Python `range()` function. See
720 // [the Python documentation](http://docs.python.org/library/functions.html#range).
721 _.range = function(start, stop, step) {
722 if (stop == null) {
723 stop = start || 0;
724 start = 0;
725 }
726 if (!step) {
727 step = stop < start ? -1 : 1;
728 }
729
730 var length = Math.max(Math.ceil((stop - start) / step), 0);
731 var range = Array(length);
732
733 for (var idx = 0; idx < length; idx++, start += step) {
734 range[idx] = start;
735 }
736
737 return range;
738 };
739
740 // Chunk a single array into multiple arrays, each containing `count` or fewer
741 // items.
742 _.chunk = function(array, count) {
743 if (count == null || count < 1) return [];
744 var result = [];
745 var i = 0, length = array.length;
746 while (i < length) {
747 result.push(slice.call(array, i, i += count));
748 }
749 return result;
750 };
751
752 // Function (ahem) Functions
753 // ------------------
754
755 // Determines whether to execute a function as a constructor
756 // or a normal function with the provided arguments.
757 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
758 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
759 var self = baseCreate(sourceFunc.prototype);
760 var result = sourceFunc.apply(self, args);
761 if (_.isObject(result)) return result;
762 return self;
763 };
764
765 // Create a function bound to a given object (assigning `this`, and arguments,
766 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
767 // available.
768 _.bind = restArguments(function(func, context, args) {
769 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
770 var bound = restArguments(function(callArgs) {
771 return executeBound(func, bound, context, this, args.concat(callArgs));
772 });
773 return bound;
774 });
775
776 // Partially apply a function by creating a version that has had some of its
777 // arguments pre-filled, without changing its dynamic `this` context. _ acts
778 // as a placeholder by default, allowing any combination of arguments to be
779 // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
780 _.partial = restArguments(function(func, boundArgs) {
781 var placeholder = _.partial.placeholder;
782 var bound = function() {
783 var position = 0, length = boundArgs.length;
784 var args = Array(length);
785 for (var i = 0; i < length; i++) {
786 args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
787 }
788 while (position < arguments.length) args.push(arguments[position++]);
789 return executeBound(func, bound, this, this, args);
790 };
791 return bound;
792 });
793
794 _.partial.placeholder = _;
795
796 // Bind a number of an object's methods to that object. Remaining arguments
797 // are the method names to be bound. Useful for ensuring that all callbacks
798 // defined on an object belong to it.
799 _.bindAll = restArguments(function(obj, keys) {
800 keys = flatten(keys, false, false);
801 var index = keys.length;
802 if (index < 1) throw new Error('bindAll must be passed function names');
803 while (index--) {
804 var key = keys[index];
805 obj[key] = _.bind(obj[key], obj);
806 }
807 });
808
809 // Memoize an expensive function by storing its results.
810 _.memoize = function(func, hasher) {
811 var memoize = function(key) {
812 var cache = memoize.cache;
813 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
814 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
815 return cache[address];
816 };
817 memoize.cache = {};
818 return memoize;
819 };
820
821 // Delays a function for the given number of milliseconds, and then calls
822 // it with the arguments supplied.
823 _.delay = restArguments(function(func, wait, args) {
824 return setTimeout(function() {
825 return func.apply(null, args);
826 }, wait);
827 });
828
829 // Defers a function, scheduling it to run after the current call stack has
830 // cleared.
831 _.defer = _.partial(_.delay, _, 1);
832
833 // Returns a function, that, when invoked, will only be triggered at most once
834 // during a given window of time. Normally, the throttled function will run
835 // as much as it can, without ever going more than once per `wait` duration;
836 // but if you'd like to disable the execution on the leading edge, pass
837 // `{leading: false}`. To disable execution on the trailing edge, ditto.
838 _.throttle = function(func, wait, options) {
839 var timeout, context, args, result;
840 var previous = 0;
841 if (!options) options = {};
842
843 var later = function() {
844 previous = options.leading === false ? 0 : _.now();
845 timeout = null;
846 result = func.apply(context, args);
847 if (!timeout) context = args = null;
848 };
849
850 var throttled = function() {
851 var now = _.now();
852 if (!previous && options.leading === false) previous = now;
853 var remaining = wait - (now - previous);
854 context = this;
855 args = arguments;
856 if (remaining <= 0 || remaining > wait) {
857 if (timeout) {
858 clearTimeout(timeout);
859 timeout = null;
860 }
861 previous = now;
862 result = func.apply(context, args);
863 if (!timeout) context = args = null;
864 } else if (!timeout && options.trailing !== false) {
865 timeout = setTimeout(later, remaining);
866 }
867 return result;
868 };
869
870 throttled.cancel = function() {
871 clearTimeout(timeout);
872 previous = 0;
873 timeout = context = args = null;
874 };
875
876 return throttled;
877 };
878
879 // Returns a function, that, as long as it continues to be invoked, will not
880 // be triggered. The function will be called after it stops being called for
881 // N milliseconds. If `immediate` is passed, trigger the function on the
882 // leading edge, instead of the trailing.
883 _.debounce = function(func, wait, immediate) {
884 var timeout, result;
885
886 var later = function(context, args) {
887 timeout = null;
888 if (args) result = func.apply(context, args);
889 };
890
891 var debounced = restArguments(function(args) {
892 if (timeout) clearTimeout(timeout);
893 if (immediate) {
894 var callNow = !timeout;
895 timeout = setTimeout(later, wait);
896 if (callNow) result = func.apply(this, args);
897 } else {
898 timeout = _.delay(later, wait, this, args);
899 }
900
901 return result;
902 });
903
904 debounced.cancel = function() {
905 clearTimeout(timeout);
906 timeout = null;
907 };
908
909 return debounced;
910 };
911
912 // Returns the first function passed as an argument to the second,
913 // allowing you to adjust arguments, run code before and after, and
914 // conditionally execute the original function.
915 _.wrap = function(func, wrapper) {
916 return _.partial(wrapper, func);
917 };
918
919 // Returns a negated version of the passed-in predicate.
920 _.negate = function(predicate) {
921 return function() {
922 return !predicate.apply(this, arguments);
923 };
924 };
925
926 // Returns a function that is the composition of a list of functions, each
927 // consuming the return value of the function that follows.
928 _.compose = function() {
929 var args = arguments;
930 var start = args.length - 1;
931 return function() {
932 var i = start;
933 var result = args[start].apply(this, arguments);
934 while (i--) result = args[i].call(this, result);
935 return result;
936 };
937 };
938
939 // Returns a function that will only be executed on and after the Nth call.
940 _.after = function(times, func) {
941 return function() {
942 if (--times < 1) {
943 return func.apply(this, arguments);
944 }
945 };
946 };
947
948 // Returns a function that will only be executed up to (but not including) the Nth call.
949 _.before = function(times, func) {
950 var memo;
951 return function() {
952 if (--times > 0) {
953 memo = func.apply(this, arguments);
954 }
955 if (times <= 1) func = null;
956 return memo;
957 };
958 };
959
960 // Returns a function that will be executed at most one time, no matter how
961 // often you call it. Useful for lazy initialization.
962 _.once = _.partial(_.before, 2);
963
964 _.restArguments = restArguments;
965
966 // Object Functions
967 // ----------------
968
969 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
970 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
971 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
972 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
973
974 var collectNonEnumProps = function(obj, keys) {
975 var nonEnumIdx = nonEnumerableProps.length;
976 var constructor = obj.constructor;
977 var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;
978
979 // Constructor is a special case.
980 var prop = 'constructor';
981 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
982
983 while (nonEnumIdx--) {
984 prop = nonEnumerableProps[nonEnumIdx];
985 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
986 keys.push(prop);
987 }
988 }
989 };
990
991 // Retrieve the names of an object's own properties.
992 // Delegates to **ECMAScript 5**'s native `Object.keys`.
993 _.keys = function(obj) {
994 if (!_.isObject(obj)) return [];
995 if (nativeKeys) return nativeKeys(obj);
996 var keys = [];
997 for (var key in obj) if (_.has(obj, key)) keys.push(key);
998 // Ahem, IE < 9.
999 if (hasEnumBug) collectNonEnumProps(obj, keys);
1000 return keys;
1001 };
1002
1003 // Retrieve all the property names of an object.
1004 _.allKeys = function(obj) {
1005 if (!_.isObject(obj)) return [];
1006 var keys = [];
1007 for (var key in obj) keys.push(key);
1008 // Ahem, IE < 9.
1009 if (hasEnumBug) collectNonEnumProps(obj, keys);
1010 return keys;
1011 };
1012
1013 // Retrieve the values of an object's properties.
1014 _.values = function(obj) {
1015 var keys = _.keys(obj);
1016 var length = keys.length;
1017 var values = Array(length);
1018 for (var i = 0; i < length; i++) {
1019 values[i] = obj[keys[i]];
1020 }
1021 return values;
1022 };
1023
1024 // Returns the results of applying the iteratee to each element of the object.
1025 // In contrast to _.map it returns an object.
1026 _.mapObject = function(obj, iteratee, context) {
1027 iteratee = cb(iteratee, context);
1028 var keys = _.keys(obj),
1029 length = keys.length,
1030 results = {};
1031 for (var index = 0; index < length; index++) {
1032 var currentKey = keys[index];
1033 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
1034 }
1035 return results;
1036 };
1037
1038 // Convert an object into a list of `[key, value]` pairs.
1039 // The opposite of _.object.
1040 _.pairs = function(obj) {
1041 var keys = _.keys(obj);
1042 var length = keys.length;
1043 var pairs = Array(length);
1044 for (var i = 0; i < length; i++) {
1045 pairs[i] = [keys[i], obj[keys[i]]];
1046 }
1047 return pairs;
1048 };
1049
1050 // Invert the keys and values of an object. The values must be serializable.
1051 _.invert = function(obj) {
1052 var result = {};
1053 var keys = _.keys(obj);
1054 for (var i = 0, length = keys.length; i < length; i++) {
1055 result[obj[keys[i]]] = keys[i];
1056 }
1057 return result;
1058 };
1059
1060 // Return a sorted list of the function names available on the object.
1061 // Aliased as `methods`.
1062 _.functions = _.methods = function(obj) {
1063 var names = [];
1064 for (var key in obj) {
1065 if (_.isFunction(obj[key])) names.push(key);
1066 }
1067 return names.sort();
1068 };
1069
1070 // An internal function for creating assigner functions.
1071 var createAssigner = function(keysFunc, defaults) {
1072 return function(obj) {
1073 var length = arguments.length;
1074 if (defaults) obj = Object(obj);
1075 if (length < 2 || obj == null) return obj;
1076 for (var index = 1; index < length; index++) {
1077 var source = arguments[index],
1078 keys = keysFunc(source),
1079 l = keys.length;
1080 for (var i = 0; i < l; i++) {
1081 var key = keys[i];
1082 if (!defaults || obj[key] === void 0) obj[key] = source[key];
1083 }
1084 }
1085 return obj;
1086 };
1087 };
1088
1089 // Extend a given object with all the properties in passed-in object(s).
1090 _.extend = createAssigner(_.allKeys);
1091
1092 // Assigns a given object with all the own properties in the passed-in object(s).
1093 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
1094 _.extendOwn = _.assign = createAssigner(_.keys);
1095
1096 // Returns the first key on an object that passes a predicate test.
1097 _.findKey = function(obj, predicate, context) {
1098 predicate = cb(predicate, context);
1099 var keys = _.keys(obj), key;
1100 for (var i = 0, length = keys.length; i < length; i++) {
1101 key = keys[i];
1102 if (predicate(obj[key], key, obj)) return key;
1103 }
1104 };
1105
1106 // Internal pick helper function to determine if `obj` has key `key`.
1107 var keyInObj = function(value, key, obj) {
1108 return key in obj;
1109 };
1110
1111 // Return a copy of the object only containing the whitelisted properties.
1112 _.pick = restArguments(function(obj, keys) {
1113 var result = {}, iteratee = keys[0];
1114 if (obj == null) return result;
1115 if (_.isFunction(iteratee)) {
1116 if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
1117 keys = _.allKeys(obj);
1118 } else {
1119 iteratee = keyInObj;
1120 keys = flatten(keys, false, false);
1121 obj = Object(obj);
1122 }
1123 for (var i = 0, length = keys.length; i < length; i++) {
1124 var key = keys[i];
1125 var value = obj[key];
1126 if (iteratee(value, key, obj)) result[key] = value;
1127 }
1128 return result;
1129 });
1130
1131 // Return a copy of the object without the blacklisted properties.
1132 _.omit = restArguments(function(obj, keys) {
1133 var iteratee = keys[0], context;
1134 if (_.isFunction(iteratee)) {
1135 iteratee = _.negate(iteratee);
1136 if (keys.length > 1) context = keys[1];
1137 } else {
1138 keys = _.map(flatten(keys, false, false), String);
1139 iteratee = function(value, key) {
1140 return !_.contains(keys, key);
1141 };
1142 }
1143 return _.pick(obj, iteratee, context);
1144 });
1145
1146 // Fill in a given object with default properties.
1147 _.defaults = createAssigner(_.allKeys, true);
1148
1149 // Creates an object that inherits from the given prototype object.
1150 // If additional properties are provided then they will be added to the
1151 // created object.
1152 _.create = function(prototype, props) {
1153 var result = baseCreate(prototype);
1154 if (props) _.extendOwn(result, props);
1155 return result;
1156 };
1157
1158 // Create a (shallow-cloned) duplicate of an object.
1159 _.clone = function(obj) {
1160 if (!_.isObject(obj)) return obj;
1161 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
1162 };
1163
1164 // Invokes interceptor with the obj, and then returns obj.
1165 // The primary purpose of this method is to "tap into" a method chain, in
1166 // order to perform operations on intermediate results within the chain.
1167 _.tap = function(obj, interceptor) {
1168 interceptor(obj);
1169 return obj;
1170 };
1171
1172 // Returns whether an object has a given set of `key:value` pairs.
1173 _.isMatch = function(object, attrs) {
1174 var keys = _.keys(attrs), length = keys.length;
1175 if (object == null) return !length;
1176 var obj = Object(object);
1177 for (var i = 0; i < length; i++) {
1178 var key = keys[i];
1179 if (attrs[key] !== obj[key] || !(key in obj)) return false;
1180 }
1181 return true;
1182 };
1183
1184
1185 // Internal recursive comparison function for `isEqual`.
1186 var eq, deepEq;
1187 eq = function(a, b, aStack, bStack) {
1188 // Identical objects are equal. `0 === -0`, but they aren't identical.
1189 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
1190 if (a === b) return a !== 0 || 1 / a === 1 / b;
1191 // `null` or `undefined` only equal to itself (strict comparison).
1192 if (a == null || b == null) return false;
1193 // `NaN`s are equivalent, but non-reflexive.
1194 if (a !== a) return b !== b;
1195 // Exhaust primitive checks
1196 var type = typeof a;
1197 if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
1198 return deepEq(a, b, aStack, bStack);
1199 };
1200
1201 // Internal recursive comparison function for `isEqual`.
1202 deepEq = function(a, b, aStack, bStack) {
1203 // Unwrap any wrapped objects.
1204 if (a instanceof _) a = a._wrapped;
1205 if (b instanceof _) b = b._wrapped;
1206 // Compare `[[Class]]` names.
1207 var className = toString.call(a);
1208 if (className !== toString.call(b)) return false;
1209 switch (className) {
1210 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
1211 case '[object RegExp]':
1212 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
1213 case '[object String]':
1214 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
1215 // equivalent to `new String("5")`.
1216 return '' + a === '' + b;
1217 case '[object Number]':
1218 // `NaN`s are equivalent, but non-reflexive.
1219 // Object(NaN) is equivalent to NaN.
1220 if (+a !== +a) return +b !== +b;
1221 // An `egal` comparison is performed for other numeric values.
1222 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
1223 case '[object Date]':
1224 case '[object Boolean]':
1225 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
1226 // millisecond representations. Note that invalid dates with millisecond representations
1227 // of `NaN` are not equivalent.
1228 return +a === +b;
1229 case '[object Symbol]':
1230 return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
1231 }
1232
1233 var areArrays = className === '[object Array]';
1234 if (!areArrays) {
1235 if (typeof a != 'object' || typeof b != 'object') return false;
1236
1237 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
1238 // from different frames are.
1239 var aCtor = a.constructor, bCtor = b.constructor;
1240 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
1241 _.isFunction(bCtor) && bCtor instanceof bCtor)
1242 && ('constructor' in a && 'constructor' in b)) {
1243 return false;
1244 }
1245 }
1246 // Assume equality for cyclic structures. The algorithm for detecting cyclic
1247 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
1248
1249 // Initializing stack of traversed objects.
1250 // It's done here since we only need them for objects and arrays comparison.
1251 aStack = aStack || [];
1252 bStack = bStack || [];
1253 var length = aStack.length;
1254 while (length--) {
1255 // Linear search. Performance is inversely proportional to the number of
1256 // unique nested structures.
1257 if (aStack[length] === a) return bStack[length] === b;
1258 }
1259
1260 // Add the first object to the stack of traversed objects.
1261 aStack.push(a);
1262 bStack.push(b);
1263
1264 // Recursively compare objects and arrays.
1265 if (areArrays) {
1266 // Compare array lengths to determine if a deep comparison is necessary.
1267 length = a.length;
1268 if (length !== b.length) return false;
1269 // Deep compare the contents, ignoring non-numeric properties.
1270 while (length--) {
1271 if (!eq(a[length], b[length], aStack, bStack)) return false;
1272 }
1273 } else {
1274 // Deep compare objects.
1275 var keys = _.keys(a), key;
1276 length = keys.length;
1277 // Ensure that both objects contain the same number of properties before comparing deep equality.
1278 if (_.keys(b).length !== length) return false;
1279 while (length--) {
1280 // Deep compare each member
1281 key = keys[length];
1282 if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
1283 }
1284 }
1285 // Remove the first object from the stack of traversed objects.
1286 aStack.pop();
1287 bStack.pop();
1288 return true;
1289 };
1290
1291 // Perform a deep comparison to check if two objects are equal.
1292 _.isEqual = function(a, b) {
1293 return eq(a, b);
1294 };
1295
1296 // Is a given array, string, or object empty?
1297 // An "empty" object has no enumerable own-properties.
1298 _.isEmpty = function(obj) {
1299 if (obj == null) return true;
1300 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
1301 return _.keys(obj).length === 0;
1302 };
1303
1304 // Is a given value a DOM element?
1305 _.isElement = function(obj) {
1306 return !!(obj && obj.nodeType === 1);
1307 };
1308
1309 // Is a given value an array?
1310 // Delegates to ECMA5's native Array.isArray
1311 _.isArray = nativeIsArray || function(obj) {
1312 return toString.call(obj) === '[object Array]';
1313 };
1314
1315 // Is a given variable an object?
1316 _.isObject = function(obj) {
1317 var type = typeof obj;
1318 return type === 'function' || type === 'object' && !!obj;
1319 };
1320
1321 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError, isMap, isWeakMap, isSet, isWeakSet.
1322 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol', 'Map', 'WeakMap', 'Set', 'WeakSet'], function(name) {
1323 _['is' + name] = function(obj) {
1324 return toString.call(obj) === '[object ' + name + ']';
1325 };
1326 });
1327
1328 // Define a fallback version of the method in browsers (ahem, IE < 9), where
1329 // there isn't any inspectable "Arguments" type.
1330 if (!_.isArguments(arguments)) {
1331 _.isArguments = function(obj) {
1332 return _.has(obj, 'callee');
1333 };
1334 }
1335
1336 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
1337 // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
1338 var nodelist = root.document && root.document.childNodes;
1339 if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
1340 _.isFunction = function(obj) {
1341 return typeof obj == 'function' || false;
1342 };
1343 }
1344
1345 // Is a given object a finite number?
1346 _.isFinite = function(obj) {
1347 return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj));
1348 };
1349
1350 // Is the given value `NaN`?
1351 _.isNaN = function(obj) {
1352 return _.isNumber(obj) && isNaN(obj);
1353 };
1354
1355 // Is a given value a boolean?
1356 _.isBoolean = function(obj) {
1357 return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
1358 };
1359
1360 // Is a given value equal to null?
1361 _.isNull = function(obj) {
1362 return obj === null;
1363 };
1364
1365 // Is a given variable undefined?
1366 _.isUndefined = function(obj) {
1367 return obj === void 0;
1368 };
1369
1370 // Shortcut function for checking if an object has a given property directly
1371 // on itself (in other words, not on a prototype).
1372 _.has = function(obj, path) {
1373 if (!_.isArray(path)) {
1374 return obj != null && hasOwnProperty.call(obj, path);
1375 }
1376 var length = path.length;
1377 for (var i = 0; i < length; i++) {
1378 var key = path[i];
1379 if (obj == null || !hasOwnProperty.call(obj, key)) {
1380 return false;
1381 }
1382 obj = obj[key];
1383 }
1384 return !!length;
1385 };
1386
1387 // Utility Functions
1388 // -----------------
1389
1390 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
1391 // previous owner. Returns a reference to the Underscore object.
1392 _.noConflict = function() {
1393 root._ = previousUnderscore;
1394 return this;
1395 };
1396
1397 // Keep the identity function around for default iteratees.
1398 _.identity = function(value) {
1399 return value;
1400 };
1401
1402 // Predicate-generating functions. Often useful outside of Underscore.
1403 _.constant = function(value) {
1404 return function() {
1405 return value;
1406 };
1407 };
1408
1409 _.noop = function(){};
1410
1411 // Creates a function that, when passed an object, will traverse that object’s
1412 // properties down the given `path`, specified as an array of keys or indexes.
1413 _.property = function(path) {
1414 if (!_.isArray(path)) {
1415 return shallowProperty(path);
1416 }
1417 return function(obj) {
1418 return deepGet(obj, path);
1419 };
1420 };
1421
1422 // Generates a function for a given object that returns a given property.
1423 _.propertyOf = function(obj) {
1424 if (obj == null) {
1425 return function(){};
1426 }
1427 return function(path) {
1428 return !_.isArray(path) ? obj[path] : deepGet(obj, path);
1429 };
1430 };
1431
1432 // Returns a predicate for checking whether an object has a given set of
1433 // `key:value` pairs.
1434 _.matcher = _.matches = function(attrs) {
1435 attrs = _.extendOwn({}, attrs);
1436 return function(obj) {
1437 return _.isMatch(obj, attrs);
1438 };
1439 };
1440
1441 // Run a function **n** times.
1442 _.times = function(n, iteratee, context) {
1443 var accum = Array(Math.max(0, n));
1444 iteratee = optimizeCb(iteratee, context, 1);
1445 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
1446 return accum;
1447 };
1448
1449 // Return a random integer between min and max (inclusive).
1450 _.random = function(min, max) {
1451 if (max == null) {
1452 max = min;
1453 min = 0;
1454 }
1455 return min + Math.floor(Math.random() * (max - min + 1));
1456 };
1457
1458 // A (possibly faster) way to get the current timestamp as an integer.
1459 _.now = Date.now || function() {
1460 return new Date().getTime();
1461 };
1462
1463 // List of HTML entities for escaping.
1464 var escapeMap = {
1465 '&': '&',
1466 '<': '<',
1467 '>': '>',
1468 '"': '"',
1469 "'": ''',
1470 '`': '`'
1471 };
1472 var unescapeMap = _.invert(escapeMap);
1473
1474 // Functions for escaping and unescaping strings to/from HTML interpolation.
1475 var createEscaper = function(map) {
1476 var escaper = function(match) {
1477 return map[match];
1478 };
1479 // Regexes for identifying a key that needs to be escaped.
1480 var source = '(?:' + _.keys(map).join('|') + ')';
1481 var testRegexp = RegExp(source);
1482 var replaceRegexp = RegExp(source, 'g');
1483 return function(string) {
1484 string = string == null ? '' : '' + string;
1485 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
1486 };
1487 };
1488 _.escape = createEscaper(escapeMap);
1489 _.unescape = createEscaper(unescapeMap);
1490
1491 // Traverses the children of `obj` along `path`. If a child is a function, it
1492 // is invoked with its parent as context. Returns the value of the final
1493 // child, or `fallback` if any child is undefined.
1494 _.result = function(obj, path, fallback) {
1495 if (!_.isArray(path)) path = [path];
1496 var length = path.length;
1497 if (!length) {
1498 return _.isFunction(fallback) ? fallback.call(obj) : fallback;
1499 }
1500 for (var i = 0; i < length; i++) {
1501 var prop = obj == null ? void 0 : obj[path[i]];
1502 if (prop === void 0) {
1503 prop = fallback;
1504 i = length; // Ensure we don't continue iterating.
1505 }
1506 obj = _.isFunction(prop) ? prop.call(obj) : prop;
1507 }
1508 return obj;
1509 };
1510
1511 // Generate a unique integer id (unique within the entire client session).
1512 // Useful for temporary DOM ids.
1513 var idCounter = 0;
1514 _.uniqueId = function(prefix) {
1515 var id = ++idCounter + '';
1516 return prefix ? prefix + id : id;
1517 };
1518
1519 // By default, Underscore uses ERB-style template delimiters, change the
1520 // following template settings to use alternative delimiters.
1521 _.templateSettings = {
1522 evaluate: /<%([\s\S]+?)%>/g,
1523 interpolate: /<%=([\s\S]+?)%>/g,
1524 escape: /<%-([\s\S]+?)%>/g
1525 };
1526
1527 // When customizing `templateSettings`, if you don't want to define an
1528 // interpolation, evaluation or escaping regex, we need one that is
1529 // guaranteed not to match.
1530 var noMatch = /(.)^/;
1531
1532 // Certain characters need to be escaped so that they can be put into a
1533 // string literal.
1534 var escapes = {
1535 "'": "'",
1536 '\\': '\\',
1537 '\r': 'r',
1538 '\n': 'n',
1539 '\u2028': 'u2028',
1540 '\u2029': 'u2029'
1541 };
1542
1543 var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
1544
1545 var escapeChar = function(match) {
1546 return '\\' + escapes[match];
1547 };
1548
1549 // JavaScript micro-templating, similar to John Resig's implementation.
1550 // Underscore templating handles arbitrary delimiters, preserves whitespace,
1551 // and correctly escapes quotes within interpolated code.
1552 // NB: `oldSettings` only exists for backwards compatibility.
1553 _.template = function(text, settings, oldSettings) {
1554 if (!settings && oldSettings) settings = oldSettings;
1555 settings = _.defaults({}, settings, _.templateSettings);
1556
1557 // Combine delimiters into one regular expression via alternation.
1558 var matcher = RegExp([
1559 (settings.escape || noMatch).source,
1560 (settings.interpolate || noMatch).source,
1561 (settings.evaluate || noMatch).source
1562 ].join('|') + '|$', 'g');
1563
1564 // Compile the template source, escaping string literals appropriately.
1565 var index = 0;
1566 var source = "__p+='";
1567 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
1568 source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
1569 index = offset + match.length;
1570
1571 if (escape) {
1572 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
1573 } else if (interpolate) {
1574 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
1575 } else if (evaluate) {
1576 source += "';\n" + evaluate + "\n__p+='";
1577 }
1578
1579 // Adobe VMs need the match returned to produce the correct offset.
1580 return match;
1581 });
1582 source += "';\n";
1583
1584 // If a variable is not specified, place data values in local scope.
1585 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
1586
1587 source = "var __t,__p='',__j=Array.prototype.join," +
1588 "print=function(){__p+=__j.call(arguments,'');};\n" +
1589 source + 'return __p;\n';
1590
1591 var render;
1592 try {
1593 render = new Function(settings.variable || 'obj', '_', source);
1594 } catch (e) {
1595 e.source = source;
1596 throw e;
1597 }
1598
1599 var template = function(data) {
1600 return render.call(this, data, _);
1601 };
1602
1603 // Provide the compiled source as a convenience for precompilation.
1604 var argument = settings.variable || 'obj';
1605 template.source = 'function(' + argument + '){\n' + source + '}';
1606
1607 return template;
1608 };
1609
1610 // Add a "chain" function. Start chaining a wrapped Underscore object.
1611 _.chain = function(obj) {
1612 var instance = _(obj);
1613 instance._chain = true;
1614 return instance;
1615 };
1616
1617 // OOP
1618 // ---------------
1619 // If Underscore is called as a function, it returns a wrapped object that
1620 // can be used OO-style. This wrapper holds altered versions of all the
1621 // underscore functions. Wrapped objects may be chained.
1622
1623 // Helper function to continue chaining intermediate results.
1624 var chainResult = function(instance, obj) {
1625 return instance._chain ? _(obj).chain() : obj;
1626 };
1627
1628 // Add your own custom functions to the Underscore object.
1629 _.mixin = function(obj) {
1630 _.each(_.functions(obj), function(name) {
1631 var func = _[name] = obj[name];
1632 _.prototype[name] = function() {
1633 var args = [this._wrapped];
1634 push.apply(args, arguments);
1635 return chainResult(this, func.apply(_, args));
1636 };
1637 });
1638 return _;
1639 };
1640
1641 // Add all of the Underscore functions to the wrapper object.
1642 _.mixin(_);
1643
1644 // Add all mutator Array functions to the wrapper.
1645 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
1646 var method = ArrayProto[name];
1647 _.prototype[name] = function() {
1648 var obj = this._wrapped;
1649 method.apply(obj, arguments);
1650 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
1651 return chainResult(this, obj);
1652 };
1653 });
1654
1655 // Add all accessor Array functions to the wrapper.
1656 _.each(['concat', 'join', 'slice'], function(name) {
1657 var method = ArrayProto[name];
1658 _.prototype[name] = function() {
1659 return chainResult(this, method.apply(this._wrapped, arguments));
1660 };
1661 });
1662
1663 // Extracts the result from a wrapped and chained object.
1664 _.prototype.value = function() {
1665 return this._wrapped;
1666 };
1667
1668 // Provide unwrapping proxy for some methods used in engine operations
1669 // such as arithmetic and JSON stringification.
1670 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
1671
1672 _.prototype.toString = function() {
1673 return String(this._wrapped);
1674 };
1675
1676 // AMD registration happens at the end for compatibility with AMD loaders
1677 // that may not enforce next-turn semantics on modules. Even though general
1678 // practice for AMD registration is to be anonymous, underscore registers
1679 // as a named module because, like jQuery, it is a base library that is
1680 // popular enough to be bundled in a third party lib, but not be part of
1681 // an AMD load request. Those cases could generate an error when an
1682 // anonymous define() is called outside of a loader request.
1683 if (typeof define == 'function' && define.amd) {
1684 define('underscore', [], function() {
1685 return _;
1686 });
1687 }
1688}());