nexus site path corrected
[portal.git] / ecomp-portal-FE / client / bower_components / lodash / vendor / underscore / underscore.js
1 //     Underscore.js 1.8.3
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.
5
6 (function() {
7
8   // Baseline setup
9   // --------------
10
11   // Establish the root object, `window` (`self`) in the browser, `global`
12   // on the server, or `this` in some virtual machines. We use `self`
13   // instead of `window` for `WebWorker` support.
14   var root = typeof self == 'object' && self.self === self && self ||
15             typeof global == 'object' && global.global === global && global ||
16             this;
17
18   // Save the previous value of the `_` variable.
19   var previousUnderscore = root._;
20
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;
24
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;
30
31   // All **ECMAScript 5** native function implementations that we hope to use
32   // are declared here.
33   var nativeIsArray = Array.isArray,
34       nativeKeys = Object.keys,
35       nativeCreate = Object.create;
36
37   // Naked function reference for surrogate-prototype-swapping.
38   var Ctor = function(){};
39
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);
44     this._wrapped = obj;
45   };
46
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 = _;
55     }
56     exports._ = _;
57   } else {
58     root._ = _;
59   }
60
61   // Current version.
62   _.VERSION = '1.8.3';
63
64   // Internal function that returns an efficient (for current engines) version
65   // of the passed-in callback, to be repeatedly applied in other Underscore
66   // functions.
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);
72       };
73       // The 2-parameter case has been omitted only because no current consumers
74       // made use of it.
75       case 3: return function(value, index, collection) {
76         return func.call(context, value, index, collection);
77       };
78       case 4: return function(accumulator, value, index, collection) {
79         return func.call(context, accumulator, value, index, collection);
80       };
81     }
82     return function() {
83       return func.apply(context, arguments);
84     };
85   };
86
87   // 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);
95   };
96
97   // An external wrapper for the internal callback generator.
98   _.iteratee = function(value, context) {
99     return cb(value, context, Infinity);
100   };
101
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;
106     return function() {
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];
111       }
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);
116       }
117       var args = Array(startIndex + 1);
118       for (index = 0; index < startIndex; index++) {
119         args[index] = arguments[index];
120       }
121       args[startIndex] = rest;
122       return func.apply(this, args);
123     };
124   };
125
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;
133     return result;
134   };
135
136   var property = function(key) {
137     return function(obj) {
138       return obj == null ? void 0 : obj[key];
139     };
140   };
141
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;
151   };
152
153   // Collection Functions
154   // --------------------
155
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);
161     var i, length;
162     if (isArrayLike(obj)) {
163       for (i = 0, length = obj.length; i < length; i++) {
164         iteratee(obj[i], i, obj);
165       }
166     } else {
167       var keys = _.keys(obj);
168       for (i = 0, length = keys.length; i < length; i++) {
169         iteratee(obj[keys[i]], keys[i], obj);
170       }
171     }
172     return obj;
173   };
174
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);
184     }
185     return results;
186   };
187
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;
196       if (!initial) {
197         memo = obj[keys ? keys[index] : index];
198         index += dir;
199       }
200       for (; index >= 0 && index < length; index += dir) {
201         var currentKey = keys ? keys[index] : index;
202         memo = iteratee(memo, obj[currentKey], currentKey, obj);
203       }
204       return memo;
205     };
206
207     return function(obj, iteratee, memo, context) {
208       var initial = arguments.length >= 3;
209       return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
210     };
211   };
212
213   // **Reduce** builds up a single result from a list of values, aka `inject`,
214   // or `foldl`.
215   _.reduce = _.foldl = _.inject = createReduce(1);
216
217   // The right-associative version of reduce, also known as `foldr`.
218   _.reduceRight = _.foldr = createReduce(-1);
219
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];
225   };
226
227   // Return all the elements that pass a truth test.
228   // Aliased as `select`.
229   _.filter = _.select = function(obj, predicate, context) {
230     var results = [];
231     predicate = cb(predicate, context);
232     _.each(obj, function(value, index, list) {
233       if (predicate(value, index, list)) results.push(value);
234     });
235     return results;
236   };
237
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);
241   };
242
243   // Determine whether all of the elements match a truth test.
244   // Aliased as `all`.
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;
252     }
253     return true;
254   };
255
256   // Determine if at least one element in the object matches a truth test.
257   // Aliased as `any`.
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;
265     }
266     return false;
267   };
268
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;
275   };
276
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);
283     });
284   });
285
286   // Convenience version of a common use case of `map`: fetching a property.
287   _.pluck = function(obj, key) {
288     return _.map(obj, _.property(key));
289   };
290
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));
295   };
296
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));
301   };
302
303   // Return the maximum element (or element-based computation).
304   _.max = function(obj, iteratee, context) {
305     var result = -Infinity, lastComputed = -Infinity,
306         value, computed;
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++) {
310         value = obj[i];
311         if (value != null && value > result) {
312           result = value;
313         }
314       }
315     } else {
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) {
320           result = v;
321           lastComputed = computed;
322         }
323       });
324     }
325     return result;
326   };
327
328   // Return the minimum element (or element-based computation).
329   _.min = function(obj, iteratee, context) {
330     var result = Infinity, lastComputed = Infinity,
331         value, computed;
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++) {
335         value = obj[i];
336         if (value != null && value < result) {
337           result = value;
338         }
339       }
340     } else {
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) {
345           result = v;
346           lastComputed = computed;
347         }
348       });
349     }
350     return result;
351   };
352
353   // Shuffle a collection.
354   _.shuffle = function(obj) {
355     return _.sample(obj, Infinity);
356   };
357
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)];
366     }
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];
375       sample[rand] = temp;
376     }
377     return sample.slice(0, n);
378   };
379
380   // Sort the object's values by a criterion produced by an iteratee.
381   _.sortBy = function(obj, iteratee, context) {
382     var index = 0;
383     iteratee = cb(iteratee, context);
384     return _.pluck(_.map(obj, function(value, key, list) {
385       return {
386         value: value,
387         index: index++,
388         criteria: iteratee(value, key, list)
389       };
390     }).sort(function(left, right) {
391       var a = left.criteria;
392       var b = right.criteria;
393       if (a !== b) {
394         if (a > b || a === void 0) return 1;
395         if (a < b || b === void 0) return -1;
396       }
397       return left.index - right.index;
398     }), 'value');
399   };
400
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);
409       });
410       return result;
411     };
412   };
413
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];
418   });
419
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) {
423     result[key] = value;
424   });
425
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
428   // criterion.
429   _.countBy = group(function(result, value, key) {
430     if (_.has(result, key)) result[key]++; else result[key] = 1;
431   });
432
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) {
436     if (!obj) return [];
437     if (_.isArray(obj)) return slice.call(obj);
438     if (_.isString(obj)) {
439       // Keep surrogate pair characters together
440       return obj.match(reStrSymbol);
441     }
442     if (isArrayLike(obj)) return _.map(obj);
443     return _.values(obj);
444   };
445
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;
450   };
451
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);
456   }, true);
457
458   // Array Functions
459   // ---------------
460
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);
468   };
469
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)));
475   };
476
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));
483   };
484
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);
490   };
491
492   // Trim out all falsy values from an array.
493   _.compact = function(array) {
494     return _.filter(array);
495   };
496
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.
505         if (shallow) {
506           var j = 0, len = value.length;
507           while (j < len) output[idx++] = value[j++];
508         } else {
509           flatten(value, shallow, strict, output);
510           idx = output.length;
511         }
512       } else if (!strict) {
513         output[idx++] = value;
514       }
515     }
516     return output;
517   };
518
519   // Flatten out an array, either recursively (by default), or just one level.
520   _.flatten = function(array, shallow) {
521     return flatten(array, shallow, false);
522   };
523
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);
527   });
528
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)) {
534       context = iteratee;
535       iteratee = isSorted;
536       isSorted = false;
537     }
538     if (iteratee != null) iteratee = cb(iteratee, context);
539     var result = [];
540     var seen = [];
541     for (var i = 0, length = getLength(array); i < length; i++) {
542       var value = array[i],
543           computed = iteratee ? iteratee(value, i, array) : value;
544       if (isSorted) {
545         if (!i || seen !== computed) result.push(value);
546         seen = computed;
547       } else if (iteratee) {
548         if (!_.contains(seen, computed)) {
549           seen.push(computed);
550           result.push(value);
551         }
552       } else if (!_.contains(result, value)) {
553         result.push(value);
554       }
555     }
556     return result;
557   };
558
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));
563   });
564
565   // Produce an array that contains every item shared between all the
566   // passed-in arrays.
567   _.intersection = function(array) {
568     var result = [];
569     var argsLength = arguments.length;
570     for (var i = 0, length = getLength(array); i < length; i++) {
571       var item = array[i];
572       if (_.contains(result, item)) continue;
573       var j;
574       for (j = 1; j < argsLength; j++) {
575         if (!_.contains(arguments[j], item)) break;
576       }
577       if (j === argsLength) result.push(item);
578     }
579     return result;
580   };
581
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);
588     });
589   });
590
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);
596
597     for (var index = 0; index < length; index++) {
598       result[index] = _.pluck(array, index);
599     }
600     return result;
601   };
602
603   // Zip together multiple lists into a single array -- elements that share
604   // an index go together.
605   _.zip = restArgs(_.unzip);
606
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) {
611     var result = {};
612     for (var i = 0, length = getLength(list); i < length; i++) {
613       if (values) {
614         result[list[i]] = values[i];
615       } else {
616         result[list[i][0]] = list[i][1];
617       }
618     }
619     return result;
620   };
621
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;
630       }
631       return -1;
632     };
633   };
634
635   // Returns the first index on an array-like that passes a predicate test.
636   _.findIndex = createPredicateIndexFinder(1);
637   _.findLastIndex = createPredicateIndexFinder(-1);
638
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);
645     while (low < high) {
646       var mid = Math.floor((low + high) / 2);
647       if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
648     }
649     return low;
650   };
651
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') {
657         if (dir > 0) {
658           i = idx >= 0 ? idx : Math.max(idx + length, i);
659         } else {
660           length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
661         }
662       } else if (sortedIndex && idx && length) {
663         idx = sortedIndex(array, item);
664         return array[idx] === item ? idx : -1;
665       }
666       if (item !== item) {
667         idx = predicateFind(slice.call(array, i, length), _.isNaN);
668         return idx >= 0 ? idx + i : -1;
669       }
670       for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
671         if (array[idx] === item) return idx;
672       }
673       return -1;
674     };
675   };
676
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);
683
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) {
688     if (stop == null) {
689       stop = start || 0;
690       start = 0;
691     }
692     if (!step) {
693       step = stop < start ? -1 : 1;
694     }
695
696     var length = Math.max(Math.ceil((stop - start) / step), 0);
697     var range = Array(length);
698
699     for (var idx = 0; idx < length; idx++, start += step) {
700       range[idx] = start;
701     }
702
703     return range;
704   };
705
706   // Split an **array** into several arrays containing **count** or less elements
707   // of initial array.
708   _.chunk = function(array, count) {
709     if (count == null || count < 1) return [];
710
711     var result = [];
712     var i = 0, length = array.length;
713     while (i < length) {
714       result.push(slice.call(array, i, i += count));
715     }
716     return result;
717   };
718
719   // Function (ahem) Functions
720   // ------------------
721
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;
729     return self;
730   };
731
732   // Create a function bound to a given object (assigning `this`, and arguments,
733   // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
734   // available.
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));
739     });
740     return bound;
741   });
742
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];
754       }
755       while (position < arguments.length) args.push(arguments[position++]);
756       return executeBound(func, bound, this, this, args);
757     };
758     return bound;
759   });
760
761   _.partial.placeholder = _;
762
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');
770     while (index--) {
771       var key = keys[index];
772       obj[key] = _.bind(obj[key], obj);
773     }
774   });
775
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];
783     };
784     memoize.cache = {};
785     return memoize;
786   };
787
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);
793     }, wait);
794   });
795
796   // Defers a function, scheduling it to run after the current call stack has
797   // cleared.
798   _.defer = _.partial(_.delay, _, 1);
799
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;
807     var previous = 0;
808     if (!options) options = {};
809
810     var later = function() {
811       previous = options.leading === false ? 0 : _.now();
812       timeout = null;
813       result = func.apply(context, args);
814       if (!timeout) context = args = null;
815     };
816
817     var throttled = function() {
818       var now = _.now();
819       if (!previous && options.leading === false) previous = now;
820       var remaining = wait - (now - previous);
821       context = this;
822       args = arguments;
823       if (remaining <= 0 || remaining > wait) {
824         if (timeout) {
825           clearTimeout(timeout);
826           timeout = null;
827         }
828         previous = now;
829         result = func.apply(context, args);
830         if (!timeout) context = args = null;
831       } else if (!timeout && options.trailing !== false) {
832         timeout = setTimeout(later, remaining);
833       }
834       return result;
835     };
836
837     throttled.cancel = function() {
838       clearTimeout(timeout);
839       previous = 0;
840       timeout = context = args = null;
841     };
842
843     return throttled;
844   };
845
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) {
851     var timeout, result;
852
853     var later = function(context, args) {
854       timeout = null;
855       if (args) result = func.apply(context, args);
856     };
857
858     var debounced = restArgs(function(args) {
859       if (timeout) clearTimeout(timeout);
860       if (immediate) {
861         var callNow = !timeout;
862         timeout = setTimeout(later, wait);
863         if (callNow) result = func.apply(this, args);
864       } else {
865         timeout = _.delay(later, wait, this, args);
866       }
867
868       return result;
869     });
870
871     debounced.cancel = function() {
872       clearTimeout(timeout);
873       timeout = null;
874     };
875
876     return debounced;
877   };
878
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);
884   };
885
886   // Returns a negated version of the passed-in predicate.
887   _.negate = function(predicate) {
888     return function() {
889       return !predicate.apply(this, arguments);
890     };
891   };
892
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;
898     return function() {
899       var i = start;
900       var result = args[start].apply(this, arguments);
901       while (i--) result = args[i].call(this, result);
902       return result;
903     };
904   };
905
906   // Returns a function that will only be executed on and after the Nth call.
907   _.after = function(times, func) {
908     return function() {
909       if (--times < 1) {
910         return func.apply(this, arguments);
911       }
912     };
913   };
914
915   // Returns a function that will only be executed up to (but not including) the Nth call.
916   _.before = function(times, func) {
917     var memo;
918     return function() {
919       if (--times > 0) {
920         memo = func.apply(this, arguments);
921       }
922       if (times <= 1) func = null;
923       return memo;
924     };
925   };
926
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);
930
931   _.restArgs = restArgs;
932
933   // Object Functions
934   // ----------------
935
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'];
940
941   var collectNonEnumProps = function(obj, keys) {
942     var nonEnumIdx = nonEnumerableProps.length;
943     var constructor = obj.constructor;
944     var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;
945
946     // Constructor is a special case.
947     var prop = 'constructor';
948     if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
949
950     while (nonEnumIdx--) {
951       prop = nonEnumerableProps[nonEnumIdx];
952       if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
953         keys.push(prop);
954       }
955     }
956   };
957
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);
963     var keys = [];
964     for (var key in obj) if (_.has(obj, key)) keys.push(key);
965     // Ahem, IE < 9.
966     if (hasEnumBug) collectNonEnumProps(obj, keys);
967     return keys;
968   };
969
970   // Retrieve all the property names of an object.
971   _.allKeys = function(obj) {
972     if (!_.isObject(obj)) return [];
973     var keys = [];
974     for (var key in obj) keys.push(key);
975     // Ahem, IE < 9.
976     if (hasEnumBug) collectNonEnumProps(obj, keys);
977     return keys;
978   };
979
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]];
987     }
988     return values;
989   };
990
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,
997         results = {};
998     for (var index = 0; index < length; index++) {
999       var currentKey = keys[index];
1000       results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
1001     }
1002     return results;
1003   };
1004
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]]];
1012     }
1013     return pairs;
1014   };
1015
1016   // Invert the keys and values of an object. The values must be serializable.
1017   _.invert = function(obj) {
1018     var result = {};
1019     var keys = _.keys(obj);
1020     for (var i = 0, length = keys.length; i < length; i++) {
1021       result[obj[keys[i]]] = keys[i];
1022     }
1023     return result;
1024   };
1025
1026   // Return a sorted list of the function names available on the object.
1027   // Aliased as `methods`.
1028   _.functions = _.methods = function(obj) {
1029     var names = [];
1030     for (var key in obj) {
1031       if (_.isFunction(obj[key])) names.push(key);
1032     }
1033     return names.sort();
1034   };
1035
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),
1045             l = keys.length;
1046         for (var i = 0; i < l; i++) {
1047           var key = keys[i];
1048           if (!defaults || obj[key] === void 0) obj[key] = source[key];
1049         }
1050       }
1051       return obj;
1052     };
1053   };
1054
1055   // Extend a given object with all the properties in passed-in object(s).
1056   _.extend = createAssigner(_.allKeys);
1057
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);
1061
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++) {
1067       key = keys[i];
1068       if (predicate(obj[key], key, obj)) return key;
1069     }
1070   };
1071
1072   // Internal pick helper function to determine if `obj` has key `key`.
1073   var keyInObj = function(value, key, obj) {
1074     return key in obj;
1075   };
1076
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);
1084     } else {
1085       iteratee = keyInObj;
1086       keys = flatten(keys, false, false);
1087       obj = Object(obj);
1088     }
1089     for (var i = 0, length = keys.length; i < length; i++) {
1090       var key = keys[i];
1091       var value = obj[key];
1092       if (iteratee(value, key, obj)) result[key] = value;
1093     }
1094     return result;
1095   });
1096
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];
1103     } else {
1104       keys = _.map(flatten(keys, false, false), String);
1105       iteratee = function(value, key) {
1106         return !_.contains(keys, key);
1107       };
1108     }
1109     return _.pick(obj, iteratee, context);
1110   });
1111
1112   // Fill in a given object with default properties.
1113   _.defaults = createAssigner(_.allKeys, true);
1114
1115   // Creates an object that inherits from the given prototype object.
1116   // If additional properties are provided then they will be added to the
1117   // created object.
1118   _.create = function(prototype, props) {
1119     var result = baseCreate(prototype);
1120     if (props) _.extendOwn(result, props);
1121     return result;
1122   };
1123
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);
1128   };
1129
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) {
1134     interceptor(obj);
1135     return obj;
1136   };
1137
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++) {
1144       var key = keys[i];
1145       if (attrs[key] !== obj[key] || !(key in obj)) return false;
1146     }
1147     return true;
1148   };
1149
1150
1151   // Internal recursive comparison function for `isEqual`.
1152   var eq, deepEq;
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);
1165   };
1166
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.
1194         return +a === +b;
1195       case '[object Symbol]':
1196         return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
1197     }
1198
1199     var areArrays = className === '[object Array]';
1200     if (!areArrays) {
1201       if (typeof a != 'object' || typeof b != 'object') return false;
1202
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)) {
1209         return false;
1210       }
1211     }
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`.
1214
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;
1220     while (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;
1224     }
1225
1226     // Add the first object to the stack of traversed objects.
1227     aStack.push(a);
1228     bStack.push(b);
1229
1230     // Recursively compare objects and arrays.
1231     if (areArrays) {
1232       // Compare array lengths to determine if a deep comparison is necessary.
1233       length = a.length;
1234       if (length !== b.length) return false;
1235       // Deep compare the contents, ignoring non-numeric properties.
1236       while (length--) {
1237         if (!eq(a[length], b[length], aStack, bStack)) return false;
1238       }
1239     } else {
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;
1245       while (length--) {
1246         // Deep compare each member
1247         key = keys[length];
1248         if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
1249       }
1250     }
1251     // Remove the first object from the stack of traversed objects.
1252     aStack.pop();
1253     bStack.pop();
1254     return true;
1255   };
1256
1257   // Perform a deep comparison to check if two objects are equal.
1258   _.isEqual = function(a, b) {
1259     return eq(a, b);
1260   };
1261
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;
1268   };
1269
1270   // Is a given value a DOM element?
1271   _.isElement = function(obj) {
1272     return !!(obj && obj.nodeType === 1);
1273   };
1274
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]';
1279   };
1280
1281   // Is a given variable an object?
1282   _.isObject = function(obj) {
1283     var type = typeof obj;
1284     return type === 'function' || type === 'object' && !!obj;
1285   };
1286
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 + ']';
1291     };
1292   });
1293
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');
1299     };
1300   }
1301
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;
1308     };
1309   }
1310
1311   // Is a given object a finite number?
1312   _.isFinite = function(obj) {
1313     return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj));
1314   };
1315
1316   // Is the given value `NaN`?
1317   _.isNaN = function(obj) {
1318     return _.isNumber(obj) && isNaN(obj);
1319   };
1320
1321   // Is a given value a boolean?
1322   _.isBoolean = function(obj) {
1323     return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
1324   };
1325
1326   // Is a given value equal to null?
1327   _.isNull = function(obj) {
1328     return obj === null;
1329   };
1330
1331   // Is a given variable undefined?
1332   _.isUndefined = function(obj) {
1333     return obj === void 0;
1334   };
1335
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);
1340   };
1341
1342   // Utility Functions
1343   // -----------------
1344
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;
1349     return this;
1350   };
1351
1352   // Keep the identity function around for default iteratees.
1353   _.identity = function(value) {
1354     return value;
1355   };
1356
1357   // Predicate-generating functions. Often useful outside of Underscore.
1358   _.constant = function(value) {
1359     return function() {
1360       return value;
1361     };
1362   };
1363
1364   _.noop = function(){};
1365
1366   _.property = property;
1367
1368   // Generates a function for a given object that returns a given property.
1369   _.propertyOf = function(obj) {
1370     return obj == null ? function(){} : function(key) {
1371       return obj[key];
1372     };
1373   };
1374
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);
1381     };
1382   };
1383
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);
1389     return accum;
1390   };
1391
1392   // Return a random integer between min and max (inclusive).
1393   _.random = function(min, max) {
1394     if (max == null) {
1395       max = min;
1396       min = 0;
1397     }
1398     return min + Math.floor(Math.random() * (max - min + 1));
1399   };
1400
1401   // A (possibly faster) way to get the current timestamp as an integer.
1402   _.now = Date.now || function() {
1403     return new Date().getTime();
1404   };
1405
1406    // List of HTML entities for escaping.
1407   var escapeMap = {
1408     '&': '&amp;',
1409     '<': '&lt;',
1410     '>': '&gt;',
1411     '"': '&quot;',
1412     "'": '&#x27;',
1413     '`': '&#x60;'
1414   };
1415   var unescapeMap = _.invert(escapeMap);
1416
1417   // Functions for escaping and unescaping strings to/from HTML interpolation.
1418   var createEscaper = function(map) {
1419     var escaper = function(match) {
1420       return map[match];
1421     };
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;
1429     };
1430   };
1431   _.escape = createEscaper(escapeMap);
1432   _.unescape = createEscaper(unescapeMap);
1433
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) {
1439       value = fallback;
1440     }
1441     return _.isFunction(value) ? value.call(object) : value;
1442   };
1443
1444   // Generate a unique integer id (unique within the entire client session).
1445   // Useful for temporary DOM ids.
1446   var idCounter = 0;
1447   _.uniqueId = function(prefix) {
1448     var id = ++idCounter + '';
1449     return prefix ? prefix + id : id;
1450   };
1451
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
1458   };
1459
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 = /(.)^/;
1464
1465   // Certain characters need to be escaped so that they can be put into a
1466   // string literal.
1467   var escapes = {
1468     "'": "'",
1469     '\\': '\\',
1470     '\r': 'r',
1471     '\n': 'n',
1472     '\u2028': 'u2028',
1473     '\u2029': 'u2029'
1474   };
1475
1476   var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
1477
1478   var escapeChar = function(match) {
1479     return '\\' + escapes[match];
1480   };
1481
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);
1489
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');
1496
1497     // Compile the template source, escaping string literals appropriately.
1498     var index = 0;
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;
1503
1504       if (escape) {
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+='";
1510       }
1511
1512       // Adobe VMs need the match returned to produce the correct offset.
1513       return match;
1514     });
1515     source += "';\n";
1516
1517     // If a variable is not specified, place data values in local scope.
1518     if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
1519
1520     source = "var __t,__p='',__j=Array.prototype.join," +
1521       "print=function(){__p+=__j.call(arguments,'');};\n" +
1522       source + 'return __p;\n';
1523
1524     var render;
1525     try {
1526       render = new Function(settings.variable || 'obj', '_', source);
1527     } catch (e) {
1528       e.source = source;
1529       throw e;
1530     }
1531
1532     var template = function(data) {
1533       return render.call(this, data, _);
1534     };
1535
1536     // Provide the compiled source as a convenience for precompilation.
1537     var argument = settings.variable || 'obj';
1538     template.source = 'function(' + argument + '){\n' + source + '}';
1539
1540     return template;
1541   };
1542
1543   // Add a "chain" function. Start chaining a wrapped Underscore object.
1544   _.chain = function(obj) {
1545     var instance = _(obj);
1546     instance._chain = true;
1547     return instance;
1548   };
1549
1550   // OOP
1551   // ---------------
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.
1555
1556   // Helper function to continue chaining intermediate results.
1557   var chainResult = function(instance, obj) {
1558     return instance._chain ? _(obj).chain() : obj;
1559   };
1560
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));
1569       };
1570     });
1571   };
1572
1573   // Add all of the Underscore functions to the wrapper object.
1574   _.mixin(_);
1575
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);
1584     };
1585   });
1586
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));
1592     };
1593   });
1594
1595   // Extracts the result from a wrapped and chained object.
1596   _.prototype.value = function() {
1597     return this._wrapped;
1598   };
1599
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;
1603
1604   _.prototype.toString = function() {
1605     return '' + this._wrapped;
1606   };
1607
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() {
1617       return _;
1618     });
1619   }
1620 }());