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;
23 var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
25 // Create quick reference variables for speed access to core prototypes.
26 var push = ArrayProto.push,
27 slice = ArrayProto.slice,
28 toString = ObjProto.toString,
29 hasOwnProperty = ObjProto.hasOwnProperty;
31 // All **ECMAScript 5** native function implementations that we hope to use
33 var nativeIsArray = Array.isArray,
34 nativeKeys = Object.keys,
35 nativeCreate = Object.create;
37 // Naked function reference for surrogate-prototype-swapping.
38 var Ctor = function(){};
40 // Create a safe reference to the Underscore object for use below.
41 var _ = function(obj) {
42 if (obj instanceof _) return obj;
43 if (!(this instanceof _)) return new _(obj);
47 // Export the Underscore object for **Node.js**, with
48 // backwards-compatibility for their old module API. If we're in
49 // the browser, add `_` as a global object.
50 // (`nodeType` is checked to ensure that `module`
51 // and `exports` are not HTML elements.)
52 if (typeof exports != 'undefined' && !exports.nodeType) {
53 if (typeof module != 'undefined' && !module.nodeType && module.exports) {
54 exports = module.exports = _;
64 // Internal function that returns an efficient (for current engines) version
65 // of the passed-in callback, to be repeatedly applied in other Underscore
67 var optimizeCb = function(func, context, argCount) {
68 if (context === void 0) return func;
69 switch (argCount == null ? 3 : argCount) {
70 case 1: return function(value) {
71 return func.call(context, value);
73 // The 2-parameter case has been omitted only because no current consumers
75 case 3: return function(value, index, collection) {
76 return func.call(context, value, index, collection);
78 case 4: return function(accumulator, value, index, collection) {
79 return func.call(context, accumulator, value, index, collection);
83 return func.apply(context, arguments);
87 // An internal function to generate callbacks that can be applied to each
88 // element in a collection, returning the desired result — either `identity`,
89 // an arbitrary callback, a property matcher, or a property accessor.
90 var cb = function(value, context, argCount) {
91 if (value == null) return _.identity;
92 if (_.isFunction(value)) return optimizeCb(value, context, argCount);
93 if (_.isObject(value)) return _.matcher(value);
94 return _.property(value);
97 // An external wrapper for the internal callback generator.
98 _.iteratee = function(value, context) {
99 return cb(value, context, Infinity);
102 // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
103 // This accumulates the arguments passed into an array, after a given index.
104 var restArgs = function(func, startIndex) {
105 startIndex = startIndex == null ? func.length - 1 : +startIndex;
107 var length = Math.max(arguments.length - startIndex, 0);
108 var rest = Array(length);
109 for (var index = 0; index < length; index++) {
110 rest[index] = arguments[index + startIndex];
112 switch (startIndex) {
113 case 0: return func.call(this, rest);
114 case 1: return func.call(this, arguments[0], rest);
115 case 2: return func.call(this, arguments[0], arguments[1], rest);
117 var args = Array(startIndex + 1);
118 for (index = 0; index < startIndex; index++) {
119 args[index] = arguments[index];
121 args[startIndex] = rest;
122 return func.apply(this, args);
126 // An internal function for creating a new object that inherits from another.
127 var baseCreate = function(prototype) {
128 if (!_.isObject(prototype)) return {};
129 if (nativeCreate) return nativeCreate(prototype);
130 Ctor.prototype = prototype;
131 var result = new Ctor;
132 Ctor.prototype = null;
136 var property = function(key) {
137 return function(obj) {
138 return obj == null ? void 0 : obj[key];
142 // Helper for collection methods to determine whether a collection
143 // should be iterated as an array or as an object.
144 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
145 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
146 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
147 var getLength = property('length');
148 var isArrayLike = function(collection) {
149 var length = getLength(collection);
150 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
153 // Collection Functions
154 // --------------------
156 // The cornerstone, an `each` implementation, aka `forEach`.
157 // Handles raw objects in addition to array-likes. Treats all
158 // sparse array-likes as if they were dense.
159 _.each = _.forEach = function(obj, iteratee, context) {
160 iteratee = optimizeCb(iteratee, context);
162 if (isArrayLike(obj)) {
163 for (i = 0, length = obj.length; i < length; i++) {
164 iteratee(obj[i], i, obj);
167 var keys = _.keys(obj);
168 for (i = 0, length = keys.length; i < length; i++) {
169 iteratee(obj[keys[i]], keys[i], obj);
175 // Return the results of applying the iteratee to each element.
176 _.map = _.collect = function(obj, iteratee, context) {
177 iteratee = cb(iteratee, context);
178 var keys = !isArrayLike(obj) && _.keys(obj),
179 length = (keys || obj).length,
180 results = Array(length);
181 for (var index = 0; index < length; index++) {
182 var currentKey = keys ? keys[index] : index;
183 results[index] = iteratee(obj[currentKey], currentKey, obj);
188 // Create a reducing function iterating left or right.
189 var createReduce = function(dir) {
190 // Wrap code that reassigns argument variables in a separate function than
191 // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
192 var reducer = function(obj, iteratee, memo, initial) {
193 var keys = !isArrayLike(obj) && _.keys(obj),
194 length = (keys || obj).length,
195 index = dir > 0 ? 0 : length - 1;
197 memo = obj[keys ? keys[index] : index];
200 for (; index >= 0 && index < length; index += dir) {
201 var currentKey = keys ? keys[index] : index;
202 memo = iteratee(memo, obj[currentKey], currentKey, obj);
207 return function(obj, iteratee, memo, context) {
208 var initial = arguments.length >= 3;
209 return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
213 // **Reduce** builds up a single result from a list of values, aka `inject`,
215 _.reduce = _.foldl = _.inject = createReduce(1);
217 // The right-associative version of reduce, also known as `foldr`.
218 _.reduceRight = _.foldr = createReduce(-1);
220 // Return the first value which passes a truth test. Aliased as `detect`.
221 _.find = _.detect = function(obj, predicate, context) {
222 var keyFinder = isArrayLike(obj) ? _.findIndex : _.findKey;
223 var key = keyFinder(obj, predicate, context);
224 if (key !== void 0 && key !== -1) return obj[key];
227 // Return all the elements that pass a truth test.
228 // Aliased as `select`.
229 _.filter = _.select = function(obj, predicate, context) {
231 predicate = cb(predicate, context);
232 _.each(obj, function(value, index, list) {
233 if (predicate(value, index, list)) results.push(value);
238 // Return all the elements for which a truth test fails.
239 _.reject = function(obj, predicate, context) {
240 return _.filter(obj, _.negate(cb(predicate)), context);
243 // Determine whether all of the elements match a truth test.
245 _.every = _.all = function(obj, predicate, context) {
246 predicate = cb(predicate, context);
247 var keys = !isArrayLike(obj) && _.keys(obj),
248 length = (keys || obj).length;
249 for (var index = 0; index < length; index++) {
250 var currentKey = keys ? keys[index] : index;
251 if (!predicate(obj[currentKey], currentKey, obj)) return false;
256 // Determine if at least one element in the object matches a truth test.
258 _.some = _.any = function(obj, predicate, context) {
259 predicate = cb(predicate, context);
260 var keys = !isArrayLike(obj) && _.keys(obj),
261 length = (keys || obj).length;
262 for (var index = 0; index < length; index++) {
263 var currentKey = keys ? keys[index] : index;
264 if (predicate(obj[currentKey], currentKey, obj)) return true;
269 // Determine if the array or object contains a given item (using `===`).
270 // Aliased as `includes` and `include`.
271 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
272 if (!isArrayLike(obj)) obj = _.values(obj);
273 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
274 return _.indexOf(obj, item, fromIndex) >= 0;
277 // Invoke a method (with arguments) on every item in a collection.
278 _.invoke = restArgs(function(obj, method, args) {
279 var isFunc = _.isFunction(method);
280 return _.map(obj, function(value) {
281 var func = isFunc ? method : value[method];
282 return func == null ? func : func.apply(value, args);
286 // Convenience version of a common use case of `map`: fetching a property.
287 _.pluck = function(obj, key) {
288 return _.map(obj, _.property(key));
291 // Convenience version of a common use case of `filter`: selecting only objects
292 // containing specific `key:value` pairs.
293 _.where = function(obj, attrs) {
294 return _.filter(obj, _.matcher(attrs));
297 // Convenience version of a common use case of `find`: getting the first object
298 // containing specific `key:value` pairs.
299 _.findWhere = function(obj, attrs) {
300 return _.find(obj, _.matcher(attrs));
303 // Return the maximum element (or element-based computation).
304 _.max = function(obj, iteratee, context) {
305 var result = -Infinity, lastComputed = -Infinity,
307 if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
308 obj = isArrayLike(obj) ? obj : _.values(obj);
309 for (var i = 0, length = obj.length; i < length; i++) {
311 if (value != null && value > result) {
316 iteratee = cb(iteratee, context);
317 _.each(obj, function(v, index, list) {
318 computed = iteratee(v, index, list);
319 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
321 lastComputed = computed;
328 // Return the minimum element (or element-based computation).
329 _.min = function(obj, iteratee, context) {
330 var result = Infinity, lastComputed = Infinity,
332 if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
333 obj = isArrayLike(obj) ? obj : _.values(obj);
334 for (var i = 0, length = obj.length; i < length; i++) {
336 if (value != null && value < result) {
341 iteratee = cb(iteratee, context);
342 _.each(obj, function(v, index, list) {
343 computed = iteratee(v, index, list);
344 if (computed < lastComputed || computed === Infinity && result === Infinity) {
346 lastComputed = computed;
353 // Shuffle a collection.
354 _.shuffle = function(obj) {
355 return _.sample(obj, Infinity);
358 // Sample **n** random values from a collection using the modern version of the
359 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
360 // If **n** is not specified, returns a single random element.
361 // The internal `guard` argument allows it to work with `map`.
362 _.sample = function(obj, n, guard) {
363 if (n == null || guard) {
364 if (!isArrayLike(obj)) obj = _.values(obj);
365 return obj[_.random(obj.length - 1)];
367 var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj);
368 var length = getLength(sample);
369 n = Math.max(Math.min(n, length), 0);
370 var last = length - 1;
371 for (var index = 0; index < n; index++) {
372 var rand = _.random(index, last);
373 var temp = sample[index];
374 sample[index] = sample[rand];
377 return sample.slice(0, n);
380 // Sort the object's values by a criterion produced by an iteratee.
381 _.sortBy = function(obj, iteratee, context) {
383 iteratee = cb(iteratee, context);
384 return _.pluck(_.map(obj, function(value, key, list) {
388 criteria: iteratee(value, key, list)
390 }).sort(function(left, right) {
391 var a = left.criteria;
392 var b = right.criteria;
394 if (a > b || a === void 0) return 1;
395 if (a < b || b === void 0) return -1;
397 return left.index - right.index;
401 // An internal function used for aggregate "group by" operations.
402 var group = function(behavior, partition) {
403 return function(obj, iteratee, context) {
404 var result = partition ? [[], []] : {};
405 iteratee = cb(iteratee, context);
406 _.each(obj, function(value, index) {
407 var key = iteratee(value, index, obj);
408 behavior(result, value, key);
414 // Groups the object's values by a criterion. Pass either a string attribute
415 // to group by, or a function that returns the criterion.
416 _.groupBy = group(function(result, value, key) {
417 if (_.has(result, key)) result[key].push(value); else result[key] = [value];
420 // Indexes the object's values by a criterion, similar to `groupBy`, but for
421 // when you know that your index values will be unique.
422 _.indexBy = group(function(result, value, key) {
426 // Counts instances of an object that group by a certain criterion. Pass
427 // either a string attribute to count by, or a function that returns the
429 _.countBy = group(function(result, value, key) {
430 if (_.has(result, key)) result[key]++; else result[key] = 1;
433 var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
434 // Safely create a real, live array from anything iterable.
435 _.toArray = function(obj) {
437 if (_.isArray(obj)) return slice.call(obj);
438 if (_.isString(obj)) {
439 // Keep surrogate pair characters together
440 return obj.match(reStrSymbol);
442 if (isArrayLike(obj)) return _.map(obj);
443 return _.values(obj);
446 // Return the number of elements in an object.
447 _.size = function(obj) {
448 if (obj == null) return 0;
449 return isArrayLike(obj) ? obj.length : _.keys(obj).length;
452 // Split a collection into two arrays: one whose elements all satisfy the given
453 // predicate, and one whose elements all do not satisfy the predicate.
454 _.partition = group(function(result, value, pass) {
455 result[pass ? 0 : 1].push(value);
461 // Get the first element of an array. Passing **n** will return the first N
462 // values in the array. Aliased as `head` and `take`. The **guard** check
463 // allows it to work with `_.map`.
464 _.first = _.head = _.take = function(array, n, guard) {
465 if (array == null) return void 0;
466 if (n == null || guard) return array[0];
467 return _.initial(array, array.length - n);
470 // Returns everything but the last entry of the array. Especially useful on
471 // the arguments object. Passing **n** will return all the values in
472 // the array, excluding the last N.
473 _.initial = function(array, n, guard) {
474 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
477 // Get the last element of an array. Passing **n** will return the last N
478 // values in the array.
479 _.last = function(array, n, guard) {
480 if (array == null) return void 0;
481 if (n == null || guard) return array[array.length - 1];
482 return _.rest(array, Math.max(0, array.length - n));
485 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
486 // Especially useful on the arguments object. Passing an **n** will return
487 // the rest N values in the array.
488 _.rest = _.tail = _.drop = function(array, n, guard) {
489 return slice.call(array, n == null || guard ? 1 : n);
492 // Trim out all falsy values from an array.
493 _.compact = function(array) {
494 return _.filter(array);
497 // Internal implementation of a recursive `flatten` function.
498 var flatten = function(input, shallow, strict, output) {
499 output = output || [];
500 var idx = output.length;
501 for (var i = 0, length = getLength(input); i < length; i++) {
502 var value = input[i];
503 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
504 // Flatten current level of array or arguments object.
506 var j = 0, len = value.length;
507 while (j < len) output[idx++] = value[j++];
509 flatten(value, shallow, strict, output);
512 } else if (!strict) {
513 output[idx++] = value;
519 // Flatten out an array, either recursively (by default), or just one level.
520 _.flatten = function(array, shallow) {
521 return flatten(array, shallow, false);
524 // Return a version of the array that does not contain the specified value(s).
525 _.without = restArgs(function(array, otherArrays) {
526 return _.difference(array, otherArrays);
529 // Produce a duplicate-free version of the array. If the array has already
530 // been sorted, you have the option of using a faster algorithm.
531 // Aliased as `unique`.
532 _.uniq = _.unique = function(array, isSorted, iteratee, context) {
533 if (!_.isBoolean(isSorted)) {
538 if (iteratee != null) iteratee = cb(iteratee, context);
541 for (var i = 0, length = getLength(array); i < length; i++) {
542 var value = array[i],
543 computed = iteratee ? iteratee(value, i, array) : value;
545 if (!i || seen !== computed) result.push(value);
547 } else if (iteratee) {
548 if (!_.contains(seen, computed)) {
552 } else if (!_.contains(result, value)) {
559 // Produce an array that contains the union: each distinct element from all of
560 // the passed-in arrays.
561 _.union = restArgs(function(arrays) {
562 return _.uniq(flatten(arrays, true, true));
565 // Produce an array that contains every item shared between all the
567 _.intersection = function(array) {
569 var argsLength = arguments.length;
570 for (var i = 0, length = getLength(array); i < length; i++) {
572 if (_.contains(result, item)) continue;
574 for (j = 1; j < argsLength; j++) {
575 if (!_.contains(arguments[j], item)) break;
577 if (j === argsLength) result.push(item);
582 // Take the difference between one array and a number of other arrays.
583 // Only the elements present in just the first array will remain.
584 _.difference = restArgs(function(array, rest) {
585 rest = flatten(rest, true, true);
586 return _.filter(array, function(value){
587 return !_.contains(rest, value);
591 // Complement of _.zip. Unzip accepts an array of arrays and groups
592 // each array's elements on shared indices.
593 _.unzip = function(array) {
594 var length = array && _.max(array, getLength).length || 0;
595 var result = Array(length);
597 for (var index = 0; index < length; index++) {
598 result[index] = _.pluck(array, index);
603 // Zip together multiple lists into a single array -- elements that share
604 // an index go together.
605 _.zip = restArgs(_.unzip);
607 // Converts lists into objects. Pass either a single array of `[key, value]`
608 // pairs, or two parallel arrays of the same length -- one of keys, and one of
609 // the corresponding values.
610 _.object = function(list, values) {
612 for (var i = 0, length = getLength(list); i < length; i++) {
614 result[list[i]] = values[i];
616 result[list[i][0]] = list[i][1];
622 // Generator function to create the findIndex and findLastIndex functions.
623 var createPredicateIndexFinder = function(dir) {
624 return function(array, predicate, context) {
625 predicate = cb(predicate, context);
626 var length = getLength(array);
627 var index = dir > 0 ? 0 : length - 1;
628 for (; index >= 0 && index < length; index += dir) {
629 if (predicate(array[index], index, array)) return index;
635 // Returns the first index on an array-like that passes a predicate test.
636 _.findIndex = createPredicateIndexFinder(1);
637 _.findLastIndex = createPredicateIndexFinder(-1);
639 // Use a comparator function to figure out the smallest index at which
640 // an object should be inserted so as to maintain order. Uses binary search.
641 _.sortedIndex = function(array, obj, iteratee, context) {
642 iteratee = cb(iteratee, context, 1);
643 var value = iteratee(obj);
644 var low = 0, high = getLength(array);
646 var mid = Math.floor((low + high) / 2);
647 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
652 // Generator function to create the indexOf and lastIndexOf functions.
653 var createIndexFinder = function(dir, predicateFind, sortedIndex) {
654 return function(array, item, idx) {
655 var i = 0, length = getLength(array);
656 if (typeof idx == 'number') {
658 i = idx >= 0 ? idx : Math.max(idx + length, i);
660 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
662 } else if (sortedIndex && idx && length) {
663 idx = sortedIndex(array, item);
664 return array[idx] === item ? idx : -1;
667 idx = predicateFind(slice.call(array, i, length), _.isNaN);
668 return idx >= 0 ? idx + i : -1;
670 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
671 if (array[idx] === item) return idx;
677 // Return the position of the first occurrence of an item in an array,
678 // or -1 if the item is not included in the array.
679 // If the array is large and already in sort order, pass `true`
680 // for **isSorted** to use binary search.
681 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
682 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
684 // Generate an integer Array containing an arithmetic progression. A port of
685 // the native Python `range()` function. See
686 // [the Python documentation](http://docs.python.org/library/functions.html#range).
687 _.range = function(start, stop, step) {
693 step = stop < start ? -1 : 1;
696 var length = Math.max(Math.ceil((stop - start) / step), 0);
697 var range = Array(length);
699 for (var idx = 0; idx < length; idx++, start += step) {
706 // Split an **array** into several arrays containing **count** or less elements
708 _.chunk = function(array, count) {
709 if (count == null || count < 1) return [];
712 var i = 0, length = array.length;
714 result.push(slice.call(array, i, i += count));
719 // Function (ahem) Functions
720 // ------------------
722 // Determines whether to execute a function as a constructor
723 // or a normal function with the provided arguments.
724 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
725 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
726 var self = baseCreate(sourceFunc.prototype);
727 var result = sourceFunc.apply(self, args);
728 if (_.isObject(result)) return result;
732 // Create a function bound to a given object (assigning `this`, and arguments,
733 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
735 _.bind = restArgs(function(func, context, args) {
736 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
737 var bound = restArgs(function(callArgs) {
738 return executeBound(func, bound, context, this, args.concat(callArgs));
743 // Partially apply a function by creating a version that has had some of its
744 // arguments pre-filled, without changing its dynamic `this` context. _ acts
745 // as a placeholder by default, allowing any combination of arguments to be
746 // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
747 _.partial = restArgs(function(func, boundArgs) {
748 var placeholder = _.partial.placeholder;
749 var bound = function() {
750 var position = 0, length = boundArgs.length;
751 var args = Array(length);
752 for (var i = 0; i < length; i++) {
753 args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
755 while (position < arguments.length) args.push(arguments[position++]);
756 return executeBound(func, bound, this, this, args);
761 _.partial.placeholder = _;
763 // Bind a number of an object's methods to that object. Remaining arguments
764 // are the method names to be bound. Useful for ensuring that all callbacks
765 // defined on an object belong to it.
766 _.bindAll = restArgs(function(obj, keys) {
767 keys = flatten(keys, false, false);
768 var index = keys.length;
769 if (index < 1) throw new Error('bindAll must be passed function names');
771 var key = keys[index];
772 obj[key] = _.bind(obj[key], obj);
776 // Memoize an expensive function by storing its results.
777 _.memoize = function(func, hasher) {
778 var memoize = function(key) {
779 var cache = memoize.cache;
780 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
781 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
782 return cache[address];
788 // Delays a function for the given number of milliseconds, and then calls
789 // it with the arguments supplied.
790 _.delay = restArgs(function(func, wait, args) {
791 return setTimeout(function() {
792 return func.apply(null, args);
796 // Defers a function, scheduling it to run after the current call stack has
798 _.defer = _.partial(_.delay, _, 1);
800 // Returns a function, that, when invoked, will only be triggered at most once
801 // during a given window of time. Normally, the throttled function will run
802 // as much as it can, without ever going more than once per `wait` duration;
803 // but if you'd like to disable the execution on the leading edge, pass
804 // `{leading: false}`. To disable execution on the trailing edge, ditto.
805 _.throttle = function(func, wait, options) {
806 var timeout, context, args, result;
808 if (!options) options = {};
810 var later = function() {
811 previous = options.leading === false ? 0 : _.now();
813 result = func.apply(context, args);
814 if (!timeout) context = args = null;
817 var throttled = function() {
819 if (!previous && options.leading === false) previous = now;
820 var remaining = wait - (now - previous);
823 if (remaining <= 0 || remaining > wait) {
825 clearTimeout(timeout);
829 result = func.apply(context, args);
830 if (!timeout) context = args = null;
831 } else if (!timeout && options.trailing !== false) {
832 timeout = setTimeout(later, remaining);
837 throttled.cancel = function() {
838 clearTimeout(timeout);
840 timeout = context = args = null;
846 // Returns a function, that, as long as it continues to be invoked, will not
847 // be triggered. The function will be called after it stops being called for
848 // N milliseconds. If `immediate` is passed, trigger the function on the
849 // leading edge, instead of the trailing.
850 _.debounce = function(func, wait, immediate) {
853 var later = function(context, args) {
855 if (args) result = func.apply(context, args);
858 var debounced = restArgs(function(args) {
859 if (timeout) clearTimeout(timeout);
861 var callNow = !timeout;
862 timeout = setTimeout(later, wait);
863 if (callNow) result = func.apply(this, args);
865 timeout = _.delay(later, wait, this, args);
871 debounced.cancel = function() {
872 clearTimeout(timeout);
879 // Returns the first function passed as an argument to the second,
880 // allowing you to adjust arguments, run code before and after, and
881 // conditionally execute the original function.
882 _.wrap = function(func, wrapper) {
883 return _.partial(wrapper, func);
886 // Returns a negated version of the passed-in predicate.
887 _.negate = function(predicate) {
889 return !predicate.apply(this, arguments);
893 // Returns a function that is the composition of a list of functions, each
894 // consuming the return value of the function that follows.
895 _.compose = function() {
896 var args = arguments;
897 var start = args.length - 1;
900 var result = args[start].apply(this, arguments);
901 while (i--) result = args[i].call(this, result);
906 // Returns a function that will only be executed on and after the Nth call.
907 _.after = function(times, func) {
910 return func.apply(this, arguments);
915 // Returns a function that will only be executed up to (but not including) the Nth call.
916 _.before = function(times, func) {
920 memo = func.apply(this, arguments);
922 if (times <= 1) func = null;
927 // Returns a function that will be executed at most one time, no matter how
928 // often you call it. Useful for lazy initialization.
929 _.once = _.partial(_.before, 2);
931 _.restArgs = restArgs;
936 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
937 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
938 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
939 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
941 var collectNonEnumProps = function(obj, keys) {
942 var nonEnumIdx = nonEnumerableProps.length;
943 var constructor = obj.constructor;
944 var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;
946 // Constructor is a special case.
947 var prop = 'constructor';
948 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
950 while (nonEnumIdx--) {
951 prop = nonEnumerableProps[nonEnumIdx];
952 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
958 // Retrieve the names of an object's own properties.
959 // Delegates to **ECMAScript 5**'s native `Object.keys`.
960 _.keys = function(obj) {
961 if (!_.isObject(obj)) return [];
962 if (nativeKeys) return nativeKeys(obj);
964 for (var key in obj) if (_.has(obj, key)) keys.push(key);
966 if (hasEnumBug) collectNonEnumProps(obj, keys);
970 // Retrieve all the property names of an object.
971 _.allKeys = function(obj) {
972 if (!_.isObject(obj)) return [];
974 for (var key in obj) keys.push(key);
976 if (hasEnumBug) collectNonEnumProps(obj, keys);
980 // Retrieve the values of an object's properties.
981 _.values = function(obj) {
982 var keys = _.keys(obj);
983 var length = keys.length;
984 var values = Array(length);
985 for (var i = 0; i < length; i++) {
986 values[i] = obj[keys[i]];
991 // Returns the results of applying the iteratee to each element of the object.
992 // In contrast to _.map it returns an object.
993 _.mapObject = function(obj, iteratee, context) {
994 iteratee = cb(iteratee, context);
995 var keys = _.keys(obj),
996 length = keys.length,
998 for (var index = 0; index < length; index++) {
999 var currentKey = keys[index];
1000 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
1005 // Convert an object into a list of `[key, value]` pairs.
1006 _.pairs = function(obj) {
1007 var keys = _.keys(obj);
1008 var length = keys.length;
1009 var pairs = Array(length);
1010 for (var i = 0; i < length; i++) {
1011 pairs[i] = [keys[i], obj[keys[i]]];
1016 // Invert the keys and values of an object. The values must be serializable.
1017 _.invert = function(obj) {
1019 var keys = _.keys(obj);
1020 for (var i = 0, length = keys.length; i < length; i++) {
1021 result[obj[keys[i]]] = keys[i];
1026 // Return a sorted list of the function names available on the object.
1027 // Aliased as `methods`.
1028 _.functions = _.methods = function(obj) {
1030 for (var key in obj) {
1031 if (_.isFunction(obj[key])) names.push(key);
1033 return names.sort();
1036 // An internal function for creating assigner functions.
1037 var createAssigner = function(keysFunc, defaults) {
1038 return function(obj) {
1039 var length = arguments.length;
1040 if (defaults) obj = Object(obj);
1041 if (length < 2 || obj == null) return obj;
1042 for (var index = 1; index < length; index++) {
1043 var source = arguments[index],
1044 keys = keysFunc(source),
1046 for (var i = 0; i < l; i++) {
1048 if (!defaults || obj[key] === void 0) obj[key] = source[key];
1055 // Extend a given object with all the properties in passed-in object(s).
1056 _.extend = createAssigner(_.allKeys);
1058 // Assigns a given object with all the own properties in the passed-in object(s).
1059 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
1060 _.extendOwn = _.assign = createAssigner(_.keys);
1062 // Returns the first key on an object that passes a predicate test.
1063 _.findKey = function(obj, predicate, context) {
1064 predicate = cb(predicate, context);
1065 var keys = _.keys(obj), key;
1066 for (var i = 0, length = keys.length; i < length; i++) {
1068 if (predicate(obj[key], key, obj)) return key;
1072 // Internal pick helper function to determine if `obj` has key `key`.
1073 var keyInObj = function(value, key, obj) {
1077 // Return a copy of the object only containing the whitelisted properties.
1078 _.pick = restArgs(function(obj, keys) {
1079 var result = {}, iteratee = keys[0];
1080 if (obj == null) return result;
1081 if (_.isFunction(iteratee)) {
1082 if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
1083 keys = _.allKeys(obj);
1085 iteratee = keyInObj;
1086 keys = flatten(keys, false, false);
1089 for (var i = 0, length = keys.length; i < length; i++) {
1091 var value = obj[key];
1092 if (iteratee(value, key, obj)) result[key] = value;
1097 // Return a copy of the object without the blacklisted properties.
1098 _.omit = restArgs(function(obj, keys) {
1099 var iteratee = keys[0], context;
1100 if (_.isFunction(iteratee)) {
1101 iteratee = _.negate(iteratee);
1102 if (keys.length > 1) context = keys[1];
1104 keys = _.map(flatten(keys, false, false), String);
1105 iteratee = function(value, key) {
1106 return !_.contains(keys, key);
1109 return _.pick(obj, iteratee, context);
1112 // Fill in a given object with default properties.
1113 _.defaults = createAssigner(_.allKeys, true);
1115 // Creates an object that inherits from the given prototype object.
1116 // If additional properties are provided then they will be added to the
1118 _.create = function(prototype, props) {
1119 var result = baseCreate(prototype);
1120 if (props) _.extendOwn(result, props);
1124 // Create a (shallow-cloned) duplicate of an object.
1125 _.clone = function(obj) {
1126 if (!_.isObject(obj)) return obj;
1127 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
1130 // Invokes interceptor with the obj, and then returns obj.
1131 // The primary purpose of this method is to "tap into" a method chain, in
1132 // order to perform operations on intermediate results within the chain.
1133 _.tap = function(obj, interceptor) {
1138 // Returns whether an object has a given set of `key:value` pairs.
1139 _.isMatch = function(object, attrs) {
1140 var keys = _.keys(attrs), length = keys.length;
1141 if (object == null) return !length;
1142 var obj = Object(object);
1143 for (var i = 0; i < length; i++) {
1145 if (attrs[key] !== obj[key] || !(key in obj)) return false;
1151 // Internal recursive comparison function for `isEqual`.
1153 eq = function(a, b, aStack, bStack) {
1154 // Identical objects are equal. `0 === -0`, but they aren't identical.
1155 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
1156 if (a === b) return a !== 0 || 1 / a === 1 / b;
1157 // A strict comparison is necessary because `null == undefined`.
1158 if (a == null || b == null) return a === b;
1159 // `NaN`s are equivalent, but non-reflexive.
1160 if (a !== a) return b !== b;
1161 // Exhaust primitive checks
1162 var type = typeof a;
1163 if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
1164 return deepEq(a, b, aStack, bStack);
1167 // Internal recursive comparison function for `isEqual`.
1168 deepEq = function(a, b, aStack, bStack) {
1169 // Unwrap any wrapped objects.
1170 if (a instanceof _) a = a._wrapped;
1171 if (b instanceof _) b = b._wrapped;
1172 // Compare `[[Class]]` names.
1173 var className = toString.call(a);
1174 if (className !== toString.call(b)) return false;
1175 switch (className) {
1176 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
1177 case '[object RegExp]':
1178 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
1179 case '[object String]':
1180 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
1181 // equivalent to `new String("5")`.
1182 return '' + a === '' + b;
1183 case '[object Number]':
1184 // `NaN`s are equivalent, but non-reflexive.
1185 // Object(NaN) is equivalent to NaN.
1186 if (+a !== +a) return +b !== +b;
1187 // An `egal` comparison is performed for other numeric values.
1188 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
1189 case '[object Date]':
1190 case '[object Boolean]':
1191 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
1192 // millisecond representations. Note that invalid dates with millisecond representations
1193 // of `NaN` are not equivalent.
1195 case '[object Symbol]':
1196 return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
1199 var areArrays = className === '[object Array]';
1201 if (typeof a != 'object' || typeof b != 'object') return false;
1203 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
1204 // from different frames are.
1205 var aCtor = a.constructor, bCtor = b.constructor;
1206 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
1207 _.isFunction(bCtor) && bCtor instanceof bCtor)
1208 && ('constructor' in a && 'constructor' in b)) {
1212 // Assume equality for cyclic structures. The algorithm for detecting cyclic
1213 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
1215 // Initializing stack of traversed objects.
1216 // It's done here since we only need them for objects and arrays comparison.
1217 aStack = aStack || [];
1218 bStack = bStack || [];
1219 var length = aStack.length;
1221 // Linear search. Performance is inversely proportional to the number of
1222 // unique nested structures.
1223 if (aStack[length] === a) return bStack[length] === b;
1226 // Add the first object to the stack of traversed objects.
1230 // Recursively compare objects and arrays.
1232 // Compare array lengths to determine if a deep comparison is necessary.
1234 if (length !== b.length) return false;
1235 // Deep compare the contents, ignoring non-numeric properties.
1237 if (!eq(a[length], b[length], aStack, bStack)) return false;
1240 // Deep compare objects.
1241 var keys = _.keys(a), key;
1242 length = keys.length;
1243 // Ensure that both objects contain the same number of properties before comparing deep equality.
1244 if (_.keys(b).length !== length) return false;
1246 // Deep compare each member
1248 if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
1251 // Remove the first object from the stack of traversed objects.
1257 // Perform a deep comparison to check if two objects are equal.
1258 _.isEqual = function(a, b) {
1262 // Is a given array, string, or object empty?
1263 // An "empty" object has no enumerable own-properties.
1264 _.isEmpty = function(obj) {
1265 if (obj == null) return true;
1266 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
1267 return _.keys(obj).length === 0;
1270 // Is a given value a DOM element?
1271 _.isElement = function(obj) {
1272 return !!(obj && obj.nodeType === 1);
1275 // Is a given value an array?
1276 // Delegates to ECMA5's native Array.isArray
1277 _.isArray = nativeIsArray || function(obj) {
1278 return toString.call(obj) === '[object Array]';
1281 // Is a given variable an object?
1282 _.isObject = function(obj) {
1283 var type = typeof obj;
1284 return type === 'function' || type === 'object' && !!obj;
1287 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError, isMap, isWeakMap, isSet, isWeakSet.
1288 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol', 'Map', 'WeakMap', 'Set', 'WeakSet'], function(name) {
1289 _['is' + name] = function(obj) {
1290 return toString.call(obj) === '[object ' + name + ']';
1294 // Define a fallback version of the method in browsers (ahem, IE < 9), where
1295 // there isn't any inspectable "Arguments" type.
1296 if (!_.isArguments(arguments)) {
1297 _.isArguments = function(obj) {
1298 return _.has(obj, 'callee');
1302 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
1303 // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
1304 var nodelist = root.document && root.document.childNodes;
1305 if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
1306 _.isFunction = function(obj) {
1307 return typeof obj == 'function' || false;
1311 // Is a given object a finite number?
1312 _.isFinite = function(obj) {
1313 return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj));
1316 // Is the given value `NaN`?
1317 _.isNaN = function(obj) {
1318 return _.isNumber(obj) && isNaN(obj);
1321 // Is a given value a boolean?
1322 _.isBoolean = function(obj) {
1323 return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
1326 // Is a given value equal to null?
1327 _.isNull = function(obj) {
1328 return obj === null;
1331 // Is a given variable undefined?
1332 _.isUndefined = function(obj) {
1333 return obj === void 0;
1336 // Shortcut function for checking if an object has a given property directly
1337 // on itself (in other words, not on a prototype).
1338 _.has = function(obj, key) {
1339 return obj != null && hasOwnProperty.call(obj, key);
1342 // Utility Functions
1343 // -----------------
1345 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
1346 // previous owner. Returns a reference to the Underscore object.
1347 _.noConflict = function() {
1348 root._ = previousUnderscore;
1352 // Keep the identity function around for default iteratees.
1353 _.identity = function(value) {
1357 // Predicate-generating functions. Often useful outside of Underscore.
1358 _.constant = function(value) {
1364 _.noop = function(){};
1366 _.property = property;
1368 // Generates a function for a given object that returns a given property.
1369 _.propertyOf = function(obj) {
1370 return obj == null ? function(){} : function(key) {
1375 // Returns a predicate for checking whether an object has a given set of
1376 // `key:value` pairs.
1377 _.matcher = _.matches = function(attrs) {
1378 attrs = _.extendOwn({}, attrs);
1379 return function(obj) {
1380 return _.isMatch(obj, attrs);
1384 // Run a function **n** times.
1385 _.times = function(n, iteratee, context) {
1386 var accum = Array(Math.max(0, n));
1387 iteratee = optimizeCb(iteratee, context, 1);
1388 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
1392 // Return a random integer between min and max (inclusive).
1393 _.random = function(min, max) {
1398 return min + Math.floor(Math.random() * (max - min + 1));
1401 // A (possibly faster) way to get the current timestamp as an integer.
1402 _.now = Date.now || function() {
1403 return new Date().getTime();
1406 // List of HTML entities for escaping.
1415 var unescapeMap = _.invert(escapeMap);
1417 // Functions for escaping and unescaping strings to/from HTML interpolation.
1418 var createEscaper = function(map) {
1419 var escaper = function(match) {
1422 // Regexes for identifying a key that needs to be escaped.
1423 var source = '(?:' + _.keys(map).join('|') + ')';
1424 var testRegexp = RegExp(source);
1425 var replaceRegexp = RegExp(source, 'g');
1426 return function(string) {
1427 string = string == null ? '' : '' + string;
1428 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
1431 _.escape = createEscaper(escapeMap);
1432 _.unescape = createEscaper(unescapeMap);
1434 // If the value of the named `property` is a function then invoke it with the
1435 // `object` as context; otherwise, return it.
1436 _.result = function(object, prop, fallback) {
1437 var value = object == null ? void 0 : object[prop];
1438 if (value === void 0) {
1441 return _.isFunction(value) ? value.call(object) : value;
1444 // Generate a unique integer id (unique within the entire client session).
1445 // Useful for temporary DOM ids.
1447 _.uniqueId = function(prefix) {
1448 var id = ++idCounter + '';
1449 return prefix ? prefix + id : id;
1452 // By default, Underscore uses ERB-style template delimiters, change the
1453 // following template settings to use alternative delimiters.
1454 _.templateSettings = {
1455 evaluate: /<%([\s\S]+?)%>/g,
1456 interpolate: /<%=([\s\S]+?)%>/g,
1457 escape: /<%-([\s\S]+?)%>/g
1460 // When customizing `templateSettings`, if you don't want to define an
1461 // interpolation, evaluation or escaping regex, we need one that is
1462 // guaranteed not to match.
1463 var noMatch = /(.)^/;
1465 // Certain characters need to be escaped so that they can be put into a
1476 var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
1478 var escapeChar = function(match) {
1479 return '\\' + escapes[match];
1482 // JavaScript micro-templating, similar to John Resig's implementation.
1483 // Underscore templating handles arbitrary delimiters, preserves whitespace,
1484 // and correctly escapes quotes within interpolated code.
1485 // NB: `oldSettings` only exists for backwards compatibility.
1486 _.template = function(text, settings, oldSettings) {
1487 if (!settings && oldSettings) settings = oldSettings;
1488 settings = _.defaults({}, settings, _.templateSettings);
1490 // Combine delimiters into one regular expression via alternation.
1491 var matcher = RegExp([
1492 (settings.escape || noMatch).source,
1493 (settings.interpolate || noMatch).source,
1494 (settings.evaluate || noMatch).source
1495 ].join('|') + '|$', 'g');
1497 // Compile the template source, escaping string literals appropriately.
1499 var source = "__p+='";
1500 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
1501 source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
1502 index = offset + match.length;
1505 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
1506 } else if (interpolate) {
1507 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
1508 } else if (evaluate) {
1509 source += "';\n" + evaluate + "\n__p+='";
1512 // Adobe VMs need the match returned to produce the correct offset.
1517 // If a variable is not specified, place data values in local scope.
1518 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
1520 source = "var __t,__p='',__j=Array.prototype.join," +
1521 "print=function(){__p+=__j.call(arguments,'');};\n" +
1522 source + 'return __p;\n';
1526 render = new Function(settings.variable || 'obj', '_', source);
1532 var template = function(data) {
1533 return render.call(this, data, _);
1536 // Provide the compiled source as a convenience for precompilation.
1537 var argument = settings.variable || 'obj';
1538 template.source = 'function(' + argument + '){\n' + source + '}';
1543 // Add a "chain" function. Start chaining a wrapped Underscore object.
1544 _.chain = function(obj) {
1545 var instance = _(obj);
1546 instance._chain = true;
1552 // If Underscore is called as a function, it returns a wrapped object that
1553 // can be used OO-style. This wrapper holds altered versions of all the
1554 // underscore functions. Wrapped objects may be chained.
1556 // Helper function to continue chaining intermediate results.
1557 var chainResult = function(instance, obj) {
1558 return instance._chain ? _(obj).chain() : obj;
1561 // Add your own custom functions to the Underscore object.
1562 _.mixin = function(obj) {
1563 _.each(_.functions(obj), function(name) {
1564 var func = _[name] = obj[name];
1565 _.prototype[name] = function() {
1566 var args = [this._wrapped];
1567 push.apply(args, arguments);
1568 return chainResult(this, func.apply(_, args));
1573 // Add all of the Underscore functions to the wrapper object.
1576 // Add all mutator Array functions to the wrapper.
1577 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
1578 var method = ArrayProto[name];
1579 _.prototype[name] = function() {
1580 var obj = this._wrapped;
1581 method.apply(obj, arguments);
1582 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
1583 return chainResult(this, obj);
1587 // Add all accessor Array functions to the wrapper.
1588 _.each(['concat', 'join', 'slice'], function(name) {
1589 var method = ArrayProto[name];
1590 _.prototype[name] = function() {
1591 return chainResult(this, method.apply(this._wrapped, arguments));
1595 // Extracts the result from a wrapped and chained object.
1596 _.prototype.value = function() {
1597 return this._wrapped;
1600 // Provide unwrapping proxy for some methods used in engine operations
1601 // such as arithmetic and JSON stringification.
1602 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
1604 _.prototype.toString = function() {
1605 return '' + this._wrapped;
1608 // AMD registration happens at the end for compatibility with AMD loaders
1609 // that may not enforce next-turn semantics on modules. Even though general
1610 // practice for AMD registration is to be anonymous, underscore registers
1611 // as a named module because, like jQuery, it is a base library that is
1612 // popular enough to be bundled in a third party lib, but not be part of
1613 // an AMD load request. Those cases could generate an error when an
1614 // anonymous define() is called outside of a loader request.
1615 if (typeof define == 'function' && define.amd) {
1616 define('underscore', [], function() {