2 // http://underscorejs.org
3 // (c) 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
4 // Underscore may be freely distributed under the MIT license.
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 ||
18 // Save the previous value of the `_` variable.
19 var previousUnderscore = root._;
21 // Save bytes in the minified (but not gzipped) version:
22 var ArrayProto = Array.prototype, ObjProto = Object.prototype;
24 // Create quick reference variables for speed access to core prototypes.
25 var push = ArrayProto.push,
26 slice = ArrayProto.slice,
27 toString = ObjProto.toString,
28 hasOwnProperty = ObjProto.hasOwnProperty;
30 // All **ECMAScript 5** native function implementations that we hope to use
32 var nativeIsArray = Array.isArray,
33 nativeKeys = Object.keys,
34 nativeCreate = Object.create;
36 // Naked function reference for surrogate-prototype-swapping.
37 var Ctor = function(){};
39 // Create a safe reference to the Underscore object for use below.
40 var _ = function(obj) {
41 if (obj instanceof _) return obj;
42 if (!(this instanceof _)) return new _(obj);
46 // Export the Underscore object for **Node.js**, with
47 // backwards-compatibility for their old module API. If we're in
48 // the browser, add `_` as a global object.
49 // (`nodeType` is checked to ensure that `module`
50 // and `exports` are not HTML elements.)
51 if (typeof exports != 'undefined' && !exports.nodeType) {
52 if (typeof module != 'undefined' && !module.nodeType && module.exports) {
53 exports = module.exports = _;
63 // Internal function that returns an efficient (for current engines) version
64 // of the passed-in callback, to be repeatedly applied in other Underscore
66 var optimizeCb = function(func, context, argCount) {
67 if (context === void 0) return func;
68 switch (argCount == null ? 3 : argCount) {
69 case 1: return function(value) {
70 return func.call(context, value);
72 // The 2-parameter case has been omitted only because no current consumers
74 case 3: return function(value, index, collection) {
75 return func.call(context, value, index, collection);
77 case 4: return function(accumulator, value, index, collection) {
78 return func.call(context, accumulator, value, index, collection);
82 return func.apply(context, arguments);
86 // An internal function to generate callbacks that can be applied to each
87 // element in a collection, returning the desired result — either `identity`,
88 // an arbitrary callback, a property matcher, or a property accessor.
89 var cb = function(value, context, argCount) {
90 if (value == null) return _.identity;
91 if (_.isFunction(value)) return optimizeCb(value, context, argCount);
92 if (_.isObject(value)) return _.matcher(value);
93 return _.property(value);
96 // An external wrapper for the internal callback generator.
97 _.iteratee = function(value, context) {
98 return cb(value, context, Infinity);
101 // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
102 // This accumulates the arguments passed into an array, after a given index.
103 var restArgs = function(func, startIndex) {
104 startIndex = startIndex == null ? func.length - 1 : +startIndex;
106 var length = Math.max(arguments.length - startIndex, 0);
107 var rest = Array(length);
108 for (var index = 0; index < length; index++) {
109 rest[index] = arguments[index + startIndex];
111 switch (startIndex) {
112 case 0: return func.call(this, rest);
113 case 1: return func.call(this, arguments[0], rest);
114 case 2: return func.call(this, arguments[0], arguments[1], rest);
116 var args = Array(startIndex + 1);
117 for (index = 0; index < startIndex; index++) {
118 args[index] = arguments[index];
120 args[startIndex] = rest;
121 return func.apply(this, args);
125 // An internal function for creating a new object that inherits from another.
126 var baseCreate = function(prototype) {
127 if (!_.isObject(prototype)) return {};
128 if (nativeCreate) return nativeCreate(prototype);
129 Ctor.prototype = prototype;
130 var result = new Ctor;
131 Ctor.prototype = null;
135 var property = function(key) {
136 return function(obj) {
137 return obj == null ? void 0 : obj[key];
141 // Helper for collection methods to determine whether a collection
142 // should be iterated as an array or as an object.
143 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
144 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
145 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
146 var getLength = property('length');
147 var isArrayLike = function(collection) {
148 var length = getLength(collection);
149 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
152 // Collection Functions
153 // --------------------
155 // The cornerstone, an `each` implementation, aka `forEach`.
156 // Handles raw objects in addition to array-likes. Treats all
157 // sparse array-likes as if they were dense.
158 _.each = _.forEach = function(obj, iteratee, context) {
159 iteratee = optimizeCb(iteratee, context);
161 if (isArrayLike(obj)) {
162 for (i = 0, length = obj.length; i < length; i++) {
163 iteratee(obj[i], i, obj);
166 var keys = _.keys(obj);
167 for (i = 0, length = keys.length; i < length; i++) {
168 iteratee(obj[keys[i]], keys[i], obj);
174 // Return the results of applying the iteratee to each element.
175 _.map = _.collect = function(obj, iteratee, context) {
176 iteratee = cb(iteratee, context);
177 var keys = !isArrayLike(obj) && _.keys(obj),
178 length = (keys || obj).length,
179 results = Array(length);
180 for (var index = 0; index < length; index++) {
181 var currentKey = keys ? keys[index] : index;
182 results[index] = iteratee(obj[currentKey], currentKey, obj);
187 // Create a reducing function iterating left or right.
188 var createReduce = function(dir) {
189 // Wrap code that reassigns argument variables in a separate function than
190 // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
191 var reducer = function(obj, iteratee, memo, initial) {
192 var keys = !isArrayLike(obj) && _.keys(obj),
193 length = (keys || obj).length,
194 index = dir > 0 ? 0 : length - 1;
196 memo = obj[keys ? keys[index] : index];
199 for (; index >= 0 && index < length; index += dir) {
200 var currentKey = keys ? keys[index] : index;
201 memo = iteratee(memo, obj[currentKey], currentKey, obj);
206 return function(obj, iteratee, memo, context) {
207 var initial = arguments.length >= 3;
208 return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
212 // **Reduce** builds up a single result from a list of values, aka `inject`,
214 _.reduce = _.foldl = _.inject = createReduce(1);
216 // The right-associative version of reduce, also known as `foldr`.
217 _.reduceRight = _.foldr = createReduce(-1);
219 // Return the first value which passes a truth test. Aliased as `detect`.
220 _.find = _.detect = function(obj, predicate, context) {
222 if (isArrayLike(obj)) {
223 key = _.findIndex(obj, predicate, context);
225 key = _.findKey(obj, predicate, context);
227 if (key !== void 0 && key !== -1) return obj[key];
230 // Return all the elements that pass a truth test.
231 // Aliased as `select`.
232 _.filter = _.select = function(obj, predicate, context) {
234 predicate = cb(predicate, context);
235 _.each(obj, function(value, index, list) {
236 if (predicate(value, index, list)) results.push(value);
241 // Return all the elements for which a truth test fails.
242 _.reject = function(obj, predicate, context) {
243 return _.filter(obj, _.negate(cb(predicate)), context);
246 // Determine whether all of the elements match a truth test.
248 _.every = _.all = function(obj, predicate, context) {
249 predicate = cb(predicate, context);
250 var keys = !isArrayLike(obj) && _.keys(obj),
251 length = (keys || obj).length;
252 for (var index = 0; index < length; index++) {
253 var currentKey = keys ? keys[index] : index;
254 if (!predicate(obj[currentKey], currentKey, obj)) return false;
259 // Determine if at least one element in the object matches a truth test.
261 _.some = _.any = function(obj, predicate, context) {
262 predicate = cb(predicate, context);
263 var keys = !isArrayLike(obj) && _.keys(obj),
264 length = (keys || obj).length;
265 for (var index = 0; index < length; index++) {
266 var currentKey = keys ? keys[index] : index;
267 if (predicate(obj[currentKey], currentKey, obj)) return true;
272 // Determine if the array or object contains a given item (using `===`).
273 // Aliased as `includes` and `include`.
274 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
275 if (!isArrayLike(obj)) obj = _.values(obj);
276 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
277 return _.indexOf(obj, item, fromIndex) >= 0;
280 // Invoke a method (with arguments) on every item in a collection.
281 _.invoke = restArgs(function(obj, method, args) {
282 var isFunc = _.isFunction(method);
283 return _.map(obj, function(value) {
284 var func = isFunc ? method : value[method];
285 return func == null ? func : func.apply(value, args);
289 // Convenience version of a common use case of `map`: fetching a property.
290 _.pluck = function(obj, key) {
291 return _.map(obj, _.property(key));
294 // Convenience version of a common use case of `filter`: selecting only objects
295 // containing specific `key:value` pairs.
296 _.where = function(obj, attrs) {
297 return _.filter(obj, _.matcher(attrs));
300 // Convenience version of a common use case of `find`: getting the first object
301 // containing specific `key:value` pairs.
302 _.findWhere = function(obj, attrs) {
303 return _.find(obj, _.matcher(attrs));
306 // Return the maximum element (or element-based computation).
307 _.max = function(obj, iteratee, context) {
308 var result = -Infinity, lastComputed = -Infinity,
310 if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
311 obj = isArrayLike(obj) ? obj : _.values(obj);
312 for (var i = 0, length = obj.length; i < length; i++) {
314 if (value != null && value > result) {
319 iteratee = cb(iteratee, context);
320 _.each(obj, function(v, index, list) {
321 computed = iteratee(v, index, list);
322 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
324 lastComputed = computed;
331 // Return the minimum element (or element-based computation).
332 _.min = function(obj, iteratee, context) {
333 var result = Infinity, lastComputed = Infinity,
335 if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
336 obj = isArrayLike(obj) ? obj : _.values(obj);
337 for (var i = 0, length = obj.length; i < length; i++) {
339 if (value != null && value < result) {
344 iteratee = cb(iteratee, context);
345 _.each(obj, function(v, index, list) {
346 computed = iteratee(v, index, list);
347 if (computed < lastComputed || computed === Infinity && result === Infinity) {
349 lastComputed = computed;
356 // Shuffle a collection.
357 _.shuffle = function(obj) {
358 return _.sample(obj, Infinity);
361 // Sample **n** random values from a collection using the modern version of the
362 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
363 // If **n** is not specified, returns a single random element.
364 // The internal `guard` argument allows it to work with `map`.
365 _.sample = function(obj, n, guard) {
366 if (n == null || guard) {
367 if (!isArrayLike(obj)) obj = _.values(obj);
368 return obj[_.random(obj.length - 1)];
370 var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj);
371 var length = getLength(sample);
372 n = Math.max(Math.min(n, length), 0);
373 var last = length - 1;
374 for (var index = 0; index < n; index++) {
375 var rand = _.random(index, last);
376 var temp = sample[index];
377 sample[index] = sample[rand];
380 return sample.slice(0, n);
383 // Sort the object's values by a criterion produced by an iteratee.
384 _.sortBy = function(obj, iteratee, context) {
386 iteratee = cb(iteratee, context);
387 return _.pluck(_.map(obj, function(value, key, list) {
391 criteria: iteratee(value, key, list)
393 }).sort(function(left, right) {
394 var a = left.criteria;
395 var b = right.criteria;
397 if (a > b || a === void 0) return 1;
398 if (a < b || b === void 0) return -1;
400 return left.index - right.index;
404 // An internal function used for aggregate "group by" operations.
405 var group = function(behavior, partition) {
406 return function(obj, iteratee, context) {
407 var result = partition ? [[], []] : {};
408 iteratee = cb(iteratee, context);
409 _.each(obj, function(value, index) {
410 var key = iteratee(value, index, obj);
411 behavior(result, value, key);
417 // Groups the object's values by a criterion. Pass either a string attribute
418 // to group by, or a function that returns the criterion.
419 _.groupBy = group(function(result, value, key) {
420 if (_.has(result, key)) result[key].push(value); else result[key] = [value];
423 // Indexes the object's values by a criterion, similar to `groupBy`, but for
424 // when you know that your index values will be unique.
425 _.indexBy = group(function(result, value, key) {
429 // Counts instances of an object that group by a certain criterion. Pass
430 // either a string attribute to count by, or a function that returns the
432 _.countBy = group(function(result, value, key) {
433 if (_.has(result, key)) result[key]++; else result[key] = 1;
436 var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
437 // Safely create a real, live array from anything iterable.
438 _.toArray = function(obj) {
440 if (_.isArray(obj)) return slice.call(obj);
441 if (_.isString(obj)) {
442 // Keep surrogate pair characters together
443 return obj.match(reStrSymbol);
445 if (isArrayLike(obj)) return _.map(obj, _.identity);
446 return _.values(obj);
449 // Return the number of elements in an object.
450 _.size = function(obj) {
451 if (obj == null) return 0;
452 return isArrayLike(obj) ? obj.length : _.keys(obj).length;
455 // Split a collection into two arrays: one whose elements all satisfy the given
456 // predicate, and one whose elements all do not satisfy the predicate.
457 _.partition = group(function(result, value, pass) {
458 result[pass ? 0 : 1].push(value);
464 // Get the first element of an array. Passing **n** will return the first N
465 // values in the array. Aliased as `head` and `take`. The **guard** check
466 // allows it to work with `_.map`.
467 _.first = _.head = _.take = function(array, n, guard) {
468 if (array == null) return void 0;
469 if (n == null || guard) return array[0];
470 return _.initial(array, array.length - n);
473 // Returns everything but the last entry of the array. Especially useful on
474 // the arguments object. Passing **n** will return all the values in
475 // the array, excluding the last N.
476 _.initial = function(array, n, guard) {
477 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
480 // Get the last element of an array. Passing **n** will return the last N
481 // values in the array.
482 _.last = function(array, n, guard) {
483 if (array == null) return void 0;
484 if (n == null || guard) return array[array.length - 1];
485 return _.rest(array, Math.max(0, array.length - n));
488 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
489 // Especially useful on the arguments object. Passing an **n** will return
490 // the rest N values in the array.
491 _.rest = _.tail = _.drop = function(array, n, guard) {
492 return slice.call(array, n == null || guard ? 1 : n);
495 // Trim out all falsy values from an array.
496 _.compact = function(array) {
497 return _.filter(array, _.identity);
500 // Internal implementation of a recursive `flatten` function.
501 var flatten = function(input, shallow, strict, output) {
502 output = output || [];
503 var idx = output.length;
504 for (var i = 0, length = getLength(input); i < length; i++) {
505 var value = input[i];
506 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
507 // Flatten current level of array or arguments object.
509 var j = 0, len = value.length;
510 while (j < len) output[idx++] = value[j++];
512 flatten(value, shallow, strict, output);
515 } else if (!strict) {
516 output[idx++] = value;
522 // Flatten out an array, either recursively (by default), or just one level.
523 _.flatten = function(array, shallow) {
524 return flatten(array, shallow, false);
527 // Return a version of the array that does not contain the specified value(s).
528 _.without = restArgs(function(array, otherArrays) {
529 return _.difference(array, otherArrays);
532 // Produce a duplicate-free version of the array. If the array has already
533 // been sorted, you have the option of using a faster algorithm.
534 // Aliased as `unique`.
535 _.uniq = _.unique = function(array, isSorted, iteratee, context) {
536 if (!_.isBoolean(isSorted)) {
541 if (iteratee != null) iteratee = cb(iteratee, context);
544 for (var i = 0, length = getLength(array); i < length; i++) {
545 var value = array[i],
546 computed = iteratee ? iteratee(value, i, array) : value;
548 if (!i || seen !== computed) result.push(value);
550 } else if (iteratee) {
551 if (!_.contains(seen, computed)) {
555 } else if (!_.contains(result, value)) {
562 // Produce an array that contains the union: each distinct element from all of
563 // the passed-in arrays.
564 _.union = restArgs(function(arrays) {
565 return _.uniq(flatten(arrays, true, true));
568 // Produce an array that contains every item shared between all the
570 _.intersection = function(array) {
572 var argsLength = arguments.length;
573 for (var i = 0, length = getLength(array); i < length; i++) {
575 if (_.contains(result, item)) continue;
577 for (j = 1; j < argsLength; j++) {
578 if (!_.contains(arguments[j], item)) break;
580 if (j === argsLength) result.push(item);
585 // Take the difference between one array and a number of other arrays.
586 // Only the elements present in just the first array will remain.
587 _.difference = restArgs(function(array, rest) {
588 rest = flatten(rest, true, true);
589 return _.filter(array, function(value){
590 return !_.contains(rest, value);
594 // Complement of _.zip. Unzip accepts an array of arrays and groups
595 // each array's elements on shared indices.
596 _.unzip = function(array) {
597 var length = array && _.max(array, getLength).length || 0;
598 var result = Array(length);
600 for (var index = 0; index < length; index++) {
601 result[index] = _.pluck(array, index);
606 // Zip together multiple lists into a single array -- elements that share
607 // an index go together.
608 _.zip = restArgs(_.unzip);
610 // Converts lists into objects. Pass either a single array of `[key, value]`
611 // pairs, or two parallel arrays of the same length -- one of keys, and one of
612 // the corresponding values.
613 _.object = function(list, values) {
615 for (var i = 0, length = getLength(list); i < length; i++) {
617 result[list[i]] = values[i];
619 result[list[i][0]] = list[i][1];
625 // Generator function to create the findIndex and findLastIndex functions.
626 var createPredicateIndexFinder = function(dir) {
627 return function(array, predicate, context) {
628 predicate = cb(predicate, context);
629 var length = getLength(array);
630 var index = dir > 0 ? 0 : length - 1;
631 for (; index >= 0 && index < length; index += dir) {
632 if (predicate(array[index], index, array)) return index;
638 // Returns the first index on an array-like that passes a predicate test.
639 _.findIndex = createPredicateIndexFinder(1);
640 _.findLastIndex = createPredicateIndexFinder(-1);
642 // Use a comparator function to figure out the smallest index at which
643 // an object should be inserted so as to maintain order. Uses binary search.
644 _.sortedIndex = function(array, obj, iteratee, context) {
645 iteratee = cb(iteratee, context, 1);
646 var value = iteratee(obj);
647 var low = 0, high = getLength(array);
649 var mid = Math.floor((low + high) / 2);
650 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
655 // Generator function to create the indexOf and lastIndexOf functions.
656 var createIndexFinder = function(dir, predicateFind, sortedIndex) {
657 return function(array, item, idx) {
658 var i = 0, length = getLength(array);
659 if (typeof idx == 'number') {
661 i = idx >= 0 ? idx : Math.max(idx + length, i);
663 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
665 } else if (sortedIndex && idx && length) {
666 idx = sortedIndex(array, item);
667 return array[idx] === item ? idx : -1;
670 idx = predicateFind(slice.call(array, i, length), _.isNaN);
671 return idx >= 0 ? idx + i : -1;
673 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
674 if (array[idx] === item) return idx;
680 // Return the position of the first occurrence of an item in an array,
681 // or -1 if the item is not included in the array.
682 // If the array is large and already in sort order, pass `true`
683 // for **isSorted** to use binary search.
684 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
685 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
687 // Generate an integer Array containing an arithmetic progression. A port of
688 // the native Python `range()` function. See
689 // [the Python documentation](http://docs.python.org/library/functions.html#range).
690 _.range = function(start, stop, step) {
696 step = stop < start ? -1 : 1;
699 var length = Math.max(Math.ceil((stop - start) / step), 0);
700 var range = Array(length);
702 for (var idx = 0; idx < length; idx++, start += step) {
709 // Split an **array** into several arrays containing **count** or less elements
711 _.chunk = function(array, count) {
712 if (count == null || count < 1) return [];
715 var i = 0, length = array.length;
717 result.push(slice.call(array, i, i += count));
722 // Function (ahem) Functions
723 // ------------------
725 // Determines whether to execute a function as a constructor
726 // or a normal function with the provided arguments.
727 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
728 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
729 var self = baseCreate(sourceFunc.prototype);
730 var result = sourceFunc.apply(self, args);
731 if (_.isObject(result)) return result;
735 // Create a function bound to a given object (assigning `this`, and arguments,
736 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
738 _.bind = restArgs(function(func, context, args) {
739 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
740 var bound = restArgs(function(callArgs) {
741 return executeBound(func, bound, context, this, args.concat(callArgs));
746 // Partially apply a function by creating a version that has had some of its
747 // arguments pre-filled, without changing its dynamic `this` context. _ acts
748 // as a placeholder by default, allowing any combination of arguments to be
749 // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
750 _.partial = restArgs(function(func, boundArgs) {
751 var placeholder = _.partial.placeholder;
752 var bound = function() {
753 var position = 0, length = boundArgs.length;
754 var args = Array(length);
755 for (var i = 0; i < length; i++) {
756 args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
758 while (position < arguments.length) args.push(arguments[position++]);
759 return executeBound(func, bound, this, this, args);
764 _.partial.placeholder = _;
766 // Bind a number of an object's methods to that object. Remaining arguments
767 // are the method names to be bound. Useful for ensuring that all callbacks
768 // defined on an object belong to it.
769 _.bindAll = restArgs(function(obj, keys) {
770 keys = flatten(keys, false, false);
771 var index = keys.length;
772 if (index < 1) throw new Error('bindAll must be passed function names');
774 var key = keys[index];
775 obj[key] = _.bind(obj[key], obj);
779 // Memoize an expensive function by storing its results.
780 _.memoize = function(func, hasher) {
781 var memoize = function(key) {
782 var cache = memoize.cache;
783 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
784 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
785 return cache[address];
791 // Delays a function for the given number of milliseconds, and then calls
792 // it with the arguments supplied.
793 _.delay = restArgs(function(func, wait, args) {
794 return setTimeout(function() {
795 return func.apply(null, args);
799 // Defers a function, scheduling it to run after the current call stack has
801 _.defer = _.partial(_.delay, _, 1);
803 // Returns a function, that, when invoked, will only be triggered at most once
804 // during a given window of time. Normally, the throttled function will run
805 // as much as it can, without ever going more than once per `wait` duration;
806 // but if you'd like to disable the execution on the leading edge, pass
807 // `{leading: false}`. To disable execution on the trailing edge, ditto.
808 _.throttle = function(func, wait, options) {
809 var timeout, context, args, result;
811 if (!options) options = {};
813 var later = function() {
814 previous = options.leading === false ? 0 : _.now();
816 result = func.apply(context, args);
817 if (!timeout) context = args = null;
820 var throttled = function() {
822 if (!previous && options.leading === false) previous = now;
823 var remaining = wait - (now - previous);
826 if (remaining <= 0 || remaining > wait) {
828 clearTimeout(timeout);
832 result = func.apply(context, args);
833 if (!timeout) context = args = null;
834 } else if (!timeout && options.trailing !== false) {
835 timeout = setTimeout(later, remaining);
840 throttled.cancel = function() {
841 clearTimeout(timeout);
843 timeout = context = args = null;
849 // Returns a function, that, as long as it continues to be invoked, will not
850 // be triggered. The function will be called after it stops being called for
851 // N milliseconds. If `immediate` is passed, trigger the function on the
852 // leading edge, instead of the trailing.
853 _.debounce = function(func, wait, immediate) {
856 var later = function(context, args) {
858 if (args) result = func.apply(context, args);
861 var debounced = restArgs(function(args) {
862 var callNow = immediate && !timeout;
863 if (timeout) clearTimeout(timeout);
865 timeout = setTimeout(later, wait);
866 result = func.apply(this, args);
867 } else if (!immediate) {
868 timeout = _.delay(later, wait, this, args);
874 debounced.cancel = function() {
875 clearTimeout(timeout);
882 // Returns the first function passed as an argument to the second,
883 // allowing you to adjust arguments, run code before and after, and
884 // conditionally execute the original function.
885 _.wrap = function(func, wrapper) {
886 return _.partial(wrapper, func);
889 // Returns a negated version of the passed-in predicate.
890 _.negate = function(predicate) {
892 return !predicate.apply(this, arguments);
896 // Returns a function that is the composition of a list of functions, each
897 // consuming the return value of the function that follows.
898 _.compose = function() {
899 var args = arguments;
900 var start = args.length - 1;
903 var result = args[start].apply(this, arguments);
904 while (i--) result = args[i].call(this, result);
909 // Returns a function that will only be executed on and after the Nth call.
910 _.after = function(times, func) {
913 return func.apply(this, arguments);
918 // Returns a function that will only be executed up to (but not including) the Nth call.
919 _.before = function(times, func) {
923 memo = func.apply(this, arguments);
925 if (times <= 1) func = null;
930 // Returns a function that will be executed at most one time, no matter how
931 // often you call it. Useful for lazy initialization.
932 _.once = _.partial(_.before, 2);
934 _.restArgs = restArgs;
939 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
940 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
941 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
942 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
944 var collectNonEnumProps = function(obj, keys) {
945 var nonEnumIdx = nonEnumerableProps.length;
946 var constructor = obj.constructor;
947 var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;
949 // Constructor is a special case.
950 var prop = 'constructor';
951 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
953 while (nonEnumIdx--) {
954 prop = nonEnumerableProps[nonEnumIdx];
955 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
961 // Retrieve the names of an object's own properties.
962 // Delegates to **ECMAScript 5**'s native `Object.keys`.
963 _.keys = function(obj) {
964 if (!_.isObject(obj)) return [];
965 if (nativeKeys) return nativeKeys(obj);
967 for (var key in obj) if (_.has(obj, key)) keys.push(key);
969 if (hasEnumBug) collectNonEnumProps(obj, keys);
973 // Retrieve all the property names of an object.
974 _.allKeys = function(obj) {
975 if (!_.isObject(obj)) return [];
977 for (var key in obj) keys.push(key);
979 if (hasEnumBug) collectNonEnumProps(obj, keys);
983 // Retrieve the values of an object's properties.
984 _.values = function(obj) {
985 var keys = _.keys(obj);
986 var length = keys.length;
987 var values = Array(length);
988 for (var i = 0; i < length; i++) {
989 values[i] = obj[keys[i]];
994 // Returns the results of applying the iteratee to each element of the object.
995 // In contrast to _.map it returns an object.
996 _.mapObject = function(obj, iteratee, context) {
997 iteratee = cb(iteratee, context);
998 var keys = _.keys(obj),
999 length = keys.length,
1001 for (var index = 0; index < length; index++) {
1002 var currentKey = keys[index];
1003 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
1008 // Convert an object into a list of `[key, value]` pairs.
1009 _.pairs = function(obj) {
1010 var keys = _.keys(obj);
1011 var length = keys.length;
1012 var pairs = Array(length);
1013 for (var i = 0; i < length; i++) {
1014 pairs[i] = [keys[i], obj[keys[i]]];
1019 // Invert the keys and values of an object. The values must be serializable.
1020 _.invert = function(obj) {
1022 var keys = _.keys(obj);
1023 for (var i = 0, length = keys.length; i < length; i++) {
1024 result[obj[keys[i]]] = keys[i];
1029 // Return a sorted list of the function names available on the object.
1030 // Aliased as `methods`.
1031 _.functions = _.methods = function(obj) {
1033 for (var key in obj) {
1034 if (_.isFunction(obj[key])) names.push(key);
1036 return names.sort();
1039 // An internal function for creating assigner functions.
1040 var createAssigner = function(keysFunc, defaults) {
1041 return function(obj) {
1042 var length = arguments.length;
1043 if (defaults) obj = Object(obj);
1044 if (length < 2 || obj == null) return obj;
1045 for (var index = 1; index < length; index++) {
1046 var source = arguments[index],
1047 keys = keysFunc(source),
1049 for (var i = 0; i < l; i++) {
1051 if (!defaults || obj[key] === void 0) obj[key] = source[key];
1058 // Extend a given object with all the properties in passed-in object(s).
1059 _.extend = createAssigner(_.allKeys);
1061 // Assigns a given object with all the own properties in the passed-in object(s).
1062 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
1063 _.extendOwn = _.assign = createAssigner(_.keys);
1065 // Returns the first key on an object that passes a predicate test.
1066 _.findKey = function(obj, predicate, context) {
1067 predicate = cb(predicate, context);
1068 var keys = _.keys(obj), key;
1069 for (var i = 0, length = keys.length; i < length; i++) {
1071 if (predicate(obj[key], key, obj)) return key;
1075 // Internal pick helper function to determine if `obj` has key `key`.
1076 var keyInObj = function(value, key, obj) {
1080 // Return a copy of the object only containing the whitelisted properties.
1081 _.pick = restArgs(function(obj, keys) {
1082 var result = {}, iteratee = keys[0];
1083 if (obj == null) return result;
1084 if (_.isFunction(iteratee)) {
1085 if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
1086 keys = _.allKeys(obj);
1088 iteratee = keyInObj;
1089 keys = flatten(keys, false, false);
1092 for (var i = 0, length = keys.length; i < length; i++) {
1094 var value = obj[key];
1095 if (iteratee(value, key, obj)) result[key] = value;
1100 // Return a copy of the object without the blacklisted properties.
1101 _.omit = restArgs(function(obj, keys) {
1102 var iteratee = keys[0], context;
1103 if (_.isFunction(iteratee)) {
1104 iteratee = _.negate(iteratee);
1105 if (keys.length > 1) context = keys[1];
1107 keys = _.map(flatten(keys, false, false), String);
1108 iteratee = function(value, key) {
1109 return !_.contains(keys, key);
1112 return _.pick(obj, iteratee, context);
1115 // Fill in a given object with default properties.
1116 _.defaults = createAssigner(_.allKeys, true);
1118 // Creates an object that inherits from the given prototype object.
1119 // If additional properties are provided then they will be added to the
1121 _.create = function(prototype, props) {
1122 var result = baseCreate(prototype);
1123 if (props) _.extendOwn(result, props);
1127 // Create a (shallow-cloned) duplicate of an object.
1128 _.clone = function(obj) {
1129 if (!_.isObject(obj)) return obj;
1130 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
1133 // Invokes interceptor with the obj, and then returns obj.
1134 // The primary purpose of this method is to "tap into" a method chain, in
1135 // order to perform operations on intermediate results within the chain.
1136 _.tap = function(obj, interceptor) {
1141 // Returns whether an object has a given set of `key:value` pairs.
1142 _.isMatch = function(object, attrs) {
1143 var keys = _.keys(attrs), length = keys.length;
1144 if (object == null) return !length;
1145 var obj = Object(object);
1146 for (var i = 0; i < length; i++) {
1148 if (attrs[key] !== obj[key] || !(key in obj)) return false;
1154 // Internal recursive comparison function for `isEqual`.
1156 eq = function(a, b, aStack, bStack) {
1157 // Identical objects are equal. `0 === -0`, but they aren't identical.
1158 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
1159 if (a === b) return a !== 0 || 1 / a === 1 / b;
1160 // A strict comparison is necessary because `null == undefined`.
1161 if (a == null || b == null) return a === b;
1162 // `NaN`s are equivalent, but non-reflexive.
1163 if (a !== a) return b !== b;
1164 // Exhaust primitive checks
1165 var type = typeof a;
1166 if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
1167 return deepEq(a, b, aStack, bStack);
1170 // Internal recursive comparison function for `isEqual`.
1171 deepEq = function(a, b, aStack, bStack) {
1172 // Unwrap any wrapped objects.
1173 if (a instanceof _) a = a._wrapped;
1174 if (b instanceof _) b = b._wrapped;
1175 // Compare `[[Class]]` names.
1176 var className = toString.call(a);
1177 if (className !== toString.call(b)) return false;
1178 switch (className) {
1179 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
1180 case '[object RegExp]':
1181 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
1182 case '[object String]':
1183 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
1184 // equivalent to `new String("5")`.
1185 return '' + a === '' + b;
1186 case '[object Number]':
1187 // `NaN`s are equivalent, but non-reflexive.
1188 // Object(NaN) is equivalent to NaN.
1189 if (+a !== +a) return +b !== +b;
1190 // An `egal` comparison is performed for other numeric values.
1191 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
1192 case '[object Date]':
1193 case '[object Boolean]':
1194 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
1195 // millisecond representations. Note that invalid dates with millisecond representations
1196 // of `NaN` are not equivalent.
1200 var areArrays = className === '[object Array]';
1202 if (typeof a != 'object' || typeof b != 'object') return false;
1204 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
1205 // from different frames are.
1206 var aCtor = a.constructor, bCtor = b.constructor;
1207 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
1208 _.isFunction(bCtor) && bCtor instanceof bCtor)
1209 && ('constructor' in a && 'constructor' in b)) {
1213 // Assume equality for cyclic structures. The algorithm for detecting cyclic
1214 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
1216 // Initializing stack of traversed objects.
1217 // It's done here since we only need them for objects and arrays comparison.
1218 aStack = aStack || [];
1219 bStack = bStack || [];
1220 var length = aStack.length;
1222 // Linear search. Performance is inversely proportional to the number of
1223 // unique nested structures.
1224 if (aStack[length] === a) return bStack[length] === b;
1227 // Add the first object to the stack of traversed objects.
1231 // Recursively compare objects and arrays.
1233 // Compare array lengths to determine if a deep comparison is necessary.
1235 if (length !== b.length) return false;
1236 // Deep compare the contents, ignoring non-numeric properties.
1238 if (!eq(a[length], b[length], aStack, bStack)) return false;
1241 // Deep compare objects.
1242 var keys = _.keys(a), key;
1243 length = keys.length;
1244 // Ensure that both objects contain the same number of properties before comparing deep equality.
1245 if (_.keys(b).length !== length) return false;
1247 // Deep compare each member
1249 if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
1252 // Remove the first object from the stack of traversed objects.
1258 // Perform a deep comparison to check if two objects are equal.
1259 _.isEqual = function(a, b) {
1263 // Is a given array, string, or object empty?
1264 // An "empty" object has no enumerable own-properties.
1265 _.isEmpty = function(obj) {
1266 if (obj == null) return true;
1267 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
1268 return _.keys(obj).length === 0;
1271 // Is a given value a DOM element?
1272 _.isElement = function(obj) {
1273 return !!(obj && obj.nodeType === 1);
1276 // Is a given value an array?
1277 // Delegates to ECMA5's native Array.isArray
1278 _.isArray = nativeIsArray || function(obj) {
1279 return toString.call(obj) === '[object Array]';
1282 // Is a given variable an object?
1283 _.isObject = function(obj) {
1284 var type = typeof obj;
1285 return type === 'function' || type === 'object' && !!obj;
1288 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
1289 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol'], function(name) {
1290 _['is' + name] = function(obj) {
1291 return toString.call(obj) === '[object ' + name + ']';
1295 // Define a fallback version of the method in browsers (ahem, IE < 9), where
1296 // there isn't any inspectable "Arguments" type.
1297 if (!_.isArguments(arguments)) {
1298 _.isArguments = function(obj) {
1299 return _.has(obj, 'callee');
1303 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
1304 // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
1305 var nodelist = root.document && root.document.childNodes;
1306 if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
1307 _.isFunction = function(obj) {
1308 return typeof obj == 'function' || false;
1312 // Is a given object a finite number?
1313 _.isFinite = function(obj) {
1314 return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj));
1317 // Is the given value `NaN`?
1318 _.isNaN = function(obj) {
1319 return _.isNumber(obj) && isNaN(obj);
1322 // Is a given value a boolean?
1323 _.isBoolean = function(obj) {
1324 return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
1327 // Is a given value equal to null?
1328 _.isNull = function(obj) {
1329 return obj === null;
1332 // Is a given variable undefined?
1333 _.isUndefined = function(obj) {
1334 return obj === void 0;
1337 // Shortcut function for checking if an object has a given property directly
1338 // on itself (in other words, not on a prototype).
1339 _.has = function(obj, key) {
1340 return obj != null && hasOwnProperty.call(obj, key);
1343 // Utility Functions
1344 // -----------------
1346 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
1347 // previous owner. Returns a reference to the Underscore object.
1348 _.noConflict = function() {
1349 root._ = previousUnderscore;
1353 // Keep the identity function around for default iteratees.
1354 _.identity = function(value) {
1358 // Predicate-generating functions. Often useful outside of Underscore.
1359 _.constant = function(value) {
1365 _.noop = function(){};
1367 _.property = property;
1369 // Generates a function for a given object that returns a given property.
1370 _.propertyOf = function(obj) {
1371 return obj == null ? function(){} : function(key) {
1376 // Returns a predicate for checking whether an object has a given set of
1377 // `key:value` pairs.
1378 _.matcher = _.matches = function(attrs) {
1379 attrs = _.extendOwn({}, attrs);
1380 return function(obj) {
1381 return _.isMatch(obj, attrs);
1385 // Run a function **n** times.
1386 _.times = function(n, iteratee, context) {
1387 var accum = Array(Math.max(0, n));
1388 iteratee = optimizeCb(iteratee, context, 1);
1389 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
1393 // Return a random integer between min and max (inclusive).
1394 _.random = function(min, max) {
1399 return min + Math.floor(Math.random() * (max - min + 1));
1402 // A (possibly faster) way to get the current timestamp as an integer.
1403 _.now = Date.now || function() {
1404 return new Date().getTime();
1407 // List of HTML entities for escaping.
1416 var unescapeMap = _.invert(escapeMap);
1418 // Functions for escaping and unescaping strings to/from HTML interpolation.
1419 var createEscaper = function(map) {
1420 var escaper = function(match) {
1423 // Regexes for identifying a key that needs to be escaped.
1424 var source = '(?:' + _.keys(map).join('|') + ')';
1425 var testRegexp = RegExp(source);
1426 var replaceRegexp = RegExp(source, 'g');
1427 return function(string) {
1428 string = string == null ? '' : '' + string;
1429 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
1432 _.escape = createEscaper(escapeMap);
1433 _.unescape = createEscaper(unescapeMap);
1435 // If the value of the named `property` is a function then invoke it with the
1436 // `object` as context; otherwise, return it.
1437 _.result = function(object, prop, fallback) {
1438 var value = object == null ? void 0 : object[prop];
1439 if (value === void 0) {
1442 return _.isFunction(value) ? value.call(object) : value;
1445 // Generate a unique integer id (unique within the entire client session).
1446 // Useful for temporary DOM ids.
1448 _.uniqueId = function(prefix) {
1449 var id = ++idCounter + '';
1450 return prefix ? prefix + id : id;
1453 // By default, Underscore uses ERB-style template delimiters, change the
1454 // following template settings to use alternative delimiters.
1455 _.templateSettings = {
1456 evaluate: /<%([\s\S]+?)%>/g,
1457 interpolate: /<%=([\s\S]+?)%>/g,
1458 escape: /<%-([\s\S]+?)%>/g
1461 // When customizing `templateSettings`, if you don't want to define an
1462 // interpolation, evaluation or escaping regex, we need one that is
1463 // guaranteed not to match.
1464 var noMatch = /(.)^/;
1466 // Certain characters need to be escaped so that they can be put into a
1477 var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
1479 var escapeChar = function(match) {
1480 return '\\' + escapes[match];
1483 // JavaScript micro-templating, similar to John Resig's implementation.
1484 // Underscore templating handles arbitrary delimiters, preserves whitespace,
1485 // and correctly escapes quotes within interpolated code.
1486 // NB: `oldSettings` only exists for backwards compatibility.
1487 _.template = function(text, settings, oldSettings) {
1488 if (!settings && oldSettings) settings = oldSettings;
1489 settings = _.defaults({}, settings, _.templateSettings);
1491 // Combine delimiters into one regular expression via alternation.
1492 var matcher = RegExp([
1493 (settings.escape || noMatch).source,
1494 (settings.interpolate || noMatch).source,
1495 (settings.evaluate || noMatch).source
1496 ].join('|') + '|$', 'g');
1498 // Compile the template source, escaping string literals appropriately.
1500 var source = "__p+='";
1501 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
1502 source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
1503 index = offset + match.length;
1506 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
1507 } else if (interpolate) {
1508 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
1509 } else if (evaluate) {
1510 source += "';\n" + evaluate + "\n__p+='";
1513 // Adobe VMs need the match returned to produce the correct offset.
1518 // If a variable is not specified, place data values in local scope.
1519 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
1521 source = "var __t,__p='',__j=Array.prototype.join," +
1522 "print=function(){__p+=__j.call(arguments,'');};\n" +
1523 source + 'return __p;\n';
1527 render = new Function(settings.variable || 'obj', '_', source);
1533 var template = function(data) {
1534 return render.call(this, data, _);
1537 // Provide the compiled source as a convenience for precompilation.
1538 var argument = settings.variable || 'obj';
1539 template.source = 'function(' + argument + '){\n' + source + '}';
1544 // Add a "chain" function. Start chaining a wrapped Underscore object.
1545 _.chain = function(obj) {
1546 var instance = _(obj);
1547 instance._chain = true;
1553 // If Underscore is called as a function, it returns a wrapped object that
1554 // can be used OO-style. This wrapper holds altered versions of all the
1555 // underscore functions. Wrapped objects may be chained.
1557 // Helper function to continue chaining intermediate results.
1558 var chainResult = function(instance, obj) {
1559 return instance._chain ? _(obj).chain() : obj;
1562 // Add your own custom functions to the Underscore object.
1563 _.mixin = function(obj) {
1564 _.each(_.functions(obj), function(name) {
1565 var func = _[name] = obj[name];
1566 _.prototype[name] = function() {
1567 var args = [this._wrapped];
1568 push.apply(args, arguments);
1569 return chainResult(this, func.apply(_, args));
1574 // Add all of the Underscore functions to the wrapper object.
1577 // Add all mutator Array functions to the wrapper.
1578 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
1579 var method = ArrayProto[name];
1580 _.prototype[name] = function() {
1581 var obj = this._wrapped;
1582 method.apply(obj, arguments);
1583 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
1584 return chainResult(this, obj);
1588 // Add all accessor Array functions to the wrapper.
1589 _.each(['concat', 'join', 'slice'], function(name) {
1590 var method = ArrayProto[name];
1591 _.prototype[name] = function() {
1592 return chainResult(this, method.apply(this._wrapped, arguments));
1596 // Extracts the result from a wrapped and chained object.
1597 _.prototype.value = function() {
1598 return this._wrapped;
1601 // Provide unwrapping proxy for some methods used in engine operations
1602 // such as arithmetic and JSON stringification.
1603 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
1605 _.prototype.toString = function() {
1606 return '' + this._wrapped;
1609 // AMD registration happens at the end for compatibility with AMD loaders
1610 // that may not enforce next-turn semantics on modules. Even though general
1611 // practice for AMD registration is to be anonymous, underscore registers
1612 // as a named module because, like jQuery, it is a base library that is
1613 // popular enough to be bundled in a third party lib, but not be part of
1614 // an AMD load request. Those cases could generate an error when an
1615 // anonymous define() is called outside of a loader request.
1616 if (typeof define == 'function' && define.amd) {
1617 define('underscore', [], function() {