Path: blob/main/test/embind/underscore-1.4.2.js
4150 views
// Underscore.js 1.4.21// http://underscorejs.org2// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.3// Underscore may be freely distributed under the MIT license.45//(function() {67// Baseline setup8// --------------910// Establish the root object, `window` in the browser, or `global` on the server.11var root = this;1213// Save the previous value of the `_` variable.14var previousUnderscore = root._;1516// Establish the object that gets returned to break out of a loop iteration.17var breaker = {};1819// Save bytes in the minified (but not gzipped) version:20var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;2122// Create quick reference variables for speed access to core prototypes.23var push = ArrayProto.push,24slice = ArrayProto.slice,25concat = ArrayProto.concat,26unshift = ArrayProto.unshift,27toString = ObjProto.toString,28hasOwnProperty = ObjProto.hasOwnProperty;2930// All **ECMAScript 5** native function implementations that we hope to use31// are declared here.32var33nativeForEach = ArrayProto.forEach,34nativeMap = ArrayProto.map,35nativeReduce = ArrayProto.reduce,36nativeReduceRight = ArrayProto.reduceRight,37nativeFilter = ArrayProto.filter,38nativeEvery = ArrayProto.every,39nativeSome = ArrayProto.some,40nativeIndexOf = ArrayProto.indexOf,41nativeLastIndexOf = ArrayProto.lastIndexOf,42nativeIsArray = Array.isArray,43nativeKeys = Object.keys,44nativeBind = FuncProto.bind;4546// Create a safe reference to the Underscore object for use below.47var _ = function(obj) {48if (obj instanceof _) return obj;49if (!(this instanceof _)) return new _(obj);50this._wrapped = obj;51};5253// Export the Underscore object for **Node.js**, with54// backwards-compatibility for the old `require()` API. If we're in55// the browser, add `_` as a global object via a string identifier,56// for Closure Compiler "advanced" mode.57if (typeof exports !== 'undefined') {58if (typeof module !== 'undefined' && module.exports) {59exports = module.exports = _;60}61exports._ = _;62} else {63root['_'] = _;64}6566// Current version.67_.VERSION = '1.4.2';6869// Collection Functions70// --------------------7172// The cornerstone, an `each` implementation, aka `forEach`.73// Handles objects with the built-in `forEach`, arrays, and raw objects.74// Delegates to **ECMAScript 5**'s native `forEach` if available.75var each = _.each = _.forEach = function(obj, iterator, context) {76if (obj == null) return;77if (nativeForEach && obj.forEach === nativeForEach) {78obj.forEach(iterator, context);79} else if (obj.length === +obj.length) {80for (var i = 0, l = obj.length; i < l; i++) {81if (iterator.call(context, obj[i], i, obj) === breaker) return;82}83} else {84for (var key in obj) {85if (_.has(obj, key)) {86if (iterator.call(context, obj[key], key, obj) === breaker) return;87}88}89}90};9192// Return the results of applying the iterator to each element.93// Delegates to **ECMAScript 5**'s native `map` if available.94_.map = _.collect = function(obj, iterator, context) {95var results = [];96if (obj == null) return results;97if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);98each(obj, function(value, index, list) {99results[results.length] = iterator.call(context, value, index, list);100});101return results;102};103104// **Reduce** builds up a single result from a list of values, aka `inject`,105// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.106_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {107var initial = arguments.length > 2;108if (obj == null) obj = [];109if (nativeReduce && obj.reduce === nativeReduce) {110if (context) iterator = _.bind(iterator, context);111return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);112}113each(obj, function(value, index, list) {114if (!initial) {115memo = value;116initial = true;117} else {118memo = iterator.call(context, memo, value, index, list);119}120});121if (!initial) throw new TypeError('Reduce of empty array with no initial value');122return memo;123};124125// The right-associative version of reduce, also known as `foldr`.126// Delegates to **ECMAScript 5**'s native `reduceRight` if available.127_.reduceRight = _.foldr = function(obj, iterator, memo, context) {128var initial = arguments.length > 2;129if (obj == null) obj = [];130if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {131if (context) iterator = _.bind(iterator, context);132return arguments.length > 2 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);133}134var length = obj.length;135if (length !== +length) {136var keys = _.keys(obj);137length = keys.length;138}139each(obj, function(value, index, list) {140index = keys ? keys[--length] : --length;141if (!initial) {142memo = obj[index];143initial = true;144} else {145memo = iterator.call(context, memo, obj[index], index, list);146}147});148if (!initial) throw new TypeError('Reduce of empty array with no initial value');149return memo;150};151152// Return the first value which passes a truth test. Aliased as `detect`.153_.find = _.detect = function(obj, iterator, context) {154var result;155any(obj, function(value, index, list) {156if (iterator.call(context, value, index, list)) {157result = value;158return true;159}160});161return result;162};163164// Return all the elements that pass a truth test.165// Delegates to **ECMAScript 5**'s native `filter` if available.166// Aliased as `select`.167_.filter = _.select = function(obj, iterator, context) {168var results = [];169if (obj == null) return results;170if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);171each(obj, function(value, index, list) {172if (iterator.call(context, value, index, list)) results[results.length] = value;173});174return results;175};176177// Return all the elements for which a truth test fails.178_.reject = function(obj, iterator, context) {179var results = [];180if (obj == null) return results;181each(obj, function(value, index, list) {182if (!iterator.call(context, value, index, list)) results[results.length] = value;183});184return results;185};186187// Determine whether all of the elements match a truth test.188// Delegates to **ECMAScript 5**'s native `every` if available.189// Aliased as `all`.190_.every = _.all = function(obj, iterator, context) {191iterator || (iterator = _.identity);192var result = true;193if (obj == null) return result;194if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);195each(obj, function(value, index, list) {196if (!(result = result && iterator.call(context, value, index, list))) return breaker;197});198return !!result;199};200201// Determine if at least one element in the object matches a truth test.202// Delegates to **ECMAScript 5**'s native `some` if available.203// Aliased as `any`.204var any = _.some = _.any = function(obj, iterator, context) {205iterator || (iterator = _.identity);206var result = false;207if (obj == null) return result;208if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);209each(obj, function(value, index, list) {210if (result || (result = iterator.call(context, value, index, list))) return breaker;211});212return !!result;213};214215// Determine if the array or object contains a given value (using `===`).216// Aliased as `include`.217_.contains = _.include = function(obj, target) {218var found = false;219if (obj == null) return found;220if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;221found = any(obj, function(value) {222return value === target;223});224return found;225};226227// Invoke a method (with arguments) on every item in a collection.228_.invoke = function(obj, method) {229var args = slice.call(arguments, 2);230return _.map(obj, function(value) {231return (_.isFunction(method) ? method : value[method]).apply(value, args);232});233};234235// Convenience version of a common use case of `map`: fetching a property.236_.pluck = function(obj, key) {237return _.map(obj, function(value){ return value[key]; });238};239240// Convenience version of a common use case of `filter`: selecting only objects241// with specific `key:value` pairs.242_.where = function(obj, attrs) {243if (_.isEmpty(attrs)) return [];244return _.filter(obj, function(value) {245for (var key in attrs) {246if (attrs[key] !== value[key]) return false;247}248return true;249});250};251252// Return the maximum element or (element-based computation).253// Can't optimize arrays of integers longer than 65,535 elements.254// See: https://bugs.webkit.org/show_bug.cgi?id=80797255_.max = function(obj, iterator, context) {256if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {257return Math.max.apply(Math, obj);258}259if (!iterator && _.isEmpty(obj)) return -Infinity;260var result = {computed : -Infinity};261each(obj, function(value, index, list) {262var computed = iterator ? iterator.call(context, value, index, list) : value;263computed >= result.computed && (result = {value : value, computed : computed});264});265return result.value;266};267268// Return the minimum element (or element-based computation).269_.min = function(obj, iterator, context) {270if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {271return Math.min.apply(Math, obj);272}273if (!iterator && _.isEmpty(obj)) return Infinity;274var result = {computed : Infinity};275each(obj, function(value, index, list) {276var computed = iterator ? iterator.call(context, value, index, list) : value;277computed < result.computed && (result = {value : value, computed : computed});278});279return result.value;280};281282// Shuffle an array.283_.shuffle = function(obj) {284var rand;285var index = 0;286var shuffled = [];287each(obj, function(value) {288rand = _.random(index++);289shuffled[index - 1] = shuffled[rand];290shuffled[rand] = value;291});292return shuffled;293};294295// An internal function to generate lookup iterators.296var lookupIterator = function(value) {297return _.isFunction(value) ? value : function(obj){ return obj[value]; };298};299300// Sort the object's values by a criterion produced by an iterator.301_.sortBy = function(obj, value, context) {302var iterator = lookupIterator(value);303return _.pluck(_.map(obj, function(value, index, list) {304return {305value : value,306index : index,307criteria : iterator.call(context, value, index, list)308};309}).sort(function(left, right) {310var a = left.criteria;311var b = right.criteria;312if (a !== b) {313if (a > b || a === void 0) return 1;314if (a < b || b === void 0) return -1;315}316return left.index < right.index ? -1 : 1;317}), 'value');318};319320// An internal function used for aggregate "group by" operations.321var group = function(obj, value, context, behavior) {322var result = {};323var iterator = lookupIterator(value);324each(obj, function(value, index) {325var key = iterator.call(context, value, index, obj);326behavior(result, key, value);327});328return result;329};330331// Groups the object's values by a criterion. Pass either a string attribute332// to group by, or a function that returns the criterion.333_.groupBy = function(obj, value, context) {334return group(obj, value, context, function(result, key, value) {335(_.has(result, key) ? result[key] : (result[key] = [])).push(value);336});337};338339// Counts instances of an object that group by a certain criterion. Pass340// either a string attribute to count by, or a function that returns the341// criterion.342_.countBy = function(obj, value, context) {343return group(obj, value, context, function(result, key, value) {344if (!_.has(result, key)) result[key] = 0;345result[key]++;346});347};348349// Use a comparator function to figure out the smallest index at which350// an object should be inserted so as to maintain order. Uses binary search.351_.sortedIndex = function(array, obj, iterator, context) {352iterator = iterator == null ? _.identity : lookupIterator(iterator);353var value = iterator.call(context, obj);354var low = 0, high = array.length;355while (low < high) {356var mid = (low + high) >>> 1;357iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;358}359return low;360};361362// Safely convert anything iterable into a real, live array.363_.toArray = function(obj) {364if (!obj) return [];365if (obj.length === +obj.length) return slice.call(obj);366return _.values(obj);367};368369// Return the number of elements in an object.370_.size = function(obj) {371return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;372};373374// Array Functions375// ---------------376377// Get the first element of an array. Passing **n** will return the first N378// values in the array. Aliased as `head` and `take`. The **guard** check379// allows it to work with `_.map`.380_.first = _.head = _.take = function(array, n, guard) {381return (n != null) && !guard ? slice.call(array, 0, n) : array[0];382};383384// Returns everything but the last entry of the array. Especially useful on385// the arguments object. Passing **n** will return all the values in386// the array, excluding the last N. The **guard** check allows it to work with387// `_.map`.388_.initial = function(array, n, guard) {389return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));390};391392// Get the last element of an array. Passing **n** will return the last N393// values in the array. The **guard** check allows it to work with `_.map`.394_.last = function(array, n, guard) {395if ((n != null) && !guard) {396return slice.call(array, Math.max(array.length - n, 0));397} else {398return array[array.length - 1];399}400};401402// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.403// Especially useful on the arguments object. Passing an **n** will return404// the rest N values in the array. The **guard**405// check allows it to work with `_.map`.406_.rest = _.tail = _.drop = function(array, n, guard) {407return slice.call(array, (n == null) || guard ? 1 : n);408};409410// Trim out all falsy values from an array.411_.compact = function(array) {412return _.filter(array, function(value){ return !!value; });413};414415// Internal implementation of a recursive `flatten` function.416var flatten = function(input, shallow, output) {417each(input, function(value) {418if (_.isArray(value)) {419shallow ? push.apply(output, value) : flatten(value, shallow, output);420} else {421output.push(value);422}423});424return output;425};426427// Return a completely flattened version of an array.428_.flatten = function(array, shallow) {429return flatten(array, shallow, []);430};431432// Return a version of the array that does not contain the specified value(s).433_.without = function(array) {434return _.difference(array, slice.call(arguments, 1));435};436437// Produce a duplicate-free version of the array. If the array has already438// been sorted, you have the option of using a faster algorithm.439// Aliased as `unique`.440_.uniq = _.unique = function(array, isSorted, iterator, context) {441var initial = iterator ? _.map(array, iterator, context) : array;442var results = [];443var seen = [];444each(initial, function(value, index) {445if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {446seen.push(value);447results.push(array[index]);448}449});450return results;451};452453// Produce an array that contains the union: each distinct element from all of454// the passed-in arrays.455_.union = function() {456return _.uniq(concat.apply(ArrayProto, arguments));457};458459// Produce an array that contains every item shared between all the460// passed-in arrays.461_.intersection = function(array) {462var rest = slice.call(arguments, 1);463return _.filter(_.uniq(array), function(item) {464return _.every(rest, function(other) {465return _.indexOf(other, item) >= 0;466});467});468};469470// Take the difference between one array and a number of other arrays.471// Only the elements present in just the first array will remain.472_.difference = function(array) {473var rest = concat.apply(ArrayProto, slice.call(arguments, 1));474return _.filter(array, function(value){ return !_.contains(rest, value); });475};476477// Zip together multiple lists into a single array -- elements that share478// an index go together.479_.zip = function() {480var args = slice.call(arguments);481var length = _.max(_.pluck(args, 'length'));482var results = new Array(length);483for (var i = 0; i < length; i++) {484results[i] = _.pluck(args, "" + i);485}486return results;487};488489// Converts lists into objects. Pass either a single array of `[key, value]`490// pairs, or two parallel arrays of the same length -- one of keys, and one of491// the corresponding values.492_.object = function(list, values) {493var result = {};494for (var i = 0, l = list.length; i < l; i++) {495if (values) {496result[list[i]] = values[i];497} else {498result[list[i][0]] = list[i][1];499}500}501return result;502};503504// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),505// we need this function. Return the position of the first occurrence of an506// item in an array, or -1 if the item is not included in the array.507// Delegates to **ECMAScript 5**'s native `indexOf` if available.508// If the array is large and already in sort order, pass `true`509// for **isSorted** to use binary search.510_.indexOf = function(array, item, isSorted) {511if (array == null) return -1;512var i = 0, l = array.length;513if (isSorted) {514if (typeof isSorted == 'number') {515i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);516} else {517i = _.sortedIndex(array, item);518return array[i] === item ? i : -1;519}520}521if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);522for (; i < l; i++) if (array[i] === item) return i;523return -1;524};525526// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.527_.lastIndexOf = function(array, item, from) {528if (array == null) return -1;529var hasIndex = from != null;530if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {531return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);532}533var i = (hasIndex ? from : array.length);534while (i--) if (array[i] === item) return i;535return -1;536};537538// Generate an integer Array containing an arithmetic progression. A port of539// the native Python `range()` function. See540// [the Python documentation](http://docs.python.org/library/functions.html#range).541_.range = function(start, stop, step) {542if (arguments.length <= 1) {543stop = start || 0;544start = 0;545}546step = arguments[2] || 1;547548var len = Math.max(Math.ceil((stop - start) / step), 0);549var idx = 0;550var range = new Array(len);551552while(idx < len) {553range[idx++] = start;554start += step;555}556557return range;558};559560// Function (ahem) Functions561// ------------------562563// Reusable constructor function for prototype setting.564var ctor = function(){};565566// Create a function bound to a given object (assigning `this`, and arguments,567// optionally). Binding with arguments is also known as `curry`.568// Delegates to **ECMAScript 5**'s native `Function.bind` if available.569// We check for `func.bind` first, to fail fast when `func` is undefined.570_.bind = function bind(func, context) {571var bound, args;572if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));573if (!_.isFunction(func)) throw new TypeError;574args = slice.call(arguments, 2);575return bound = function() {576if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));577ctor.prototype = func.prototype;578var self = new ctor;579var result = func.apply(self, args.concat(slice.call(arguments)));580if (Object(result) === result) return result;581return self;582};583};584585// Bind all of an object's methods to that object. Useful for ensuring that586// all callbacks defined on an object belong to it.587_.bindAll = function(obj) {588var funcs = slice.call(arguments, 1);589if (funcs.length == 0) funcs = _.functions(obj);590each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });591return obj;592};593594// Memoize an expensive function by storing its results.595_.memoize = function(func, hasher) {596var memo = {};597hasher || (hasher = _.identity);598return function() {599var key = hasher.apply(this, arguments);600return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));601};602};603604// Delays a function for the given number of milliseconds, and then calls605// it with the arguments supplied.606_.delay = function(func, wait) {607var args = slice.call(arguments, 2);608return setTimeout(function(){ return func.apply(null, args); }, wait);609};610611// Defers a function, scheduling it to run after the current call stack has612// cleared.613_.defer = function(func) {614return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));615};616617// Returns a function, that, when invoked, will only be triggered at most once618// during a given window of time.619_.throttle = function(func, wait) {620var context, args, timeout, throttling, more, result;621var whenDone = _.debounce(function(){ more = throttling = false; }, wait);622return function() {623context = this; args = arguments;624var later = function() {625timeout = null;626if (more) {627result = func.apply(context, args);628}629whenDone();630};631if (!timeout) timeout = setTimeout(later, wait);632if (throttling) {633more = true;634} else {635throttling = true;636result = func.apply(context, args);637}638whenDone();639return result;640};641};642643// Returns a function, that, as long as it continues to be invoked, will not644// be triggered. The function will be called after it stops being called for645// N milliseconds. If `immediate` is passed, trigger the function on the646// leading edge, instead of the trailing.647_.debounce = function(func, wait, immediate) {648var timeout, result;649return function() {650var context = this, args = arguments;651var later = function() {652timeout = null;653if (!immediate) result = func.apply(context, args);654};655var callNow = immediate && !timeout;656clearTimeout(timeout);657timeout = setTimeout(later, wait);658if (callNow) result = func.apply(context, args);659return result;660};661};662663// Returns a function that will be executed at most one time, no matter how664// often you call it. Useful for lazy initialization.665_.once = function(func) {666var ran = false, memo;667return function() {668if (ran) return memo;669ran = true;670memo = func.apply(this, arguments);671func = null;672return memo;673};674};675676// Returns the first function passed as an argument to the second,677// allowing you to adjust arguments, run code before and after, and678// conditionally execute the original function.679_.wrap = function(func, wrapper) {680return function() {681var args = [func];682push.apply(args, arguments);683return wrapper.apply(this, args);684};685};686687// Returns a function that is the composition of a list of functions, each688// consuming the return value of the function that follows.689_.compose = function() {690var funcs = arguments;691return function() {692var args = arguments;693for (var i = funcs.length - 1; i >= 0; i--) {694args = [funcs[i].apply(this, args)];695}696return args[0];697};698};699700// Returns a function that will only be executed after being called N times.701_.after = function(times, func) {702if (times <= 0) return func();703return function() {704if (--times < 1) {705return func.apply(this, arguments);706}707};708};709710// Object Functions711// ----------------712713// Retrieve the names of an object's properties.714// Delegates to **ECMAScript 5**'s native `Object.keys`715_.keys = nativeKeys || function(obj) {716if (obj !== Object(obj)) throw new TypeError('Invalid object');717var keys = [];718for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;719return keys;720};721722// Retrieve the values of an object's properties.723_.values = function(obj) {724var values = [];725for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);726return values;727};728729// Convert an object into a list of `[key, value]` pairs.730_.pairs = function(obj) {731var pairs = [];732for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);733return pairs;734};735736// Invert the keys and values of an object. The values must be serializable.737_.invert = function(obj) {738var result = {};739for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;740return result;741};742743// Return a sorted list of the function names available on the object.744// Aliased as `methods`745_.functions = _.methods = function(obj) {746var names = [];747for (var key in obj) {748if (_.isFunction(obj[key])) names.push(key);749}750return names.sort();751};752753// Extend a given object with all the properties in passed-in object(s).754_.extend = function(obj) {755each(slice.call(arguments, 1), function(source) {756for (var prop in source) {757obj[prop] = source[prop];758}759});760return obj;761};762763// Return a copy of the object only containing the whitelisted properties.764_.pick = function(obj) {765var copy = {};766var keys = concat.apply(ArrayProto, slice.call(arguments, 1));767each(keys, function(key) {768if (key in obj) copy[key] = obj[key];769});770return copy;771};772773// Return a copy of the object without the blacklisted properties.774_.omit = function(obj) {775var copy = {};776var keys = concat.apply(ArrayProto, slice.call(arguments, 1));777for (var key in obj) {778if (!_.contains(keys, key)) copy[key] = obj[key];779}780return copy;781};782783// Fill in a given object with default properties.784_.defaults = function(obj) {785each(slice.call(arguments, 1), function(source) {786for (var prop in source) {787if (obj[prop] == null) obj[prop] = source[prop];788}789});790return obj;791};792793// Create a (shallow-cloned) duplicate of an object.794_.clone = function(obj) {795if (!_.isObject(obj)) return obj;796return _.isArray(obj) ? obj.slice() : _.extend({}, obj);797};798799// Invokes interceptor with the obj, and then returns obj.800// The primary purpose of this method is to "tap into" a method chain, in801// order to perform operations on intermediate results within the chain.802_.tap = function(obj, interceptor) {803interceptor(obj);804return obj;805};806807// Internal recursive comparison function for `isEqual`.808var eq = function(a, b, aStack, bStack) {809// Identical objects are equal. `0 === -0`, but they aren't identical.810// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.811if (a === b) return a !== 0 || 1 / a == 1 / b;812// A strict comparison is necessary because `null == undefined`.813if (a == null || b == null) return a === b;814// Unwrap any wrapped objects.815if (a instanceof _) a = a._wrapped;816if (b instanceof _) b = b._wrapped;817// Compare `[[Class]]` names.818var className = toString.call(a);819if (className != toString.call(b)) return false;820switch (className) {821// Strings, numbers, dates, and booleans are compared by value.822case '[object String]':823// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is824// equivalent to `new String("5")`.825return a == String(b);826case '[object Number]':827// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for828// other numeric values.829return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);830case '[object Date]':831case '[object Boolean]':832// Coerce dates and booleans to numeric primitive values. Dates are compared by their833// millisecond representations. Note that invalid dates with millisecond representations834// of `NaN` are not equivalent.835return +a == +b;836// RegExps are compared by their source patterns and flags.837case '[object RegExp]':838return a.source == b.source &&839a.global == b.global &&840a.multiline == b.multiline &&841a.ignoreCase == b.ignoreCase;842}843if (typeof a != 'object' || typeof b != 'object') return false;844// Assume equality for cyclic structures. The algorithm for detecting cyclic845// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.846var length = aStack.length;847while (length--) {848// Linear search. Performance is inversely proportional to the number of849// unique nested structures.850if (aStack[length] == a) return bStack[length] == b;851}852// Add the first object to the stack of traversed objects.853aStack.push(a);854bStack.push(b);855var size = 0, result = true;856// Recursively compare objects and arrays.857if (className == '[object Array]') {858// Compare array lengths to determine if a deep comparison is necessary.859size = a.length;860result = size == b.length;861if (result) {862// Deep compare the contents, ignoring non-numeric properties.863while (size--) {864if (!(result = eq(a[size], b[size], aStack, bStack))) break;865}866}867} else {868// Objects with different constructors are not equivalent, but `Object`s869// from different frames are.870var aCtor = a.constructor, bCtor = b.constructor;871if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&872_.isFunction(bCtor) && (bCtor instanceof bCtor))) {873return false;874}875// Deep compare objects.876for (var key in a) {877if (_.has(a, key)) {878// Count the expected number of properties.879size++;880// Deep compare each member.881if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;882}883}884// Ensure that both objects contain the same number of properties.885if (result) {886for (key in b) {887if (_.has(b, key) && !(size--)) break;888}889result = !size;890}891}892// Remove the first object from the stack of traversed objects.893aStack.pop();894bStack.pop();895return result;896};897898// Perform a deep comparison to check if two objects are equal.899_.isEqual = function(a, b) {900return eq(a, b, [], []);901};902903// Is a given array, string, or object empty?904// An "empty" object has no enumerable own-properties.905_.isEmpty = function(obj) {906if (obj == null) return true;907if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;908for (var key in obj) if (_.has(obj, key)) return false;909return true;910};911912// Is a given value a DOM element?913_.isElement = function(obj) {914return !!(obj && obj.nodeType === 1);915};916917// Is a given value an array?918// Delegates to ECMA5's native Array.isArray919_.isArray = nativeIsArray || function(obj) {920return toString.call(obj) == '[object Array]';921};922923// Is a given variable an object?924_.isObject = function(obj) {925return obj === Object(obj);926};927928// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.929each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {930_['is' + name] = function(obj) {931return toString.call(obj) == '[object ' + name + ']';932};933});934935// Define a fallback version of the method in browsers (ahem, IE), where936// there isn't any inspectable "Arguments" type.937if (!_.isArguments(arguments)) {938_.isArguments = function(obj) {939return !!(obj && _.has(obj, 'callee'));940};941}942943// Optimize `isFunction` if appropriate.944if (typeof (/./) !== 'function') {945_.isFunction = function(obj) {946return typeof obj === 'function';947};948}949950// Is a given object a finite number?951_.isFinite = function(obj) {952return _.isNumber(obj) && isFinite(obj);953};954955// Is the given value `NaN`? (NaN is the only number which does not equal itself).956_.isNaN = function(obj) {957return _.isNumber(obj) && obj != +obj;958};959960// Is a given value a boolean?961_.isBoolean = function(obj) {962return obj === true || obj === false || toString.call(obj) == '[object Boolean]';963};964965// Is a given value equal to null?966_.isNull = function(obj) {967return obj === null;968};969970// Is a given variable undefined?971_.isUndefined = function(obj) {972return obj === void 0;973};974975// Shortcut function for checking if an object has a given property directly976// on itself (in other words, not on a prototype).977_.has = function(obj, key) {978return hasOwnProperty.call(obj, key);979};980981// Utility Functions982// -----------------983984// Run Underscore.js in *noConflict* mode, returning the `_` variable to its985// previous owner. Returns a reference to the Underscore object.986_.noConflict = function() {987root._ = previousUnderscore;988return this;989};990991// Keep the identity function around for default iterators.992_.identity = function(value) {993return value;994};995996// Run a function **n** times.997_.times = function(n, iterator, context) {998for (var i = 0; i < n; i++) iterator.call(context, i);999};10001001// Return a random integer between min and max (inclusive).1002_.random = function(min, max) {1003if (max == null) {1004max = min;1005min = 0;1006}1007return min + (0 | Math.random() * (max - min + 1));1008};10091010// List of HTML entities for escaping.1011var entityMap = {1012escape: {1013'&': '&',1014'<': '<',1015'>': '>',1016'"': '"',1017"'": ''',1018'/': '/'1019}1020};1021entityMap.unescape = _.invert(entityMap.escape);10221023// Regexes containing the keys and values listed immediately above.1024var entityRegexes = {1025escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),1026unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')1027};10281029// Functions for escaping and unescaping strings to/from HTML interpolation.1030_.each(['escape', 'unescape'], function(method) {1031_[method] = function(string) {1032if (string == null) return '';1033return ('' + string).replace(entityRegexes[method], function(match) {1034return entityMap[method][match];1035});1036};1037});10381039// If the value of the named property is a function then invoke it;1040// otherwise, return it.1041_.result = function(object, property) {1042if (object == null) return null;1043var value = object[property];1044return _.isFunction(value) ? value.call(object) : value;1045};10461047// Add your own custom functions to the Underscore object.1048_.mixin = function(obj) {1049each(_.functions(obj), function(name){1050var func = _[name] = obj[name];1051_.prototype[name] = function() {1052var args = [this._wrapped];1053push.apply(args, arguments);1054return result.call(this, func.apply(_, args));1055};1056});1057};10581059// Generate a unique integer id (unique within the entire client session).1060// Useful for temporary DOM ids.1061var idCounter = 0;1062_.uniqueId = function(prefix) {1063var id = idCounter++;1064return prefix ? prefix + id : id;1065};10661067// By default, Underscore uses ERB-style template delimiters, change the1068// following template settings to use alternative delimiters.1069_.templateSettings = {1070evaluate : /<%([\s\S]+?)%>/g,1071interpolate : /<%=([\s\S]+?)%>/g,1072escape : /<%-([\s\S]+?)%>/g1073};10741075// When customizing `templateSettings`, if you don't want to define an1076// interpolation, evaluation or escaping regex, we need one that is1077// guaranteed not to match.1078var noMatch = /(.)^/;10791080// Certain characters need to be escaped so that they can be put into a1081// string literal.1082var escapes = {1083"'": "'",1084'\\': '\\',1085'\r': 'r',1086'\n': 'n',1087'\t': 't',1088'\u2028': 'u2028',1089'\u2029': 'u2029'1090};10911092var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;10931094// JavaScript micro-templating, similar to John Resig's implementation.1095// Underscore templating handles arbitrary delimiters, preserves whitespace,1096// and correctly escapes quotes within interpolated code.1097_.template = function(text, data, settings) {1098settings = _.defaults({}, settings, _.templateSettings);10991100// Combine delimiters into one regular expression via alternation.1101var matcher = new RegExp([1102(settings.escape || noMatch).source,1103(settings.interpolate || noMatch).source,1104(settings.evaluate || noMatch).source1105].join('|') + '|$', 'g');11061107// Compile the template source, escaping string literals appropriately.1108var index = 0;1109var source = "__p+='";1110text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {1111source += text.slice(index, offset)1112.replace(escaper, function(match) { return '\\' + escapes[match]; });1113source +=1114escape ? "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'" :1115interpolate ? "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'" :1116evaluate ? "';\n" + evaluate + "\n__p+='" : '';1117index = offset + match.length;1118});1119source += "';\n";11201121// If a variable is not specified, place data values in local scope.1122if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';11231124source = "var __t,__p='',__j=Array.prototype.join," +1125"print=function(){__p+=__j.call(arguments,'');};\n" +1126source + "return __p;\n";11271128try {1129var render = new Function(settings.variable || 'obj', '_', source);1130} catch (e) {1131e.source = source;1132throw e;1133}11341135if (data) return render(data, _);1136var template = function(data) {1137return render.call(this, data, _);1138};11391140// Provide the compiled function source as a convenience for precompilation.1141template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';11421143return template;1144};11451146// Add a "chain" function, which will delegate to the wrapper.1147_.chain = function(obj) {1148return _(obj).chain();1149};11501151// OOP1152// ---------------1153// If Underscore is called as a function, it returns a wrapped object that1154// can be used OO-style. This wrapper holds altered versions of all the1155// underscore functions. Wrapped objects may be chained.11561157// Helper function to continue chaining intermediate results.1158var result = function(obj) {1159return this._chain ? _(obj).chain() : obj;1160};11611162// Add all of the Underscore functions to the wrapper object.1163_.mixin(_);11641165// Add all mutator Array functions to the wrapper.1166each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {1167var method = ArrayProto[name];1168_.prototype[name] = function() {1169var obj = this._wrapped;1170method.apply(obj, arguments);1171if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];1172return result.call(this, obj);1173};1174});11751176// Add all accessor Array functions to the wrapper.1177each(['concat', 'join', 'slice'], function(name) {1178var method = ArrayProto[name];1179_.prototype[name] = function() {1180return result.call(this, method.apply(this._wrapped, arguments));1181};1182});11831184_.extend(_.prototype, {11851186// Start chaining a wrapped Underscore object.1187chain: function() {1188this._chain = true;1189return this;1190},11911192// Extracts the result from a wrapped and chained object.1193value: function() {1194return this._wrapped;1195}11961197});11981199//}).call(this);120012011202