Debian Codegraph @

test/vendor/underscore.js

raw
1 // Underscore.js 1.5.2
2 // http://underscorejs.org
3 // (c) 2009-2013 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` in the browser, or `exports` on the server.
12 var root = this;
13
14 // Save the previous value of the `_` variable.
15 var previousUnderscore = root._;
16
17 // Establish the object that gets returned to break out of a loop iteration.
18 var breaker = {};
19
20 // Save bytes in the minified (but not gzipped) version:
21 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
22
23 //use the faster Date.now if available.
24 var getTime = (Date.now || function() {
25 return new Date().getTime();
26 });
27
28 // Create quick reference variables for speed access to core prototypes.
29 var
30 push = ArrayProto.push,
31 slice = ArrayProto.slice,
32 concat = ArrayProto.concat,
33 toString = ObjProto.toString,
34 hasOwnProperty = ObjProto.hasOwnProperty;
35
36 // All **ECMAScript 5** native function implementations that we hope to use
37 // are declared here.
38 var
39 nativeForEach = ArrayProto.forEach,
40 nativeMap = ArrayProto.map,
41 nativeReduce = ArrayProto.reduce,
42 nativeReduceRight = ArrayProto.reduceRight,
43 nativeFilter = ArrayProto.filter,
44 nativeEvery = ArrayProto.every,
45 nativeSome = ArrayProto.some,
46 nativeIndexOf = ArrayProto.indexOf,
47 nativeLastIndexOf = ArrayProto.lastIndexOf,
48 nativeIsArray = Array.isArray,
49 nativeKeys = Object.keys,
50 nativeBind = FuncProto.bind;
51
52 // Create a safe reference to the Underscore object for use below.
53 var _ = function(obj) {
54 if (obj instanceof _) return obj;
55 if (!(this instanceof _)) return new _(obj);
56 this._wrapped = obj;
57 };
58
59 // Export the Underscore object for **Node.js**, with
60 // backwards-compatibility for the old `require()` API. If we're in
61 // the browser, add `_` as a global object via a string identifier,
62 // for Closure Compiler "advanced" mode.
63 if (typeof exports !== 'undefined') {
64 if (typeof module !== 'undefined' && module.exports) {
65 exports = module.exports = _;
66 }
67 exports._ = _;
68 } else {
69 root._ = _;
70 }
71
72 // Current version.
73 _.VERSION = '1.5.2';
74
75 // Collection Functions
76 // --------------------
77
78 // The cornerstone, an `each` implementation, aka `forEach`.
79 // Handles objects with the built-in `forEach`, arrays, and raw objects.
80 // Delegates to **ECMAScript 5**'s native `forEach` if available.
81 var each = _.each = _.forEach = function(obj, iterator, context) {
82 if (obj == null) return;
83 if (nativeForEach && obj.forEach === nativeForEach) {
84 obj.forEach(iterator, context);
85 } else if (obj.length === +obj.length) {
86 for (var i = 0, length = obj.length; i < length; i++) {
87 if (iterator.call(context, obj[i], i, obj) === breaker) return;
88 }
89 } else {
90 var keys = _.keys(obj);
91 for (var i = 0, length = keys.length; i < length; i++) {
92 if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
93 }
94 }
95 };
96
97 // Return the results of applying the iterator to each element.
98 // Delegates to **ECMAScript 5**'s native `map` if available.
99 _.map = _.collect = function(obj, iterator, context) {
100 var results = [];
101 if (obj == null) return results;
102 if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
103 each(obj, function(value, index, list) {
104 results.push(iterator.call(context, value, index, list));
105 });
106 return results;
107 };
108
109 var reduceError = 'Reduce of empty array with no initial value';
110
111 // **Reduce** builds up a single result from a list of values, aka `inject`,
112 // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
113 _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
114 var initial = arguments.length > 2;
115 if (obj == null) obj = [];
116 if (nativeReduce && obj.reduce === nativeReduce) {
117 if (context) iterator = _.bind(iterator, context);
118 return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
119 }
120 each(obj, function(value, index, list) {
121 if (!initial) {
122 memo = value;
123 initial = true;
124 } else {
125 memo = iterator.call(context, memo, value, index, list);
126 }
127 });
128 if (!initial) throw new TypeError(reduceError);
129 return memo;
130 };
131
132 // The right-associative version of reduce, also known as `foldr`.
133 // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
134 _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
135 var initial = arguments.length > 2;
136 if (obj == null) obj = [];
137 if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
138 if (context) iterator = _.bind(iterator, context);
139 return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
140 }
141 var length = obj.length;
142 if (length !== +length) {
143 var keys = _.keys(obj);
144 length = keys.length;
145 }
146 each(obj, function(value, index, list) {
147 index = keys ? keys[--length] : --length;
148 if (!initial) {
149 memo = obj[index];
150 initial = true;
151 } else {
152 memo = iterator.call(context, memo, obj[index], index, list);
153 }
154 });
155 if (!initial) throw new TypeError(reduceError);
156 return memo;
157 };
158
159 // Return the first value which passes a truth test. Aliased as `detect`.
160 _.find = _.detect = function(obj, iterator, context) {
161 var result;
162 any(obj, function(value, index, list) {
163 if (iterator.call(context, value, index, list)) {
164 result = value;
165 return true;
166 }
167 });
168 return result;
169 };
170
171 // Return all the elements that pass a truth test.
172 // Delegates to **ECMAScript 5**'s native `filter` if available.
173 // Aliased as `select`.
174 _.filter = _.select = function(obj, iterator, context) {
175 var results = [];
176 if (obj == null) return results;
177 if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
178 each(obj, function(value, index, list) {
179 if (iterator.call(context, value, index, list)) results.push(value);
180 });
181 return results;
182 };
183
184 // Return all the elements for which a truth test fails.
185 _.reject = function(obj, iterator, context) {
186 return _.filter(obj, function(value, index, list) {
187 return !iterator.call(context, value, index, list);
188 }, context);
189 };
190
191 // Determine whether all of the elements match a truth test.
192 // Delegates to **ECMAScript 5**'s native `every` if available.
193 // Aliased as `all`.
194 _.every = _.all = function(obj, iterator, context) {
195 iterator || (iterator = _.identity);
196 var result = true;
197 if (obj == null) return result;
198 if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
199 each(obj, function(value, index, list) {
200 if (!(result = result && iterator.call(context, value, index, list))) return breaker;
201 });
202 return !!result;
203 };
204
205 // Determine if at least one element in the object matches a truth test.
206 // Delegates to **ECMAScript 5**'s native `some` if available.
207 // Aliased as `any`.
208 var any = _.some = _.any = function(obj, iterator, context) {
209 iterator || (iterator = _.identity);
210 var result = false;
211 if (obj == null) return result;
212 if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
213 each(obj, function(value, index, list) {
214 if (result || (result = iterator.call(context, value, index, list))) return breaker;
215 });
216 return !!result;
217 };
218
219 // Determine if the array or object contains a given value (using `===`).
220 // Aliased as `include`.
221 _.contains = _.include = function(obj, target) {
222 if (obj == null) return false;
223 if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
224 return any(obj, function(value) {
225 return value === target;
226 });
227 };
228
229 // Invoke a method (with arguments) on every item in a collection.
230 _.invoke = function(obj, method) {
231 var args = slice.call(arguments, 2);
232 var isFunc = _.isFunction(method);
233 return _.map(obj, function(value) {
234 return (isFunc ? method : value[method]).apply(value, args);
235 });
236 };
237
238 // Convenience version of a common use case of `map`: fetching a property.
239 _.pluck = function(obj, key) {
240 return _.map(obj, _.property(key));
241 };
242
243 // Convenience version of a common use case of `filter`: selecting only objects
244 // containing specific `key:value` pairs.
245 _.where = function(obj, attrs, first) {
246 if (_.isEmpty(attrs)) return first ? void 0 : [];
247 return _[first ? 'find' : 'filter'](obj, function(value) {
248 for (var key in attrs) {
249 if (attrs[key] !== value[key]) return false;
250 }
251 return true;
252 });
253 };
254
255 // Convenience version of a common use case of `find`: getting the first object
256 // containing specific `key:value` pairs.
257 _.findWhere = function(obj, attrs) {
258 return _.where(obj, attrs, true);
259 };
260
261 // Return the maximum element or (element-based computation).
262 // Can't optimize arrays of integers longer than 65,535 elements.
263 // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
264 _.max = function(obj, iterator, context) {
265 if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
266 return Math.max.apply(Math, obj);
267 }
268 if (!iterator && _.isEmpty(obj)) return -Infinity;
269 var result = {computed : -Infinity, value: -Infinity};
270 each(obj, function(value, index, list) {
271 var computed = iterator ? iterator.call(context, value, index, list) : value;
272 computed > result.computed && (result = {value : value, computed : computed});
273 });
274 return result.value;
275 };
276
277 // Return the minimum element (or element-based computation).
278 _.min = function(obj, iterator, context) {
279 if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
280 return Math.min.apply(Math, obj);
281 }
282 if (!iterator && _.isEmpty(obj)) return Infinity;
283 var result = {computed : Infinity, value: Infinity};
284 each(obj, function(value, index, list) {
285 var computed = iterator ? iterator.call(context, value, index, list) : value;
286 computed < result.computed && (result = {value : value, computed : computed});
287 });
288 return result.value;
289 };
290
291 // Shuffle an array, using the modern version of the
292 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
293 _.shuffle = function(obj) {
294 var rand;
295 var index = 0;
296 var shuffled = [];
297 each(obj, function(value) {
298 rand = _.random(index++);
299 shuffled[index - 1] = shuffled[rand];
300 shuffled[rand] = value;
301 });
302 return shuffled;
303 };
304
305 // Sample **n** random values from a collection.
306 // If **n** is not specified, returns a single random element.
307 // The internal `guard` argument allows it to work with `map`.
308 _.sample = function(obj, n, guard) {
309 if (n == null || guard) {
310 if (obj.length !== +obj.length) obj = _.values(obj);
311 return obj[_.random(obj.length - 1)];
312 }
313 return _.shuffle(obj).slice(0, Math.max(0, n));
314 };
315
316 // An internal function to generate lookup iterators.
317 var lookupIterator = function(value) {
318 if (value == null) return _.identity;
319 if (_.isFunction(value)) return value;
320 return _.property(value);
321 };
322
323 // Sort the object's values by a criterion produced by an iterator.
324 _.sortBy = function(obj, iterator, context) {
325 iterator = lookupIterator(iterator);
326 return _.pluck(_.map(obj, function(value, index, list) {
327 return {
328 value: value,
329 index: index,
330 criteria: iterator.call(context, value, index, list)
331 };
332 }).sort(function(left, right) {
333 var a = left.criteria;
334 var b = right.criteria;
335 if (a !== b) {
336 if (a > b || a === void 0) return 1;
337 if (a < b || b === void 0) return -1;
338 }
339 return left.index - right.index;
340 }), 'value');
341 };
342
343 // An internal function used for aggregate "group by" operations.
344 var group = function(behavior) {
345 return function(obj, iterator, context) {
346 var result = {};
347 iterator = lookupIterator(iterator);
348 each(obj, function(value, index) {
349 var key = iterator.call(context, value, index, obj);
350 behavior(result, key, value);
351 });
352 return result;
353 };
354 };
355
356 // Groups the object's values by a criterion. Pass either a string attribute
357 // to group by, or a function that returns the criterion.
358 _.groupBy = group(function(result, key, value) {
359 (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
360 });
361
362 // Indexes the object's values by a criterion, similar to `groupBy`, but for
363 // when you know that your index values will be unique.
364 _.indexBy = group(function(result, key, value) {
365 result[key] = value;
366 });
367
368 // Counts instances of an object that group by a certain criterion. Pass
369 // either a string attribute to count by, or a function that returns the
370 // criterion.
371 _.countBy = group(function(result, key) {
372 _.has(result, key) ? result[key]++ : result[key] = 1;
373 });
374
375 // Use a comparator function to figure out the smallest index at which
376 // an object should be inserted so as to maintain order. Uses binary search.
377 _.sortedIndex = function(array, obj, iterator, context) {
378 iterator = lookupIterator(iterator);
379 var value = iterator.call(context, obj);
380 var low = 0, high = array.length;
381 while (low < high) {
382 var mid = (low + high) >>> 1;
383 iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
384 }
385 return low;
386 };
387
388 // Safely create a real, live array from anything iterable.
389 _.toArray = function(obj) {
390 if (!obj) return [];
391 if (_.isArray(obj)) return slice.call(obj);
392 if (obj.length === +obj.length) return _.map(obj, _.identity);
393 return _.values(obj);
394 };
395
396 // Return the number of elements in an object.
397 _.size = function(obj) {
398 if (obj == null) return 0;
399 return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
400 };
401
402 // Array Functions
403 // ---------------
404
405 // Get the first element of an array. Passing **n** will return the first N
406 // values in the array. Aliased as `head` and `take`. The **guard** check
407 // allows it to work with `_.map`.
408 _.first = _.head = _.take = function(array, n, guard) {
409 if (array == null) return void 0;
410 if ((n == null) || guard) return array[0];
411 if (n < 0) return [];
412 return slice.call(array, 0, n);
413 };
414
415 // Returns everything but the last entry of the array. Especially useful on
416 // the arguments object. Passing **n** will return all the values in
417 // the array, excluding the last N. The **guard** check allows it to work with
418 // `_.map`.
419 _.initial = function(array, n, guard) {
420 return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
421 };
422
423 // Get the last element of an array. Passing **n** will return the last N
424 // values in the array. The **guard** check allows it to work with `_.map`.
425 _.last = function(array, n, guard) {
426 if (array == null) return void 0;
427 if ((n == null) || guard) return array[array.length - 1];
428 return slice.call(array, Math.max(array.length - n, 0));
429 };
430
431 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
432 // Especially useful on the arguments object. Passing an **n** will return
433 // the rest N values in the array. The **guard**
434 // check allows it to work with `_.map`.
435 _.rest = _.tail = _.drop = function(array, n, guard) {
436 return slice.call(array, (n == null) || guard ? 1 : n);
437 };
438
439 // Trim out all falsy values from an array.
440 _.compact = function(array) {
441 return _.filter(array, _.identity);
442 };
443
444 // Internal implementation of a recursive `flatten` function.
445 var flatten = function(input, shallow, output) {
446 if (shallow && _.every(input, _.isArray)) {
447 return concat.apply(output, input);
448 }
449 each(input, function(value) {
450 if (_.isArray(value) || _.isArguments(value)) {
451 shallow ? push.apply(output, value) : flatten(value, shallow, output);
452 } else {
453 output.push(value);
454 }
455 });
456 return output;
457 };
458
459 // Flatten out an array, either recursively (by default), or just one level.
460 _.flatten = function(array, shallow) {
461 return flatten(array, shallow, []);
462 };
463
464 // Return a version of the array that does not contain the specified value(s).
465 _.without = function(array) {
466 return _.difference(array, slice.call(arguments, 1));
467 };
468
469 // Produce a duplicate-free version of the array. If the array has already
470 // been sorted, you have the option of using a faster algorithm.
471 // Aliased as `unique`.
472 _.uniq = _.unique = function(array, isSorted, iterator, context) {
473 if (_.isFunction(isSorted)) {
474 context = iterator;
475 iterator = isSorted;
476 isSorted = false;
477 }
478 var initial = iterator ? _.map(array, iterator, context) : array;
479 var results = [];
480 var seen = [];
481 each(initial, function(value, index) {
482 if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
483 seen.push(value);
484 results.push(array[index]);
485 }
486 });
487 return results;
488 };
489
490 // Produce an array that contains the union: each distinct element from all of
491 // the passed-in arrays.
492 _.union = function() {
493 return _.uniq(_.flatten(arguments, true));
494 };
495
496 // Produce an array that contains every item shared between all the
497 // passed-in arrays.
498 _.intersection = function(array) {
499 var rest = slice.call(arguments, 1);
500 return _.filter(_.uniq(array), function(item) {
501 return _.every(rest, function(other) {
502 return _.indexOf(other, item) >= 0;
503 });
504 });
505 };
506
507 // Take the difference between one array and a number of other arrays.
508 // Only the elements present in just the first array will remain.
509 _.difference = function(array) {
510 var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
511 return _.filter(array, function(value){ return !_.contains(rest, value); });
512 };
513
514 // Zip together multiple lists into a single array -- elements that share
515 // an index go together.
516 _.zip = function() {
517 var length = _.max(_.pluck(arguments, "length").concat(0));
518 var results = new Array(length);
519 for (var i = 0; i < length; i++) {
520 results[i] = _.pluck(arguments, '' + i);
521 }
522 return results;
523 };
524
525 // Converts lists into objects. Pass either a single array of `[key, value]`
526 // pairs, or two parallel arrays of the same length -- one of keys, and one of
527 // the corresponding values.
528 _.object = function(list, values) {
529 if (list == null) return {};
530 var result = {};
531 for (var i = 0, length = list.length; i < length; i++) {
532 if (values) {
533 result[list[i]] = values[i];
534 } else {
535 result[list[i][0]] = list[i][1];
536 }
537 }
538 return result;
539 };
540
541 // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
542 // we need this function. Return the position of the first occurrence of an
543 // item in an array, or -1 if the item is not included in the array.
544 // Delegates to **ECMAScript 5**'s native `indexOf` if available.
545 // If the array is large and already in sort order, pass `true`
546 // for **isSorted** to use binary search.
547 _.indexOf = function(array, item, isSorted) {
548 if (array == null) return -1;
549 var i = 0, length = array.length;
550 if (isSorted) {
551 if (typeof isSorted == 'number') {
552 i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
553 } else {
554 i = _.sortedIndex(array, item);
555 return array[i] === item ? i : -1;
556 }
557 }
558 if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
559 for (; i < length; i++) if (array[i] === item) return i;
560 return -1;
561 };
562
563 // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
564 _.lastIndexOf = function(array, item, from) {
565 if (array == null) return -1;
566 var hasIndex = from != null;
567 if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
568 return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
569 }
570 var i = (hasIndex ? from : array.length);
571 while (i--) if (array[i] === item) return i;
572 return -1;
573 };
574
575 // Generate an integer Array containing an arithmetic progression. A port of
576 // the native Python `range()` function. See
577 // [the Python documentation](http://docs.python.org/library/functions.html#range).
578 _.range = function(start, stop, step) {
579 if (arguments.length <= 1) {
580 stop = start || 0;
581 start = 0;
582 }
583 step = arguments[2] || 1;
584
585 var length = Math.max(Math.ceil((stop - start) / step), 0);
586 var idx = 0;
587 var range = new Array(length);
588
589 while(idx < length) {
590 range[idx++] = start;
591 start += step;
592 }
593
594 return range;
595 };
596
597 // Function (ahem) Functions
598 // ------------------
599
600 // Reusable constructor function for prototype setting.
601 var ctor = function(){};
602
603 // Create a function bound to a given object (assigning `this`, and arguments,
604 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
605 // available.
606 _.bind = function(func, context) {
607 var args, bound;
608 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
609 if (!_.isFunction(func)) throw new TypeError;
610 args = slice.call(arguments, 2);
611 return bound = function() {
612 if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
613 ctor.prototype = func.prototype;
614 var self = new ctor;
615 ctor.prototype = null;
616 var result = func.apply(self, args.concat(slice.call(arguments)));
617 if (Object(result) === result) return result;
618 return self;
619 };
620 };
621
622 // Partially apply a function by creating a version that has had some of its
623 // arguments pre-filled, without changing its dynamic `this` context.
624 _.partial = function(func) {
625 var args = slice.call(arguments, 1);
626 return function() {
627 return func.apply(this, args.concat(slice.call(arguments)));
628 };
629 };
630
631 // Bind all of an object's methods to that object. Useful for ensuring that
632 // all callbacks defined on an object belong to it.
633 _.bindAll = function(obj) {
634 var funcs = slice.call(arguments, 1);
635 if (funcs.length === 0) throw new Error("bindAll must be passed function names");
636 each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
637 return obj;
638 };
639
640 // Memoize an expensive function by storing its results.
641 _.memoize = function(func, hasher) {
642 var memo = {};
643 hasher || (hasher = _.identity);
644 return function() {
645 var key = hasher.apply(this, arguments);
646 return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
647 };
648 };
649
650 // Delays a function for the given number of milliseconds, and then calls
651 // it with the arguments supplied.
652 _.delay = function(func, wait) {
653 var args = slice.call(arguments, 2);
654 return setTimeout(function(){ return func.apply(null, args); }, wait);
655 };
656
657 // Defers a function, scheduling it to run after the current call stack has
658 // cleared.
659 _.defer = function(func) {
660 return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
661 };
662
663 // Returns a function, that, when invoked, will only be triggered at most once
664 // during a given window of time. Normally, the throttled function will run
665 // as much as it can, without ever going more than once per `wait` duration;
666 // but if you'd like to disable the execution on the leading edge, pass
667 // `{leading: false}`. To disable execution on the trailing edge, ditto.
668 _.throttle = function(func, wait, options) {
669 var context, args, result;
670 var timeout = null;
671 var previous = 0;
672 options || (options = {});
673 var later = function() {
674 previous = options.leading === false ? 0 : getTime();
675 timeout = null;
676 result = func.apply(context, args);
677 context = args = null;
678 };
679 return function() {
680 var now = getTime();
681 if (!previous && options.leading === false) previous = now;
682 var remaining = wait - (now - previous);
683 context = this;
684 args = arguments;
685 if (remaining <= 0) {
686 clearTimeout(timeout);
687 timeout = null;
688 previous = now;
689 result = func.apply(context, args);
690 context = args = null;
691 } else if (!timeout && options.trailing !== false) {
692 timeout = setTimeout(later, remaining);
693 }
694 return result;
695 };
696 };
697
698 // Returns a function, that, as long as it continues to be invoked, will not
699 // be triggered. The function will be called after it stops being called for
700 // N milliseconds. If `immediate` is passed, trigger the function on the
701 // leading edge, instead of the trailing.
702 _.debounce = function(func, wait, immediate) {
703 var timeout, args, context, timestamp, result;
704 return function() {
705 context = this;
706 args = arguments;
707 timestamp = getTime();
708 var later = function() {
709 var last = getTime() - timestamp;
710 if (last < wait) {
711 timeout = setTimeout(later, wait - last);
712 } else {
713 timeout = null;
714 if (!immediate) {
715 result = func.apply(context, args);
716 context = args = null;
717 }
718 }
719 };
720 var callNow = immediate && !timeout;
721 if (!timeout) {
722 timeout = setTimeout(later, wait);
723 }
724 if (callNow) {
725 result = func.apply(context, args);
726 context = args = null;
727 }
728
729 return result;
730 };
731 };
732
733 // Returns a function that will be executed at most one time, no matter how
734 // often you call it. Useful for lazy initialization.
735 _.once = function(func) {
736 var ran = false, memo;
737 return function() {
738 if (ran) return memo;
739 ran = true;
740 memo = func.apply(this, arguments);
741 func = null;
742 return memo;
743 };
744 };
745
746 // Returns the first function passed as an argument to the second,
747 // allowing you to adjust arguments, run code before and after, and
748 // conditionally execute the original function.
749 _.wrap = function(func, wrapper) {
750 return _.partial(wrapper, func);
751 };
752
753 // Returns a function that is the composition of a list of functions, each
754 // consuming the return value of the function that follows.
755 _.compose = function() {
756 var funcs = arguments;
757 return function() {
758 var args = arguments;
759 for (var i = funcs.length - 1; i >= 0; i--) {
760 args = [funcs[i].apply(this, args)];
761 }
762 return args[0];
763 };
764 };
765
766 // Returns a function that will only be executed after being called N times.
767 _.after = function(times, func) {
768 return function() {
769 if (--times < 1) {
770 return func.apply(this, arguments);
771 }
772 };
773 };
774
775 // Object Functions
776 // ----------------
777
778 // Retrieve the names of an object's properties.
779 // Delegates to **ECMAScript 5**'s native `Object.keys`
780 _.keys = nativeKeys || function(obj) {
781 if (obj !== Object(obj)) throw new TypeError('Invalid object');
782 var keys = [];
783 for (var key in obj) if (_.has(obj, key)) keys.push(key);
784 return keys;
785 };
786
787 // Retrieve the values of an object's properties.
788 _.values = function(obj) {
789 var keys = _.keys(obj);
790 var length = keys.length;
791 var values = new Array(length);
792 for (var i = 0; i < length; i++) {
793 values[i] = obj[keys[i]];
794 }
795 return values;
796 };
797
798 // Convert an object into a list of `[key, value]` pairs.
799 _.pairs = function(obj) {
800 var keys = _.keys(obj);
801 var length = keys.length;
802 var pairs = new Array(length);
803 for (var i = 0; i < length; i++) {
804 pairs[i] = [keys[i], obj[keys[i]]];
805 }
806 return pairs;
807 };
808
809 // Invert the keys and values of an object. The values must be serializable.
810 _.invert = function(obj) {
811 var result = {};
812 var keys = _.keys(obj);
813 for (var i = 0, length = keys.length; i < length; i++) {
814 result[obj[keys[i]]] = keys[i];
815 }
816 return result;
817 };
818
819 // Return a sorted list of the function names available on the object.
820 // Aliased as `methods`
821 _.functions = _.methods = function(obj) {
822 var names = [];
823 for (var key in obj) {
824 if (_.isFunction(obj[key])) names.push(key);
825 }
826 return names.sort();
827 };
828
829 // Extend a given object with all the properties in passed-in object(s).
830 _.extend = function(obj) {
831 each(slice.call(arguments, 1), function(source) {
832 if (source) {
833 for (var prop in source) {
834 obj[prop] = source[prop];
835 }
836 }
837 });
838 return obj;
839 };
840
841 // Return a copy of the object only containing the whitelisted properties.
842 _.pick = function(obj) {
843 var copy = {};
844 var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
845 each(keys, function(key) {
846 if (key in obj) copy[key] = obj[key];
847 });
848 return copy;
849 };
850
851 // Return a copy of the object without the blacklisted properties.
852 _.omit = function(obj) {
853 var copy = {};
854 var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
855 for (var key in obj) {
856 if (!_.contains(keys, key)) copy[key] = obj[key];
857 }
858 return copy;
859 };
860
861 // Fill in a given object with default properties.
862 _.defaults = function(obj) {
863 each(slice.call(arguments, 1), function(source) {
864 if (source) {
865 for (var prop in source) {
866 if (obj[prop] === void 0) obj[prop] = source[prop];
867 }
868 }
869 });
870 return obj;
871 };
872
873 // Create a (shallow-cloned) duplicate of an object.
874 _.clone = function(obj) {
875 if (!_.isObject(obj)) return obj;
876 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
877 };
878
879 // Invokes interceptor with the obj, and then returns obj.
880 // The primary purpose of this method is to "tap into" a method chain, in
881 // order to perform operations on intermediate results within the chain.
882 _.tap = function(obj, interceptor) {
883 interceptor(obj);
884 return obj;
885 };
886
887 // Internal recursive comparison function for `isEqual`.
888 var eq = function(a, b, aStack, bStack) {
889 // Identical objects are equal. `0 === -0`, but they aren't identical.
890 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
891 if (a === b) return a !== 0 || 1 / a == 1 / b;
892 // A strict comparison is necessary because `null == undefined`.
893 if (a == null || b == null) return a === b;
894 // Unwrap any wrapped objects.
895 if (a instanceof _) a = a._wrapped;
896 if (b instanceof _) b = b._wrapped;
897 // Compare `[[Class]]` names.
898 var className = toString.call(a);
899 if (className != toString.call(b)) return false;
900 switch (className) {
901 // Strings, numbers, dates, and booleans are compared by value.
902 case '[object String]':
903 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
904 // equivalent to `new String("5")`.
905 return a == String(b);
906 case '[object Number]':
907 // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
908 // other numeric values.
909 return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
910 case '[object Date]':
911 case '[object Boolean]':
912 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
913 // millisecond representations. Note that invalid dates with millisecond representations
914 // of `NaN` are not equivalent.
915 return +a == +b;
916 // RegExps are compared by their source patterns and flags.
917 case '[object RegExp]':
918 return a.source == b.source &&
919 a.global == b.global &&
920 a.multiline == b.multiline &&
921 a.ignoreCase == b.ignoreCase;
922 }
923 if (typeof a != 'object' || typeof b != 'object') return false;
924 // Assume equality for cyclic structures. The algorithm for detecting cyclic
925 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
926 var length = aStack.length;
927 while (length--) {
928 // Linear search. Performance is inversely proportional to the number of
929 // unique nested structures.
930 if (aStack[length] == a) return bStack[length] == b;
931 }
932 // Objects with different constructors are not equivalent, but `Object`s
933 // from different frames are.
934 var aCtor = a.constructor, bCtor = b.constructor;
935 if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
936 _.isFunction(bCtor) && (bCtor instanceof bCtor))
937 && ('constructor' in a && 'constructor' in b)) {
938 return false;
939 }
940 // Add the first object to the stack of traversed objects.
941 aStack.push(a);
942 bStack.push(b);
943 var size = 0, result = true;
944 // Recursively compare objects and arrays.
945 if (className == '[object Array]') {
946 // Compare array lengths to determine if a deep comparison is necessary.
947 size = a.length;
948 result = size == b.length;
949 if (result) {
950 // Deep compare the contents, ignoring non-numeric properties.
951 while (size--) {
952 if (!(result = eq(a[size], b[size], aStack, bStack))) break;
953 }
954 }
955 } else {
956 // Deep compare objects.
957 for (var key in a) {
958 if (_.has(a, key)) {
959 // Count the expected number of properties.
960 size++;
961 // Deep compare each member.
962 if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
963 }
964 }
965 // Ensure that both objects contain the same number of properties.
966 if (result) {
967 for (key in b) {
968 if (_.has(b, key) && !(size--)) break;
969 }
970 result = !size;
971 }
972 }
973 // Remove the first object from the stack of traversed objects.
974 aStack.pop();
975 bStack.pop();
976 return result;
977 };
978
979 // Perform a deep comparison to check if two objects are equal.
980 _.isEqual = function(a, b) {
981 return eq(a, b, [], []);
982 };
983
984 // Is a given array, string, or object empty?
985 // An "empty" object has no enumerable own-properties.
986 _.isEmpty = function(obj) {
987 if (obj == null) return true;
988 if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
989 for (var key in obj) if (_.has(obj, key)) return false;
990 return true;
991 };
992
993 // Is a given value a DOM element?
994 _.isElement = function(obj) {
995 return !!(obj && obj.nodeType === 1);
996 };
997
998 // Is a given value an array?
999 // Delegates to ECMA5's native Array.isArray
1000 _.isArray = nativeIsArray || function(obj) {
1001 return toString.call(obj) == '[object Array]';
1002 };
1003
1004 // Is a given variable an object?
1005 _.isObject = function(obj) {
1006 return obj === Object(obj);
1007 };
1008
1009 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
1010 each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
1011 _['is' + name] = function(obj) {
1012 return toString.call(obj) == '[object ' + name + ']';
1013 };
1014 });
1015
1016 // Define a fallback version of the method in browsers (ahem, IE), where
1017 // there isn't any inspectable "Arguments" type.
1018 if (!_.isArguments(arguments)) {
1019 _.isArguments = function(obj) {
1020 return !!(obj && _.has(obj, 'callee'));
1021 };
1022 }
1023
1024 // Optimize `isFunction` if appropriate.
1025 if (typeof (/./) !== 'function') {
1026 _.isFunction = function(obj) {
1027 return typeof obj === 'function';
1028 };
1029 }
1030
1031 // Is a given object a finite number?
1032 _.isFinite = function(obj) {
1033 return isFinite(obj) && !isNaN(parseFloat(obj));
1034 };
1035
1036 // Is the given value `NaN`? (NaN is the only number which does not equal itself).
1037 _.isNaN = function(obj) {
1038 return _.isNumber(obj) && obj != +obj;
1039 };
1040
1041 // Is a given value a boolean?
1042 _.isBoolean = function(obj) {
1043 return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
1044 };
1045
1046 // Is a given value equal to null?
1047 _.isNull = function(obj) {
1048 return obj === null;
1049 };
1050
1051 // Is a given variable undefined?
1052 _.isUndefined = function(obj) {
1053 return obj === void 0;
1054 };
1055
1056 // Shortcut function for checking if an object has a given property directly
1057 // on itself (in other words, not on a prototype).
1058 _.has = function(obj, key) {
1059 return hasOwnProperty.call(obj, key);
1060 };
1061
1062 // Utility Functions
1063 // -----------------
1064
1065 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
1066 // previous owner. Returns a reference to the Underscore object.
1067 _.noConflict = function() {
1068 root._ = previousUnderscore;
1069 return this;
1070 };
1071
1072 // Keep the identity function around for default iterators.
1073 _.identity = function(value) {
1074 return value;
1075 };
1076
1077 _.constant = function(value) {
1078 return function () {
1079 return value;
1080 };
1081 };
1082
1083 _.property = function(key) {
1084 return function(obj) {
1085 return obj[key];
1086 };
1087 };
1088
1089 // Run a function **n** times.
1090 _.times = function(n, iterator, context) {
1091 var accum = Array(Math.max(0, n));
1092 for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
1093 return accum;
1094 };
1095
1096 // Return a random integer between min and max (inclusive).
1097 _.random = function(min, max) {
1098 if (max == null) {
1099 max = min;
1100 min = 0;
1101 }
1102 return min + Math.floor(Math.random() * (max - min + 1));
1103 };
1104
1105 // List of HTML entities for escaping.
1106 var entityMap = {
1107 escape: {
1108 '&': '&amp;',
1109 '<': '&lt;',
1110 '>': '&gt;',
1111 '"': '&quot;',
1112 "'": '&#x27;'
1113 }
1114 };
1115 entityMap.unescape = _.invert(entityMap.escape);
1116
1117 // Regexes containing the keys and values listed immediately above.
1118 var entityRegexes = {
1119 escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
1120 unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
1121 };
1122
1123 // Functions for escaping and unescaping strings to/from HTML interpolation.
1124 _.each(['escape', 'unescape'], function(method) {
1125 _[method] = function(string) {
1126 if (string == null) return '';
1127 return ('' + string).replace(entityRegexes[method], function(match) {
1128 return entityMap[method][match];
1129 });
1130 };
1131 });
1132
1133 // If the value of the named `property` is a function then invoke it with the
1134 // `object` as context; otherwise, return it.
1135 _.result = function(object, property) {
1136 if (object == null) return void 0;
1137 var value = object[property];
1138 return _.isFunction(value) ? value.call(object) : value;
1139 };
1140
1141 // Add your own custom functions to the Underscore object.
1142 _.mixin = function(obj) {
1143 each(_.functions(obj), function(name) {
1144 var func = _[name] = obj[name];
1145 _.prototype[name] = function() {
1146 var args = [this._wrapped];
1147 push.apply(args, arguments);
1148 return result.call(this, func.apply(_, args));
1149 };
1150 });
1151 };
1152
1153 // Generate a unique integer id (unique within the entire client session).
1154 // Useful for temporary DOM ids.
1155 var idCounter = 0;
1156 _.uniqueId = function(prefix) {
1157 var id = ++idCounter + '';
1158 return prefix ? prefix + id : id;
1159 };
1160
1161 // By default, Underscore uses ERB-style template delimiters, change the
1162 // following template settings to use alternative delimiters.
1163 _.templateSettings = {
1164 evaluate : /<%([\s\S]+?)%>/g,
1165 interpolate : /<%=([\s\S]+?)%>/g,
1166 escape : /<%-([\s\S]+?)%>/g
1167 };
1168
1169 // When customizing `templateSettings`, if you don't want to define an
1170 // interpolation, evaluation or escaping regex, we need one that is
1171 // guaranteed not to match.
1172 var noMatch = /(.)^/;
1173
1174 // Certain characters need to be escaped so that they can be put into a
1175 // string literal.
1176 var escapes = {
1177 "'": "'",
1178 '\\': '\\',
1179 '\r': 'r',
1180 '\n': 'n',
1181 '\t': 't',
1182 '\u2028': 'u2028',
1183 '\u2029': 'u2029'
1184 };
1185
1186 var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
1187
1188 // JavaScript micro-templating, similar to John Resig's implementation.
1189 // Underscore templating handles arbitrary delimiters, preserves whitespace,
1190 // and correctly escapes quotes within interpolated code.
1191 _.template = function(text, data, settings) {
1192 var render;
1193 settings = _.defaults({}, settings, _.templateSettings);
1194
1195 // Combine delimiters into one regular expression via alternation.
1196 var matcher = new RegExp([
1197 (settings.escape || noMatch).source,
1198 (settings.interpolate || noMatch).source,
1199 (settings.evaluate || noMatch).source
1200 ].join('|') + '|$', 'g');
1201
1202 // Compile the template source, escaping string literals appropriately.
1203 var index = 0;
1204 var source = "__p+='";
1205 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
1206 source += text.slice(index, offset)
1207 .replace(escaper, function(match) { return '\\' + escapes[match]; });
1208
1209 if (escape) {
1210 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
1211 }
1212 if (interpolate) {
1213 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
1214 }
1215 if (evaluate) {
1216 source += "';\n" + evaluate + "\n__p+='";
1217 }
1218 index = offset + match.length;
1219 return match;
1220 });
1221 source += "';\n";
1222
1223 // If a variable is not specified, place data values in local scope.
1224 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
1225
1226 source = "var __t,__p='',__j=Array.prototype.join," +
1227 "print=function(){__p+=__j.call(arguments,'');};\n" +
1228 source + "return __p;\n";
1229
1230 try {
1231 render = new Function(settings.variable || 'obj', '_', source);
1232 } catch (e) {
1233 e.source = source;
1234 throw e;
1235 }
1236
1237 if (data) return render(data, _);
1238 var template = function(data) {
1239 return render.call(this, data, _);
1240 };
1241
1242 // Provide the compiled function source as a convenience for precompilation.
1243 template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
1244
1245 return template;
1246 };
1247
1248 // Add a "chain" function, which will delegate to the wrapper.
1249 _.chain = function(obj) {
1250 return _(obj).chain();
1251 };
1252
1253 // OOP
1254 // ---------------
1255 // If Underscore is called as a function, it returns a wrapped object that
1256 // can be used OO-style. This wrapper holds altered versions of all the
1257 // underscore functions. Wrapped objects may be chained.
1258
1259 // Helper function to continue chaining intermediate results.
1260 var result = function(obj) {
1261 return this._chain ? _(obj).chain() : obj;
1262 };
1263
1264 // Add all of the Underscore functions to the wrapper object.
1265 _.mixin(_);
1266
1267 // Add all mutator Array functions to the wrapper.
1268 each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
1269 var method = ArrayProto[name];
1270 _.prototype[name] = function() {
1271 var obj = this._wrapped;
1272 method.apply(obj, arguments);
1273 if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
1274 return result.call(this, obj);
1275 };
1276 });
1277
1278 // Add all accessor Array functions to the wrapper.
1279 each(['concat', 'join', 'slice'], function(name) {
1280 var method = ArrayProto[name];
1281 _.prototype[name] = function() {
1282 return result.call(this, method.apply(this._wrapped, arguments));
1283 };
1284 });
1285
1286 _.extend(_.prototype, {
1287
1288 // Start chaining a wrapped Underscore object.
1289 chain: function() {
1290 this._chain = true;
1291 return this;
1292 },
1293
1294 // Extracts the result from a wrapped and chained object.
1295 value: function() {
1296 return this._wrapped;
1297 }
1298
1299 });
1300
1301 // AMD registration happens at the end for compatibility with AMD loaders
1302 // that may not enforce next-turn semantics on modules. Even though general
1303 // practice for AMD registration is to be anonymous, underscore registers
1304 // as a named module because, like jQuery, it is a base library that is
1305 // popular enough to be bundled in a third party lib, but not be part of
1306 // an AMD load request. Those cases could generate an error when an
1307 // anonymous define() is called outside of a loader request.
1308 if (typeof define === 'function' && define.amd) {
1309 define('underscore', [], function() {
1310 return _;
1311 });
1312 }
1313 }).call(this);