Skip to content
Browse files

Merge pull request #3 from tonic20/master

Update Underscore.js
  • Loading branch information...
2 parents 38a61bc + a82b8ec commit 46dd70d9d8e0daa4b311a767af1631e5cff9cf04 @rweng committed Nov 25, 2011
Showing with 140 additions and 94 deletions.
  1. +1 −1 lib/underscore-rails/version.rb
  2. +139 −93 vendor/assets/javascripts/underscore.js
View
2 lib/underscore-rails/version.rb
@@ -1,5 +1,5 @@
module Underscore
module Rails
- VERSION = "1.2.0"
+ VERSION = "1.2.2"
end
end
View
232 vendor/assets/javascripts/underscore.js
@@ -1,4 +1,4 @@
-// Underscore.js 1.2.0
+// Underscore.js 1.2.2
// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
@@ -48,19 +48,26 @@
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
- // Export the Underscore object for **CommonJS**, with backwards-compatibility
- // for the old `require()` API. If we're not in CommonJS, add `_` to the
- // global object.
- if (typeof module !== 'undefined' && module.exports) {
- module.exports = _;
- _._ = _;
+ // Export the Underscore object for **Node.js** and **"CommonJS"**, with
+ // backwards-compatibility for the old `require()` API. If we're not in
+ // CommonJS, add `_` to the global object.
+ if (typeof exports !== 'undefined') {
+ if (typeof module !== 'undefined' && module.exports) {
+ exports = module.exports = _;
+ }
+ exports._ = _;
+ } else if (typeof define === 'function' && define.amd) {
+ // Register as a named module with AMD.
+ define('underscore', function() {
+ return _;
+ });
} else {
// Exported as a string, for Closure Compiler "advanced" mode.
root['_'] = _;
}
// Current version.
- _.VERSION = '1.2.0';
+ _.VERSION = '1.2.2';
// Collection Functions
// --------------------
@@ -187,7 +194,7 @@
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
- if (result |= iterator.call(context, value, index, list)) return breaker;
+ if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
@@ -198,8 +205,8 @@
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
- any(obj, function(value) {
- if (found = value === target) return true;
+ found = any(obj, function(value) {
+ return value === target;
});
return found;
};
@@ -269,9 +276,11 @@
}), 'value');
};
- // Groups the object's values by a criterion produced by an iterator
- _.groupBy = function(obj, iterator) {
+ // Groups the object's values by a criterion. Pass either a string attribute
+ // to group by, or a function that returns the criterion.
+ _.groupBy = function(obj, val) {
var result = {};
+ var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
@@ -326,7 +335,11 @@
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
- return (n != null) && !guard ? slice.call(array, array.length - n) : array[array.length - 1];
+ if ((n != null) && !guard) {
+ return slice.call(array, Math.max(array.length - n, 0));
+ } else {
+ return array[array.length - 1];
+ }
};
// Returns everything but the first entry of the array. Aliased as `tail`.
@@ -343,9 +356,9 @@
};
// Return a completely flattened version of an array.
- _.flatten = function(array) {
+ _.flatten = function(array, shallow) {
return _.reduce(array, function(memo, value) {
- if (_.isArray(value)) return memo.concat(_.flatten(value));
+ if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
@@ -375,7 +388,7 @@
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
- return _.uniq(_.flatten(arguments));
+ return _.uniq(_.flatten(arguments, true));
};
// Produce an array that contains every item shared between all the
@@ -457,15 +470,25 @@
// Function (ahem) Functions
// ------------------
+ // Reusable constructor function for prototype setting.
+ var ctor = function(){};
+
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
- _.bind = function(func, obj) {
+ _.bind = function bind(func, context) {
+ var bound, args;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
- var args = slice.call(arguments, 2);
- return function() {
- return func.apply(obj, args.concat(slice.call(arguments)));
+ if (!_.isFunction(func)) throw new TypeError;
+ args = slice.call(arguments, 2);
+ return bound = function() {
+ if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
+ ctor.prototype = func.prototype;
+ var self = new ctor;
+ var result = func.apply(self, args.concat(slice.call(arguments)));
+ if (Object(result) === result) return result;
+ return self;
};
};
@@ -501,31 +524,43 @@
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
- // Internal function used to implement `_.throttle` and `_.debounce`.
- var limit = function(func, wait, debounce) {
- var timeout;
+ // Returns a function, that, when invoked, will only be triggered at most once
+ // during a given window of time.
+ _.throttle = function(func, wait) {
+ var context, args, timeout, throttling, more;
+ var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
return function() {
- var context = this, args = arguments;
- var throttler = function() {
+ context = this; args = arguments;
+ var later = function() {
timeout = null;
- func.apply(context, args);
+ if (more) func.apply(context, args);
+ whenDone();
};
- if (debounce) clearTimeout(timeout);
- if (debounce || !timeout) timeout = setTimeout(throttler, wait);
+ if (!timeout) timeout = setTimeout(later, wait);
+ if (throttling) {
+ more = true;
+ } else {
+ func.apply(context, args);
+ }
+ whenDone();
+ throttling = true;
};
};
- // Returns a function, that, when invoked, will only be triggered at most once
- // during a given window of time.
- _.throttle = function(func, wait) {
- return limit(func, wait, false);
- };
-
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
_.debounce = function(func, wait) {
- return limit(func, wait, true);
+ var timeout;
+ return function() {
+ var context = this, args = arguments;
+ var later = function() {
+ timeout = null;
+ func.apply(context, args);
+ };
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ };
};
// Returns a function that will be executed at most one time, no matter how
@@ -564,6 +599,7 @@
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
+ if (times <= 0) return func();
return function() {
if (--times < 1) { return func.apply(this, arguments); }
};
@@ -618,6 +654,7 @@
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
+ if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
@@ -635,66 +672,68 @@
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
- if (a == null) return a === b;
- // Compare object types.
- var typeA = typeof a;
- if (typeA != typeof b) return false;
- // Optimization; ensure that both values are truthy or falsy.
- if (!a != !b) return false;
- // `NaN` values are equal.
- if (_.isNaN(a)) return _.isNaN(b);
- // Compare string objects by value.
- var isStringA = _.isString(a), isStringB = _.isString(b);
- if (isStringA || isStringB) return isStringA && isStringB && String(a) == String(b);
- // Compare number objects by value.
- var isNumberA = _.isNumber(a), isNumberB = _.isNumber(b);
- if (isNumberA || isNumberB) return isNumberA && isNumberB && +a == +b;
- // Compare boolean objects by value. The value of `true` is 1; the value of `false` is 0.
- var isBooleanA = _.isBoolean(a), isBooleanB = _.isBoolean(b);
- if (isBooleanA || isBooleanB) return isBooleanA && isBooleanB && +a == +b;
- // Compare dates by their millisecond values.
- var isDateA = _.isDate(a), isDateB = _.isDate(b);
- if (isDateA || isDateB) return isDateA && isDateB && a.getTime() == b.getTime();
- // Compare RegExps by their source patterns and flags.
- var isRegExpA = _.isRegExp(a), isRegExpB = _.isRegExp(b);
- if (isRegExpA || isRegExpB) {
- // Ensure commutative equality for RegExps.
- return isRegExpA && isRegExpB &&
- a.source == b.source &&
- a.global == b.global &&
- a.multiline == b.multiline &&
- a.ignoreCase == b.ignoreCase;
- }
- // Ensure that both values are objects.
- if (typeA != 'object') return false;
+ if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
// Invoke a custom `isEqual` method if one is provided.
if (_.isFunction(a.isEqual)) return a.isEqual(b);
- // Assume equality for cyclic structures. The algorithm for detecting cyclic structures is
- // adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
+ if (_.isFunction(b.isEqual)) return b.isEqual(a);
+ // Compare `[[Class]]` names.
+ var className = toString.call(a);
+ if (className != toString.call(b)) return false;
+ switch (className) {
+ // Strings, numbers, dates, and booleans are compared by value.
+ case '[object String]':
+ // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
+ // equivalent to `new String("5")`.
+ return String(a) == String(b);
+ case '[object Number]':
+ a = +a;
+ b = +b;
+ // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
+ // other numeric values.
+ return a != a ? b != b : (a == 0 ? 1 / a == 1 / b : a == b);
+ case '[object Date]':
+ case '[object Boolean]':
+ // Coerce dates and booleans to numeric primitive values. Dates are compared by their
+ // millisecond representations. Note that invalid dates with millisecond representations
+ // of `NaN` are not equivalent.
+ return +a == +b;
+ // RegExps are compared by their source patterns and flags.
+ case '[object RegExp]':
+ return a.source == b.source &&
+ a.global == b.global &&
+ a.multiline == b.multiline &&
+ a.ignoreCase == b.ignoreCase;
+ }
+ if (typeof a != 'object' || typeof b != 'object') return false;
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = stack.length;
while (length--) {
- // Linear search. Performance is inversely proportional to the number of unique nested
- // structures.
+ // Linear search. Performance is inversely proportional to the number of
+ // unique nested structures.
if (stack[length] == a) return true;
}
// Add the first object to the stack of traversed objects.
stack.push(a);
var size = 0, result = true;
- if (a.length === +a.length || b.length === +b.length) {
- // Compare object lengths to determine if a deep comparison is necessary.
+ // Recursively compare objects and arrays.
+ if (className == '[object Array]') {
+ // Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
- // Deep compare array-like object contents, ignoring non-numeric properties.
+ // Deep compare the contents, ignoring non-numeric properties.
while (size--) {
// Ensure commutative equality for sparse arrays.
if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
}
}
} else {
+ // Objects with different constructors are not equivalent.
+ if ("constructor" in a != "constructor" in b || a.constructor != b.constructor) return false;
// Deep compare objects.
for (var key in a) {
if (hasOwnProperty.call(a, key)) {
@@ -707,7 +746,7 @@
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
- if (hasOwnProperty.call(b, key) && !size--) break;
+ if (hasOwnProperty.call(b, key) && !(size--)) break;
}
result = !size;
}
@@ -722,7 +761,8 @@
return eq(a, b, []);
};
- // Is a given array or object empty?
+ // Is a given array, string, or object empty?
+ // An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
@@ -737,7 +777,7 @@
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
- return toString.call(obj) === '[object Array]';
+ return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
@@ -746,28 +786,34 @@
};
// Is a given variable an arguments object?
- _.isArguments = function(obj) {
- return !!(obj && hasOwnProperty.call(obj, 'callee'));
- };
+ if (toString.call(arguments) == '[object Arguments]') {
+ _.isArguments = function(obj) {
+ return toString.call(obj) == '[object Arguments]';
+ };
+ } else {
+ _.isArguments = function(obj) {
+ return !!(obj && hasOwnProperty.call(obj, 'callee'));
+ };
+ }
// Is a given value a function?
_.isFunction = function(obj) {
- return !!(obj && obj.constructor && obj.call && obj.apply);
+ return toString.call(obj) == '[object Function]';
};
// Is a given value a string?
_.isString = function(obj) {
- return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
+ return toString.call(obj) == '[object String]';
};
// Is a given value a number?
_.isNumber = function(obj) {
- return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
+ return toString.call(obj) == '[object Number]';
};
- // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
- // that does not equal itself.
+ // Is the given value `NaN`?
_.isNaN = function(obj) {
+ // `NaN` is the only value for which `===` is not reflexive.
return obj !== obj;
};
@@ -778,12 +824,12 @@
// Is a given value a date?
_.isDate = function(obj) {
- return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
+ return toString.call(obj) == '[object Date]';
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
- return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
+ return toString.call(obj) == '[object RegExp]';
};
// Is a given value equal to null?
@@ -818,7 +864,7 @@
// Escape a string for HTML interpolation.
_.escape = function(string) {
- return (''+string).replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
+ return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
};
// Add your own custom functions to the Underscore object, ensuring that
@@ -862,14 +908,14 @@
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
- .replace(/[\r\n\t]/g, ' ') + "__p.push('";
+ .replace(/[\r\n\t]/g, ' ') + ";__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
- var func = new Function('obj', tmpl);
- return data ? func(data) : func;
+ var func = new Function('obj', '_', tmpl);
+ return data ? func(data, _) : function(data) { return func(data, _) };
};
// The OOP Wrapper
@@ -928,4 +974,4 @@
return this._wrapped;
};
-})();
+}).call(this);

0 comments on commit 46dd70d

Please sign in to comment.
Something went wrong with that request. Please try again.