Debian Codegraph @

beetsplug/web/static/underscore.js

raw
1 // Underscore.js 1.2.2
2 // (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
3 // Underscore is freely distributable under the MIT license.
4 // Portions of Underscore are inspired or borrowed from Prototype,
5 // Oliver Steele's Functional, and John Resig's Micro-Templating.
6 // For all details and documentation:
7 // http://documentcloud.github.com/underscore
8
9 (function() {
10
11 // Baseline setup
12 // --------------
13
14 // Establish the root object, `window` in the browser, or `global` on the server.
15 var root = this;
16
17 // Save the previous value of the `_` variable.
18 var previousUnderscore = root._;
19
20 // Establish the object that gets returned to break out of a loop iteration.
21 var breaker = {};
22
23 // Save bytes in the minified (but not gzipped) version:
24 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
25
26 // Create quick reference variables for speed access to core prototypes.
27 var slice = ArrayProto.slice,
28 unshift = ArrayProto.unshift,
29 toString = ObjProto.toString,
30 hasOwnProperty = ObjProto.hasOwnProperty;
31
32 // All **ECMAScript 5** native function implementations that we hope to use
33 // are declared here.
34 var
35 nativeForEach = ArrayProto.forEach,
36 nativeMap = ArrayProto.map,
37 nativeReduce = ArrayProto.reduce,
38 nativeReduceRight = ArrayProto.reduceRight,
39 nativeFilter = ArrayProto.filter,
40 nativeEvery = ArrayProto.every,
41 nativeSome = ArrayProto.some,
42 nativeIndexOf = ArrayProto.indexOf,
43 nativeLastIndexOf = ArrayProto.lastIndexOf,
44 nativeIsArray = Array.isArray,
45 nativeKeys = Object.keys,
46 nativeBind = FuncProto.bind;
47
48 // Create a safe reference to the Underscore object for use below.
49 var _ = function(obj) { return new wrapper(obj); };
50
51 // Export the Underscore object for **Node.js** and **"CommonJS"**, with
52 // backwards-compatibility for the old `require()` API. If we're not in
53 // CommonJS, add `_` to the global object.
54 if (typeof exports !== 'undefined') {
55 if (typeof module !== 'undefined' && module.exports) {
56 exports = module.exports = _;
57 }
58 exports._ = _;
59 } else if (typeof define === 'function' && define.amd) {
60 // Register as a named module with AMD.
61 define('underscore', function() {
62 return _;
63 });
64 } else {
65 // Exported as a string, for Closure Compiler "advanced" mode.
66 root['_'] = _;
67 }
68
69 // Current version.
70 _.VERSION = '1.2.2';
71
72 // Collection Functions
73 // --------------------
74
75 // The cornerstone, an `each` implementation, aka `forEach`.
76 // Handles objects with the built-in `forEach`, arrays, and raw objects.
77 // Delegates to **ECMAScript 5**'s native `forEach` if available.
78 var each = _.each = _.forEach = function(obj, iterator, context) {
79 if (obj == null) return;
80 if (nativeForEach && obj.forEach === nativeForEach) {
81 obj.forEach(iterator, context);
82 } else if (obj.length === +obj.length) {
83 for (var i = 0, l = obj.length; i < l; i++) {
84 if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
85 }
86 } else {
87 for (var key in obj) {
88 if (hasOwnProperty.call(obj, key)) {
89 if (iterator.call(context, obj[key], key, obj) === breaker) return;
90 }
91 }
92 }
93 };
94
95 // Return the results of applying the iterator to each element.
96 // Delegates to **ECMAScript 5**'s native `map` if available.
97 _.map = function(obj, iterator, context) {
98 var results = [];
99 if (obj == null) return results;
100 if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
101 each(obj, function(value, index, list) {
102 results[results.length] = iterator.call(context, value, index, list);
103 });
104 return results;
105 };
106
107 // **Reduce** builds up a single result from a list of values, aka `inject`,
108 // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
109 _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
110 var initial = memo !== void 0;
111 if (obj == null) obj = [];
112 if (nativeReduce && obj.reduce === nativeReduce) {
113 if (context) iterator = _.bind(iterator, context);
114 return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
115 }
116 each(obj, function(value, index, list) {
117 if (!initial) {
118 memo = value;
119 initial = true;
120 } else {
121 memo = iterator.call(context, memo, value, index, list);
122 }
123 });
124 if (!initial) throw new TypeError("Reduce of empty array with no initial value");
125 return memo;
126 };
127
128 // The right-associative version of reduce, also known as `foldr`.
129 // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
130 _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
131 if (obj == null) obj = [];
132 if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
133 if (context) iterator = _.bind(iterator, context);
134 return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
135 }
136 var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
137 return _.reduce(reversed, iterator, memo, context);
138 };
139
140 // Return the first value which passes a truth test. Aliased as `detect`.
141 _.find = _.detect = function(obj, iterator, context) {
142 var result;
143 any(obj, function(value, index, list) {
144 if (iterator.call(context, value, index, list)) {
145 result = value;
146 return true;
147 }
148 });
149 return result;
150 };
151
152 // Return all the elements that pass a truth test.
153 // Delegates to **ECMAScript 5**'s native `filter` if available.
154 // Aliased as `select`.
155 _.filter = _.select = function(obj, iterator, context) {
156 var results = [];
157 if (obj == null) return results;
158 if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
159 each(obj, function(value, index, list) {
160 if (iterator.call(context, value, index, list)) results[results.length] = value;
161 });
162 return results;
163 };
164
165 // Return all the elements for which a truth test fails.
166 _.reject = function(obj, iterator, context) {
167 var results = [];
168 if (obj == null) return results;
169 each(obj, function(value, index, list) {
170 if (!iterator.call(context, value, index, list)) results[results.length] = value;
171 });
172 return results;
173 };
174
175 // Determine whether all of the elements match a truth test.
176 // Delegates to **ECMAScript 5**'s native `every` if available.
177 // Aliased as `all`.
178 _.every = _.all = function(obj, iterator, context) {
179 var result = true;
180 if (obj == null) return result;
181 if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
182 each(obj, function(value, index, list) {
183 if (!(result = result && iterator.call(context, value, index, list))) return breaker;
184 });
185 return result;
186 };
187
188 // Determine if at least one element in the object matches a truth test.
189 // Delegates to **ECMAScript 5**'s native `some` if available.
190 // Aliased as `any`.
191 var any = _.some = _.any = function(obj, iterator, context) {
192 iterator = iterator || _.identity;
193 var result = false;
194 if (obj == null) return result;
195 if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
196 each(obj, function(value, index, list) {
197 if (result || (result = iterator.call(context, value, index, list))) return breaker;
198 });
199 return !!result;
200 };
201
202 // Determine if a given value is included in the array or object using `===`.
203 // Aliased as `contains`.
204 _.include = _.contains = function(obj, target) {
205 var found = false;
206 if (obj == null) return found;
207 if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
208 found = any(obj, function(value) {
209 return value === target;
210 });
211 return found;
212 };
213
214 // Invoke a method (with arguments) on every item in a collection.
215 _.invoke = function(obj, method) {
216 var args = slice.call(arguments, 2);
217 return _.map(obj, function(value) {
218 return (method.call ? method || value : value[method]).apply(value, args);
219 });
220 };
221
222 // Convenience version of a common use case of `map`: fetching a property.
223 _.pluck = function(obj, key) {
224 return _.map(obj, function(value){ return value[key]; });
225 };
226
227 // Return the maximum element or (element-based computation).
228 _.max = function(obj, iterator, context) {
229 if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
230 if (!iterator && _.isEmpty(obj)) return -Infinity;
231 var result = {computed : -Infinity};
232 each(obj, function(value, index, list) {
233 var computed = iterator ? iterator.call(context, value, index, list) : value;
234 computed >= result.computed && (result = {value : value, computed : computed});
235 });
236 return result.value;
237 };
238
239 // Return the minimum element (or element-based computation).
240 _.min = function(obj, iterator, context) {
241 if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
242 if (!iterator && _.isEmpty(obj)) return Infinity;
243 var result = {computed : Infinity};
244 each(obj, function(value, index, list) {
245 var computed = iterator ? iterator.call(context, value, index, list) : value;
246 computed < result.computed && (result = {value : value, computed : computed});
247 });
248 return result.value;
249 };
250
251 // Shuffle an array.
252 _.shuffle = function(obj) {
253 var shuffled = [], rand;
254 each(obj, function(value, index, list) {
255 if (index == 0) {
256 shuffled[0] = value;
257 } else {
258 rand = Math.floor(Math.random() * (index + 1));
259 shuffled[index] = shuffled[rand];
260 shuffled[rand] = value;
261 }
262 });
263 return shuffled;
264 };
265
266 // Sort the object's values by a criterion produced by an iterator.
267 _.sortBy = function(obj, iterator, context) {
268 return _.pluck(_.map(obj, function(value, index, list) {
269 return {
270 value : value,
271 criteria : iterator.call(context, value, index, list)
272 };
273 }).sort(function(left, right) {
274 var a = left.criteria, b = right.criteria;
275 return a < b ? -1 : a > b ? 1 : 0;
276 }), 'value');
277 };
278
279 // Groups the object's values by a criterion. Pass either a string attribute
280 // to group by, or a function that returns the criterion.
281 _.groupBy = function(obj, val) {
282 var result = {};
283 var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
284 each(obj, function(value, index) {
285 var key = iterator(value, index);
286 (result[key] || (result[key] = [])).push(value);
287 });
288 return result;
289 };
290
291 // Use a comparator function to figure out at what index an object should
292 // be inserted so as to maintain order. Uses binary search.
293 _.sortedIndex = function(array, obj, iterator) {
294 iterator || (iterator = _.identity);
295 var low = 0, high = array.length;
296 while (low < high) {
297 var mid = (low + high) >> 1;
298 iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
299 }
300 return low;
301 };
302
303 // Safely convert anything iterable into a real, live array.
304 _.toArray = function(iterable) {
305 if (!iterable) return [];
306 if (iterable.toArray) return iterable.toArray();
307 if (_.isArray(iterable)) return slice.call(iterable);
308 if (_.isArguments(iterable)) return slice.call(iterable);
309 return _.values(iterable);
310 };
311
312 // Return the number of elements in an object.
313 _.size = function(obj) {
314 return _.toArray(obj).length;
315 };
316
317 // Array Functions
318 // ---------------
319
320 // Get the first element of an array. Passing **n** will return the first N
321 // values in the array. Aliased as `head`. The **guard** check allows it to work
322 // with `_.map`.
323 _.first = _.head = function(array, n, guard) {
324 return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
325 };
326
327 // Returns everything but the last entry of the array. Especcialy useful on
328 // the arguments object. Passing **n** will return all the values in
329 // the array, excluding the last N. The **guard** check allows it to work with
330 // `_.map`.
331 _.initial = function(array, n, guard) {
332 return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
333 };
334
335 // Get the last element of an array. Passing **n** will return the last N
336 // values in the array. The **guard** check allows it to work with `_.map`.
337 _.last = function(array, n, guard) {
338 if ((n != null) && !guard) {
339 return slice.call(array, Math.max(array.length - n, 0));
340 } else {
341 return array[array.length - 1];
342 }
343 };
344
345 // Returns everything but the first entry of the array. Aliased as `tail`.
346 // Especially useful on the arguments object. Passing an **index** will return
347 // the rest of the values in the array from that index onward. The **guard**
348 // check allows it to work with `_.map`.
349 _.rest = _.tail = function(array, index, guard) {
350 return slice.call(array, (index == null) || guard ? 1 : index);
351 };
352
353 // Trim out all falsy values from an array.
354 _.compact = function(array) {
355 return _.filter(array, function(value){ return !!value; });
356 };
357
358 // Return a completely flattened version of an array.
359 _.flatten = function(array, shallow) {
360 return _.reduce(array, function(memo, value) {
361 if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
362 memo[memo.length] = value;
363 return memo;
364 }, []);
365 };
366
367 // Return a version of the array that does not contain the specified value(s).
368 _.without = function(array) {
369 return _.difference(array, slice.call(arguments, 1));
370 };
371
372 // Produce a duplicate-free version of the array. If the array has already
373 // been sorted, you have the option of using a faster algorithm.
374 // Aliased as `unique`.
375 _.uniq = _.unique = function(array, isSorted, iterator) {
376 var initial = iterator ? _.map(array, iterator) : array;
377 var result = [];
378 _.reduce(initial, function(memo, el, i) {
379 if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
380 memo[memo.length] = el;
381 result[result.length] = array[i];
382 }
383 return memo;
384 }, []);
385 return result;
386 };
387
388 // Produce an array that contains the union: each distinct element from all of
389 // the passed-in arrays.
390 _.union = function() {
391 return _.uniq(_.flatten(arguments, true));
392 };
393
394 // Produce an array that contains every item shared between all the
395 // passed-in arrays. (Aliased as "intersect" for back-compat.)
396 _.intersection = _.intersect = function(array) {
397 var rest = slice.call(arguments, 1);
398 return _.filter(_.uniq(array), function(item) {
399 return _.every(rest, function(other) {
400 return _.indexOf(other, item) >= 0;
401 });
402 });
403 };
404
405 // Take the difference between one array and another.
406 // Only the elements present in just the first array will remain.
407 _.difference = function(array, other) {
408 return _.filter(array, function(value){ return !_.include(other, value); });
409 };
410
411 // Zip together multiple lists into a single array -- elements that share
412 // an index go together.
413 _.zip = function() {
414 var args = slice.call(arguments);
415 var length = _.max(_.pluck(args, 'length'));
416 var results = new Array(length);
417 for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
418 return results;
419 };
420
421 // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
422 // we need this function. Return the position of the first occurrence of an
423 // item in an array, or -1 if the item is not included in the array.
424 // Delegates to **ECMAScript 5**'s native `indexOf` if available.
425 // If the array is large and already in sort order, pass `true`
426 // for **isSorted** to use binary search.
427 _.indexOf = function(array, item, isSorted) {
428 if (array == null) return -1;
429 var i, l;
430 if (isSorted) {
431 i = _.sortedIndex(array, item);
432 return array[i] === item ? i : -1;
433 }
434 if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
435 for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
436 return -1;
437 };
438
439 // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
440 _.lastIndexOf = function(array, item) {
441 if (array == null) return -1;
442 if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
443 var i = array.length;
444 while (i--) if (array[i] === item) return i;
445 return -1;
446 };
447
448 // Generate an integer Array containing an arithmetic progression. A port of
449 // the native Python `range()` function. See
450 // [the Python documentation](http://docs.python.org/library/functions.html#range).
451 _.range = function(start, stop, step) {
452 if (arguments.length <= 1) {
453 stop = start || 0;
454 start = 0;
455 }
456 step = arguments[2] || 1;
457
458 var len = Math.max(Math.ceil((stop - start) / step), 0);
459 var idx = 0;
460 var range = new Array(len);
461
462 while(idx < len) {
463 range[idx++] = start;
464 start += step;
465 }
466
467 return range;
468 };
469
470 // Function (ahem) Functions
471 // ------------------
472
473 // Reusable constructor function for prototype setting.
474 var ctor = function(){};
475
476 // Create a function bound to a given object (assigning `this`, and arguments,
477 // optionally). Binding with arguments is also known as `curry`.
478 // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
479 // We check for `func.bind` first, to fail fast when `func` is undefined.
480 _.bind = function bind(func, context) {
481 var bound, args;
482 if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
483 if (!_.isFunction(func)) throw new TypeError;
484 args = slice.call(arguments, 2);
485 return bound = function() {
486 if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
487 ctor.prototype = func.prototype;
488 var self = new ctor;
489 var result = func.apply(self, args.concat(slice.call(arguments)));
490 if (Object(result) === result) return result;
491 return self;
492 };
493 };
494
495 // Bind all of an object's methods to that object. Useful for ensuring that
496 // all callbacks defined on an object belong to it.
497 _.bindAll = function(obj) {
498 var funcs = slice.call(arguments, 1);
499 if (funcs.length == 0) funcs = _.functions(obj);
500 each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
501 return obj;
502 };
503
504 // Memoize an expensive function by storing its results.
505 _.memoize = function(func, hasher) {
506 var memo = {};
507 hasher || (hasher = _.identity);
508 return function() {
509 var key = hasher.apply(this, arguments);
510 return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
511 };
512 };
513
514 // Delays a function for the given number of milliseconds, and then calls
515 // it with the arguments supplied.
516 _.delay = function(func, wait) {
517 var args = slice.call(arguments, 2);
518 return setTimeout(function(){ return func.apply(func, args); }, wait);
519 };
520
521 // Defers a function, scheduling it to run after the current call stack has
522 // cleared.
523 _.defer = function(func) {
524 return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
525 };
526
527 // Returns a function, that, when invoked, will only be triggered at most once
528 // during a given window of time.
529 _.throttle = function(func, wait) {
530 var context, args, timeout, throttling, more;
531 var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
532 return function() {
533 context = this; args = arguments;
534 var later = function() {
535 timeout = null;
536 if (more) func.apply(context, args);
537 whenDone();
538 };
539 if (!timeout) timeout = setTimeout(later, wait);
540 if (throttling) {
541 more = true;
542 } else {
543 func.apply(context, args);
544 }
545 whenDone();
546 throttling = true;
547 };
548 };
549
550 // Returns a function, that, as long as it continues to be invoked, will not
551 // be triggered. The function will be called after it stops being called for
552 // N milliseconds.
553 _.debounce = function(func, wait) {
554 var timeout;
555 return function() {
556 var context = this, args = arguments;
557 var later = function() {
558 timeout = null;
559 func.apply(context, args);
560 };
561 clearTimeout(timeout);
562 timeout = setTimeout(later, wait);
563 };
564 };
565
566 // Returns a function that will be executed at most one time, no matter how
567 // often you call it. Useful for lazy initialization.
568 _.once = function(func) {
569 var ran = false, memo;
570 return function() {
571 if (ran) return memo;
572 ran = true;
573 return memo = func.apply(this, arguments);
574 };
575 };
576
577 // Returns the first function passed as an argument to the second,
578 // allowing you to adjust arguments, run code before and after, and
579 // conditionally execute the original function.
580 _.wrap = function(func, wrapper) {
581 return function() {
582 var args = [func].concat(slice.call(arguments));
583 return wrapper.apply(this, args);
584 };
585 };
586
587 // Returns a function that is the composition of a list of functions, each
588 // consuming the return value of the function that follows.
589 _.compose = function() {
590 var funcs = slice.call(arguments);
591 return function() {
592 var args = slice.call(arguments);
593 for (var i = funcs.length - 1; i >= 0; i--) {
594 args = [funcs[i].apply(this, args)];
595 }
596 return args[0];
597 };
598 };
599
600 // Returns a function that will only be executed after being called N times.
601 _.after = function(times, func) {
602 if (times <= 0) return func();
603 return function() {
604 if (--times < 1) { return func.apply(this, arguments); }
605 };
606 };
607
608 // Object Functions
609 // ----------------
610
611 // Retrieve the names of an object's properties.
612 // Delegates to **ECMAScript 5**'s native `Object.keys`
613 _.keys = nativeKeys || function(obj) {
614 if (obj !== Object(obj)) throw new TypeError('Invalid object');
615 var keys = [];
616 for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
617 return keys;
618 };
619
620 // Retrieve the values of an object's properties.
621 _.values = function(obj) {
622 return _.map(obj, _.identity);
623 };
624
625 // Return a sorted list of the function names available on the object.
626 // Aliased as `methods`
627 _.functions = _.methods = function(obj) {
628 var names = [];
629 for (var key in obj) {
630 if (_.isFunction(obj[key])) names.push(key);
631 }
632 return names.sort();
633 };
634
635 // Extend a given object with all the properties in passed-in object(s).
636 _.extend = function(obj) {
637 each(slice.call(arguments, 1), function(source) {
638 for (var prop in source) {
639 if (source[prop] !== void 0) obj[prop] = source[prop];
640 }
641 });
642 return obj;
643 };
644
645 // Fill in a given object with default properties.
646 _.defaults = function(obj) {
647 each(slice.call(arguments, 1), function(source) {
648 for (var prop in source) {
649 if (obj[prop] == null) obj[prop] = source[prop];
650 }
651 });
652 return obj;
653 };
654
655 // Create a (shallow-cloned) duplicate of an object.
656 _.clone = function(obj) {
657 if (!_.isObject(obj)) return obj;
658 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
659 };
660
661 // Invokes interceptor with the obj, and then returns obj.
662 // The primary purpose of this method is to "tap into" a method chain, in
663 // order to perform operations on intermediate results within the chain.
664 _.tap = function(obj, interceptor) {
665 interceptor(obj);
666 return obj;
667 };
668
669 // Internal recursive comparison function.
670 function eq(a, b, stack) {
671 // Identical objects are equal. `0 === -0`, but they aren't identical.
672 // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
673 if (a === b) return a !== 0 || 1 / a == 1 / b;
674 // A strict comparison is necessary because `null == undefined`.
675 if (a == null || b == null) return a === b;
676 // Unwrap any wrapped objects.
677 if (a._chain) a = a._wrapped;
678 if (b._chain) b = b._wrapped;
679 // Invoke a custom `isEqual` method if one is provided.
680 if (_.isFunction(a.isEqual)) return a.isEqual(b);
681 if (_.isFunction(b.isEqual)) return b.isEqual(a);
682 // Compare `[[Class]]` names.
683 var className = toString.call(a);
684 if (className != toString.call(b)) return false;
685 switch (className) {
686 // Strings, numbers, dates, and booleans are compared by value.
687 case '[object String]':
688 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
689 // equivalent to `new String("5")`.
690 return String(a) == String(b);
691 case '[object Number]':
692 a = +a;
693 b = +b;
694 // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
695 // other numeric values.
696 return a != a ? b != b : (a == 0 ? 1 / a == 1 / b : a == b);
697 case '[object Date]':
698 case '[object Boolean]':
699 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
700 // millisecond representations. Note that invalid dates with millisecond representations
701 // of `NaN` are not equivalent.
702 return +a == +b;
703 // RegExps are compared by their source patterns and flags.
704 case '[object RegExp]':
705 return a.source == b.source &&
706 a.global == b.global &&
707 a.multiline == b.multiline &&
708 a.ignoreCase == b.ignoreCase;
709 }
710 if (typeof a != 'object' || typeof b != 'object') return false;
711 // Assume equality for cyclic structures. The algorithm for detecting cyclic
712 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
713 var length = stack.length;
714 while (length--) {
715 // Linear search. Performance is inversely proportional to the number of
716 // unique nested structures.
717 if (stack[length] == a) return true;
718 }
719 // Add the first object to the stack of traversed objects.
720 stack.push(a);
721 var size = 0, result = true;
722 // Recursively compare objects and arrays.
723 if (className == '[object Array]') {
724 // Compare array lengths to determine if a deep comparison is necessary.
725 size = a.length;
726 result = size == b.length;
727 if (result) {
728 // Deep compare the contents, ignoring non-numeric properties.
729 while (size--) {
730 // Ensure commutative equality for sparse arrays.
731 if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
732 }
733 }
734 } else {
735 // Objects with different constructors are not equivalent.
736 if ("constructor" in a != "constructor" in b || a.constructor != b.constructor) return false;
737 // Deep compare objects.
738 for (var key in a) {
739 if (hasOwnProperty.call(a, key)) {
740 // Count the expected number of properties.
741 size++;
742 // Deep compare each member.
743 if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break;
744 }
745 }
746 // Ensure that both objects contain the same number of properties.
747 if (result) {
748 for (key in b) {
749 if (hasOwnProperty.call(b, key) && !(size--)) break;
750 }
751 result = !size;
752 }
753 }
754 // Remove the first object from the stack of traversed objects.
755 stack.pop();
756 return result;
757 }
758
759 // Perform a deep comparison to check if two objects are equal.
760 _.isEqual = function(a, b) {
761 return eq(a, b, []);
762 };
763
764 // Is a given array, string, or object empty?
765 // An "empty" object has no enumerable own-properties.
766 _.isEmpty = function(obj) {
767 if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
768 for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
769 return true;
770 };
771
772 // Is a given value a DOM element?
773 _.isElement = function(obj) {
774 return !!(obj && obj.nodeType == 1);
775 };
776
777 // Is a given value an array?
778 // Delegates to ECMA5's native Array.isArray
779 _.isArray = nativeIsArray || function(obj) {
780 return toString.call(obj) == '[object Array]';
781 };
782
783 // Is a given variable an object?
784 _.isObject = function(obj) {
785 return obj === Object(obj);
786 };
787
788 // Is a given variable an arguments object?
789 if (toString.call(arguments) == '[object Arguments]') {
790 _.isArguments = function(obj) {
791 return toString.call(obj) == '[object Arguments]';
792 };
793 } else {
794 _.isArguments = function(obj) {
795 return !!(obj && hasOwnProperty.call(obj, 'callee'));
796 };
797 }
798
799 // Is a given value a function?
800 _.isFunction = function(obj) {
801 return toString.call(obj) == '[object Function]';
802 };
803
804 // Is a given value a string?
805 _.isString = function(obj) {
806 return toString.call(obj) == '[object String]';
807 };
808
809 // Is a given value a number?
810 _.isNumber = function(obj) {
811 return toString.call(obj) == '[object Number]';
812 };
813
814 // Is the given value `NaN`?
815 _.isNaN = function(obj) {
816 // `NaN` is the only value for which `===` is not reflexive.
817 return obj !== obj;
818 };
819
820 // Is a given value a boolean?
821 _.isBoolean = function(obj) {
822 return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
823 };
824
825 // Is a given value a date?
826 _.isDate = function(obj) {
827 return toString.call(obj) == '[object Date]';
828 };
829
830 // Is the given value a regular expression?
831 _.isRegExp = function(obj) {
832 return toString.call(obj) == '[object RegExp]';
833 };
834
835 // Is a given value equal to null?
836 _.isNull = function(obj) {
837 return obj === null;
838 };
839
840 // Is a given variable undefined?
841 _.isUndefined = function(obj) {
842 return obj === void 0;
843 };
844
845 // Utility Functions
846 // -----------------
847
848 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
849 // previous owner. Returns a reference to the Underscore object.
850 _.noConflict = function() {
851 root._ = previousUnderscore;
852 return this;
853 };
854
855 // Keep the identity function around for default iterators.
856 _.identity = function(value) {
857 return value;
858 };
859
860 // Run a function **n** times.
861 _.times = function (n, iterator, context) {
862 for (var i = 0; i < n; i++) iterator.call(context, i);
863 };
864
865 // Escape a string for HTML interpolation.
866 _.escape = function(string) {
867 return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
868 };
869
870 // Add your own custom functions to the Underscore object, ensuring that
871 // they're correctly added to the OOP wrapper as well.
872 _.mixin = function(obj) {
873 each(_.functions(obj), function(name){
874 addToWrapper(name, _[name] = obj[name]);
875 });
876 };
877
878 // Generate a unique integer id (unique within the entire client session).
879 // Useful for temporary DOM ids.
880 var idCounter = 0;
881 _.uniqueId = function(prefix) {
882 var id = idCounter++;
883 return prefix ? prefix + id : id;
884 };
885
886 // By default, Underscore uses ERB-style template delimiters, change the
887 // following template settings to use alternative delimiters.
888 _.templateSettings = {
889 evaluate : /<%([\s\S]+?)%>/g,
890 interpolate : /<%=([\s\S]+?)%>/g,
891 escape : /<%-([\s\S]+?)%>/g
892 };
893
894 // JavaScript micro-templating, similar to John Resig's implementation.
895 // Underscore templating handles arbitrary delimiters, preserves whitespace,
896 // and correctly escapes quotes within interpolated code.
897 _.template = function(str, data) {
898 var c = _.templateSettings;
899 var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
900 'with(obj||{}){__p.push(\'' +
901 str.replace(/\\/g, '\\\\')
902 .replace(/'/g, "\\'")
903 .replace(c.escape, function(match, code) {
904 return "',_.escape(" + code.replace(/\\'/g, "'") + "),'";
905 })
906 .replace(c.interpolate, function(match, code) {
907 return "'," + code.replace(/\\'/g, "'") + ",'";
908 })
909 .replace(c.evaluate || null, function(match, code) {
910 return "');" + code.replace(/\\'/g, "'")
911 .replace(/[\r\n\t]/g, ' ') + ";__p.push('";
912 })
913 .replace(/\r/g, '\\r')
914 .replace(/\n/g, '\\n')
915 .replace(/\t/g, '\\t')
916 + "');}return __p.join('');";
917 var func = new Function('obj', '_', tmpl);
918 return data ? func(data, _) : function(data) { return func(data, _) };
919 };
920
921 // The OOP Wrapper
922 // ---------------
923
924 // If Underscore is called as a function, it returns a wrapped object that
925 // can be used OO-style. This wrapper holds altered versions of all the
926 // underscore functions. Wrapped objects may be chained.
927 var wrapper = function(obj) { this._wrapped = obj; };
928
929 // Expose `wrapper.prototype` as `_.prototype`
930 _.prototype = wrapper.prototype;
931
932 // Helper function to continue chaining intermediate results.
933 var result = function(obj, chain) {
934 return chain ? _(obj).chain() : obj;
935 };
936
937 // A method to easily add functions to the OOP wrapper.
938 var addToWrapper = function(name, func) {
939 wrapper.prototype[name] = function() {
940 var args = slice.call(arguments);
941 unshift.call(args, this._wrapped);
942 return result(func.apply(_, args), this._chain);
943 };
944 };
945
946 // Add all of the Underscore functions to the wrapper object.
947 _.mixin(_);
948
949 // Add all mutator Array functions to the wrapper.
950 each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
951 var method = ArrayProto[name];
952 wrapper.prototype[name] = function() {
953 method.apply(this._wrapped, arguments);
954 return result(this._wrapped, this._chain);
955 };
956 });
957
958 // Add all accessor Array functions to the wrapper.
959 each(['concat', 'join', 'slice'], function(name) {
960 var method = ArrayProto[name];
961 wrapper.prototype[name] = function() {
962 return result(method.apply(this._wrapped, arguments), this._chain);
963 };
964 });
965
966 // Start chaining a wrapped Underscore object.
967 wrapper.prototype.chain = function() {
968 this._chain = true;
969 return this;
970 };
971
972 // Extracts the result from a wrapped and chained object.
973 wrapper.prototype.value = function() {
974 return this._wrapped;
975 };
976
977 }).call(this);