Underscore.js 1.2.0
(c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
Underscore is freely distributable under the MIT license.
Portions of Underscore are inspired or borrowed from Prototype,
@@ -27,7 +27,7 @@
module.exports=_;_._=_;}else{
The cornerstone, an each implementation, aka forEach.
Handles objects with the built-in forEach, arrays, and raw objects.
Delegates to ECMAScript 5's native forEach if available.
Get the first element of an array. Passing n will return the first N
values in the array. Aliased as head. The guard check allows it to work
with _.map.
Returns everything but the last entry of the array. Especcialy useful on
+the arguments object. Passing n will return all the values in
+the array, excluding the last N. The guard check allows it to work with
+_.map.
Returns everything but the first entry of the array. Aliased as tail.
Especially useful on the arguments object. Passing an index will return
the rest of the values in the array from that index onward. The guard
check allows it to work with _.map.
Produce a duplicate-free version of the array. If the array has already
been sorted, you have the option of using a faster algorithm.
-Aliased as unique.
_.uniq=_.unique=function(array,isSorted){
- return_.reduce(array,function(memo,el,i){
- if(0==i||(isSorted===true?_.last(memo)!=el:!_.include(memo,el)))memo[memo.length]=el;
+Aliased as unique.
If the browser doesn't supply us with indexOf (I'm looking at you, MSIE),
we need this function. Return the position of the first occurrence of an
item in an array, or -1 if the item is not included in the array.
Delegates to ECMAScript 5's native indexOf if available.
@@ -257,13 +283,13 @@
if(nativeIndexOf&&array.indexOf===nativeIndexOf)returnarray.indexOf(item);for(i=0,l=array.length;i<l;i++)if(array[i]===item)returni;return-1;
- };
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.
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.
Returns the first function passed as an argument to the second,
allowing you to adjust arguments, run code before and after, and
conditionally execute the original function.
Invokes interceptor with the obj, and then returns obj.
The primary purpose of this method is to "tap into" a method chain, in
order to perform operations on intermediate results within the chain.
JavaScript micro-templating, similar to John Resig's implementation.
Underscore templating handles arbitrary delimiters, preserves whitespace,
and correctly escapes quotes within interpolated code.
If Underscore is called as a function, it returns a wrapped object that
can be used OO-style. This wrapper holds altered versions of all the
-underscore functions. Wrapped objects may be chained.
+ initial_.initial(array, [n])
- Returns the rest of the elements in an array. Pass an index
- to return the values of the array from that index onward.
+ Returns everything but the last entry of the array. Especially useful on
+ the arguments object. Pass n to exclude the last n elements
+ from the result.
- last_.last(array)
+ last_.last(array, [n])
- Returns the last element of an array.
+ Returns the last element of an array. Passing n will return
+ the last n elements of the array.
_.last([5, 4, 3, 2, 1]);
=> 1
+
+
+
+ rest_.rest(array, [index])
+ Alias: tail
+
+ Returns the rest of the elements in an array. Pass an index
+ to return the values of the array from that index onward.
+
+
+_.rest([5, 4, 3, 2, 1]);
+=> [4, 3, 2, 1]
@@ -592,12 +625,14 @@
Array Functions
- uniq_.uniq(array, [isSorted])
+ uniq_.uniq(array, [isSorted], [iterator])Alias: unique
Produces a duplicate-free version of the array, using === to test
object equality. If you know in advance that the array is sorted,
passing true for isSorted will run a much faster algorithm.
+ If you want to compute unique items based on a transformation, pass an
+ iterator function.
_.uniq([1, 2, 1, 3, 1, 4]);
@@ -1149,7 +1184,8 @@
Utility Functions
for rendering. Useful for rendering complicated bits of HTML from JSON
data sources. Template functions can both interpolate variables, using <%= … %>, as well as execute arbitrary JavaScript code, with
- <% … %>. When you evaluate a template function, pass in a
+ <% … %>. If you wish to interpolate a value, and have
+ it be HTML-escaped, use <%- … %> When you evaluate a template function, pass in a
context object that has properties corresponding to the template's free
variables. If you're writing a one-off, you can pass the context
object as the second parameter to template in order to render
@@ -1162,7 +1198,11 @@
Utility Functions
var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
_.template(list, {people : ['moe', 'curly', 'larry']});
-=> "<li>moe</li><li>curly</li><li>larry</li>"
You can also use print from within JavaScript code. This is
@@ -1235,6 +1275,13 @@
Duck Typing
another type, if you're setting properties with names like "concat" and
"charCodeAt". So be aware.
+
+
+ In a similar fashion, _.each and all of the other functions
+ based on it are designed to be able to iterate over any Array-like
+ JavaScript object, including arguments, NodeLists, and more.
+ Passing hash-like objects with a numeric length key won't work.
+
Links & Suggested Reading
@@ -1247,6 +1294,21 @@
Links & Suggested Reading
available on GitHub.
+
+ Underscore.php,
+ a PHP port of the functions that are applicable in both languages.
+ Includes OOP-wrapping and chaining.
+ The source is
+ available on GitHub.
+
+
+
+ Underscore-perl,
+ a Perl port of many of the Underscore.js functions,
+ aimed at on Perl hashes and arrays, also
+ available on GitHub.
+
+
Underscore.string,
an Underscore extension that adds functions for string-manipulation:
@@ -1280,10 +1342,38 @@
Links & Suggested Reading
Change Log
+
+ 1.2.0 — Oct. 5, 2011
+
+
+ Underscore templates now support HTML escaping interpolations, using
+ <%- ... %> syntax. The _.isEqual function now
+ supports true deep equality comparisons, with checks for cyclic structures,
+ thanks to Kit Cambridge.
+
+
+ Ryan Tenney contributed _.shuffle, which uses a modified
+ Fisher-Yates to give you a shuffled copy of an array.
+
+
+ _.uniq can now be passed an optional iterator, to determine by
+ what criteria an object should be considered unique.
+
+
+ _.last now takes an optional argument which will return the last
+ N elements of the list.
+
+
+ A new _.initial function was added, as a mirror of _.rest,
+ which returns all the initial values of a list (except the last N).
+
+
+
+
1.1.7 — July 13, 2011
Added _.groupBy, which aggregates a collection into groups of like items.
- Added _.untion and _.difference, to complement the
+ Added _.union and _.difference, to complement the
(re-named) _.intersection.
Various improvements for support of sparse arrays.
_.toArray now returns a clone, if directly passed an array.
diff --git a/package.json b/package.json
index 08396c4d9..eb4eee826 100644
--- a/package.json
+++ b/package.json
@@ -8,5 +8,5 @@
"dependencies" : [],
"repository" : {"type": "git", "url": "git://github.com/documentcloud/underscore.git"},
"main" : "underscore.js",
- "version" : "1.1.7"
+ "version" : "1.2.0"
}
diff --git a/test/arrays.js b/test/arrays.js
index 32dd73a55..80da71f6f 100644
--- a/test/arrays.js
+++ b/test/arrays.js
@@ -1,6 +1,6 @@
$(document).ready(function() {
- module("Array-only functions (last, compact, uniq, and so on...)");
+ module("Arrays");
test("arrays: first", function() {
equals(_.first([1,2,3]), 1, 'can pull out the first element of an array');
@@ -24,10 +24,23 @@ $(document).ready(function() {
equals(_.flatten(result).join(','), '2,3,2,3', 'works well with _.map');
});
+ test("arrays: initial", function() {
+ equals(_.initial([1,2,3,4,5]).join(", "), "1, 2, 3, 4", 'working initial()');
+ equals(_.initial([1,2,3,4],2).join(", "), "1, 2", 'initial can take an index');
+ var result = (function(){ return _(arguments).initial(); })(1, 2, 3, 4);
+ equals(result.join(", "), "1, 2, 3", 'initial works on arguments object');
+ result = _.map([[1,2,3],[1,2,3]], _.initial);
+ equals(_.flatten(result).join(','), '1,2,1,2', 'initial works with _.map');
+ });
+
test("arrays: last", function() {
equals(_.last([1,2,3]), 3, 'can pull out the last element of an array');
+ equals(_.last([1,2,3], 0).join(', '), "", 'can pass an index to last');
+ equals(_.last([1,2,3], 2).join(', '), '2, 3', 'can pass an index to last');
var result = (function(){ return _(arguments).last(); })(1, 2, 3, 4);
equals(result, 4, 'works on an arguments object');
+ result = _.map([[1,2,3],[1,2,3]], _.last);
+ equals(result.join(','), '3,3', 'works well with _.map');
});
test("arrays: compact", function() {
@@ -61,6 +74,14 @@ $(document).ready(function() {
var list = [1, 1, 1, 2, 2, 3];
equals(_.uniq(list, true).join(', '), '1, 2, 3', 'can find the unique values of a sorted array faster');
+ var list = [{name:'moe'}, {name:'curly'}, {name:'larry'}, {name:'curly'}];
+ var iterator = function(value) { return value.name; };
+ equals(_.map(_.uniq(list, false, iterator), iterator).join(', '), 'moe, curly, larry', 'can find the unique values of an array using a custom iterator');
+
+ var iterator = function(value) { return value +1; };
+ var list = [1, 2, 2, 3, 4, 4];
+ equals(_.uniq(list, true, iterator).join(', '), '1, 2, 3, 4', 'iterator works with sorted array');
+
var result = (function(){ return _.uniq(arguments); })(1, 2, 1, 3, 1, 4);
equals(result.join(', '), '1, 2, 3, 4', 'works on an arguments object');
});
diff --git a/test/chaining.js b/test/chaining.js
index e633ba5ad..64b0500ef 100644
--- a/test/chaining.js
+++ b/test/chaining.js
@@ -1,6 +1,6 @@
$(document).ready(function() {
- module("Underscore chaining.");
+ module("Chaining");
test("chaining: map/flatten/reduce", function() {
var lyrics = [
diff --git a/test/collections.js b/test/collections.js
index 005ee169e..cf1c815d6 100644
--- a/test/collections.js
+++ b/test/collections.js
@@ -1,6 +1,6 @@
$(document).ready(function() {
- module("Collection functions (each, any, select, and so on...)");
+ module("Collections");
test("collections: each", function() {
_.each([1, 2, 3], function(num, i) {
@@ -177,6 +177,9 @@ $(document).ready(function() {
var neg = _.max([1, 2, 3], function(num){ return -num; });
equals(neg, 1, 'can perform a computation-based max');
+
+ equals(-Infinity, _.max({}), 'Maximum value of an empty object');
+ equals(-Infinity, _.max([]), 'Maximum value of an empty array');
});
test('collections: min', function() {
@@ -184,6 +187,9 @@ $(document).ready(function() {
var neg = _.min([1, 2, 3], function(num){ return -num; });
equals(neg, 3, 'can perform a computation-based min');
+
+ equals(Infinity, _.min({}), 'Minimum value of an empty object');
+ equals(Infinity, _.min([]), 'Minimum value of an empty array');
});
test('collections: sortBy', function() {
@@ -204,6 +210,13 @@ $(document).ready(function() {
equals(index, 3, '35 should be inserted at index 3');
});
+ test('collections: shuffle', function() {
+ var numbers = _.range(10);
+ var shuffled = _.shuffle(numbers).sort();
+ notStrictEqual(numbers, shuffled, 'original object is unmodified');
+ equals(shuffled.join(','), numbers.join(','), 'contains the same members before and after shuffle');
+ });
+
test('collections: toArray', function() {
ok(!_.isArray(arguments), 'arguments object is not an array');
ok(_.isArray(_.toArray(arguments)), 'arguments object converted into array');
diff --git a/test/functions.js b/test/functions.js
index 2a1bd51bd..af35e5eff 100644
--- a/test/functions.js
+++ b/test/functions.js
@@ -1,6 +1,6 @@
$(document).ready(function() {
- module("Function functions (bind, bindAll, and so on...)");
+ module("Functions");
test("functions: bind", function() {
var context = {name : 'moe'};
diff --git a/test/objects.js b/test/objects.js
index 78add1fed..e05c0ddc5 100644
--- a/test/objects.js
+++ b/test/objects.js
@@ -1,6 +1,6 @@
$(document).ready(function() {
- module("Object functions (values, extend, isEqual, and so on...)");
+ module("Objects");
test("objects: keys", function() {
var exception = /object/;
@@ -69,23 +69,232 @@ $(document).ready(function() {
});
test("objects: isEqual", function() {
- var moe = {name : 'moe', lucky : [13, 27, 34]};
- var clone = {name : 'moe', lucky : [13, 27, 34]};
- ok(moe != clone, 'basic equality between objects is false');
- ok(_.isEqual(moe, clone), 'deep equality is true');
- ok(_(moe).isEqual(clone), 'OO-style deep equality works');
- ok(!_.isEqual(5, NaN), '5 is not equal to NaN');
- ok(NaN != NaN, 'NaN is not equal to NaN (native equality)');
- ok(NaN !== NaN, 'NaN is not equal to NaN (native identity)');
- ok(!_.isEqual(NaN, NaN), 'NaN is not equal to NaN');
- ok(_.isEqual(new Date(100), new Date(100)), 'identical dates are equal');
- ok(_.isEqual((/hello/ig), (/hello/ig)), 'identical regexes are equal');
- ok(!_.isEqual(null, [1]), 'a falsy is never equal to a truthy');
- ok(_.isEqual({isEqual: function () { return true; }}, {}), 'first object implements `isEqual`');
- ok(_.isEqual({}, {isEqual: function () { return true; }}), 'second object implements `isEqual`');
- ok(!_.isEqual({x: 1, y: undefined}, {x: 1, z: 2}), 'objects with the same number of undefined keys are not equal');
- ok(!_.isEqual(_({x: 1, y: undefined}).chain(), _({x: 1, z: 2}).chain()), 'wrapped objects are not equal');
- equals(_({x: 1, y: 2}).chain().isEqual(_({x: 1, y: 2}).chain()).value(), true, 'wrapped objects are equal');
+ function First() {
+ this.value = 1;
+ }
+ First.prototype.value = 1;
+ function Second() {
+ this.value = 1;
+ }
+ Second.prototype.value = 2;
+
+ // Basic equality and identity comparisons.
+ ok(_.isEqual(null, null), "`null` is equal to `null`");
+ ok(_.isEqual(), "`undefined` is equal to `undefined`");
+
+ ok(!_.isEqual(0, -0), "`0` is not equal to `-0`");
+ ok(!_.isEqual(-0, 0), "Commutative equality is implemented for `0` and `-0`");
+ ok(!_.isEqual(null, undefined), "`null` is not equal to `undefined`");
+ ok(!_.isEqual(undefined, null), "Commutative equality is implemented for `null` and `undefined`");
+
+ // String object and primitive comparisons.
+ ok(_.isEqual("Curly", "Curly"), "Identical string primitives are equal");
+ ok(_.isEqual(new String("Curly"), new String("Curly")), "String objects with identical primitive values are equal");
+
+ ok(!_.isEqual("Curly", "Larry"), "String primitives with different values are not equal");
+ ok(!_.isEqual(new String("Curly"), "Curly"), "String primitives and their corresponding object wrappers are not equal");
+ ok(!_.isEqual("Curly", new String("Curly")), "Commutative equality is implemented for string objects and primitives");
+ ok(!_.isEqual(new String("Curly"), new String("Larry")), "String objects with different primitive values are not equal");
+ ok(!_.isEqual(new String("Curly"), {toString: function(){ return "Curly"; }}), "String objects and objects with a custom `toString` method are not equal");
+
+ // Number object and primitive comparisons.
+ ok(_.isEqual(75, 75), "Identical number primitives are equal");
+ ok(_.isEqual(new Number(75), new Number(75)), "Number objects with identical primitive values are equal");
+
+ ok(!_.isEqual(75, new Number(75)), "Number primitives and their corresponding object wrappers are not equal");
+ ok(!_.isEqual(new Number(75), 75), "Commutative equality is implemented for number objects and primitives");
+ ok(!_.isEqual(new Number(75), new Number(63)), "Number objects with different primitive values are not equal");
+ ok(!_.isEqual(new Number(63), {valueOf: function(){ return 63; }}), "Number objects and objects with a `valueOf` method are not equal");
+
+ // Comparisons involving `NaN`.
+ ok(_.isEqual(NaN, NaN), "`NaN` is equal to `NaN`");
+ ok(!_.isEqual(61, NaN), "A number primitive is not equal to `NaN`");
+ ok(!_.isEqual(new Number(79), NaN), "A number object is not equal to `NaN`");
+ ok(!_.isEqual(Infinity, NaN), "`Infinity` is not equal to `NaN`");
+
+ // Boolean object and primitive comparisons.
+ ok(_.isEqual(true, true), "Identical boolean primitives are equal");
+ ok(_.isEqual(new Boolean, new Boolean), "Boolean objects with identical primitive values are equal");
+ ok(!_.isEqual(true, new Boolean(true)), "Boolean primitives and their corresponding object wrappers are not equal");
+ ok(!_.isEqual(new Boolean(true), true), "Commutative equality is implemented for booleans");
+ ok(!_.isEqual(new Boolean(true), new Boolean), "Boolean objects with different primitive values are not equal");
+
+ // Common type coercions.
+ ok(!_.isEqual(true, new Boolean(false)), "Boolean objects are not equal to the boolean primitive `true`");
+ ok(!_.isEqual("75", 75), "String and number primitives with like values are not equal");
+ ok(!_.isEqual(new Number(63), new String(63)), "String and number objects with like values are not equal");
+ ok(!_.isEqual(75, "75"), "Commutative equality is implemented for like string and number values");
+ ok(!_.isEqual(0, ""), "Number and string primitives with like values are not equal");
+ ok(!_.isEqual(1, true), "Number and boolean primitives with like values are not equal");
+ ok(!_.isEqual(new Boolean(false), new Number(0)), "Boolean and number objects with like values are not equal");
+ ok(!_.isEqual(false, new String("")), "Boolean primitives and string objects with like values are not equal");
+ ok(!_.isEqual(12564504e5, new Date(2009, 9, 25)), "Dates and their corresponding numeric primitive values are not equal");
+
+ // Dates.
+ ok(_.isEqual(new Date(2009, 9, 25), new Date(2009, 9, 25)), "Date objects referencing identical times are equal");
+ ok(!_.isEqual(new Date(2009, 9, 25), new Date(2009, 11, 13)), "Date objects referencing different times are not equal");
+ ok(!_.isEqual(new Date(2009, 11, 13), {
+ getTime: function(){
+ return 12606876e5;
+ }
+ }), "Date objects and objects with a `getTime` method are not equal");
+ ok(!_.isEqual(new Date("Curly"), new Date("Curly")), "Invalid dates are not equal");
+
+ // Functions.
+ ok(!_.isEqual(First, Second), "Different functions with identical bodies and source code representations are not equal");
+
+ // RegExps.
+ ok(_.isEqual(/(?:)/gim, /(?:)/gim), "RegExps with equivalent patterns and flags are equal");
+ ok(!_.isEqual(/(?:)/g, /(?:)/gi), "RegExps with equivalent patterns and different flags are not equal");
+ ok(!_.isEqual(/Moe/gim, /Curly/gim), "RegExps with different patterns and equivalent flags are not equal");
+ ok(!_.isEqual(/(?:)/gi, /(?:)/g), "Commutative equality is implemented for RegExps");
+ ok(!_.isEqual(/Curly/g, {source: "Larry", global: true, ignoreCase: false, multiline: false}), "RegExps and RegExp-like objects are not equal");
+
+ // Empty arrays, array-like objects, and object literals.
+ ok(_.isEqual({}, {}), "Empty object literals are equal");
+ ok(_.isEqual([], []), "Empty array literals are equal");
+ ok(_.isEqual([{}], [{}]), "Empty nested arrays and objects are equal");
+ ok(_.isEqual({length: 0}, []), "Array-like objects and arrays are equal");
+ ok(_.isEqual([], {length: 0}), "Commutative equality is implemented for array-like objects");
+
+ ok(!_.isEqual({}, []), "Object literals and array literals are not equal");
+ ok(!_.isEqual([], {}), "Commutative equality is implemented for objects and arrays");
+
+ // Arrays with primitive and object values.
+ ok(_.isEqual([1, "Larry", true], [1, "Larry", true]), "Arrays containing identical primitives are equal");
+ ok(_.isEqual([/Moe/g, new Date(2009, 9, 25)], [/Moe/g, new Date(2009, 9, 25)]), "Arrays containing equivalent elements are equal");
+
+ // Multi-dimensional arrays.
+ var a = [new Number(47), false, "Larry", /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}];
+ var b = [new Number(47), false, "Larry", /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}];
+ ok(_.isEqual(a, b), "Arrays containing nested arrays and objects are recursively compared");
+
+ // Overwrite the methods defined in ES 5.1 section 15.4.4.
+ a.forEach = a.map = a.filter = a.every = a.indexOf = a.lastIndexOf = a.some = a.reduce = a.reduceRight = null;
+ b.join = b.pop = b.reverse = b.shift = b.slice = b.splice = b.concat = b.sort = b.unshift = null;
+
+ // Array elements and properties.
+ ok(_.isEqual(a, b), "Arrays containing equivalent elements and different non-numeric properties are equal");
+ a.push("White Rocks");
+ ok(!_.isEqual(a, b), "Arrays of different lengths are not equal");
+ a.push("East Boulder");
+ b.push("Gunbarrel Ranch", "Teller Farm");
+ ok(!_.isEqual(a, b), "Arrays of identical lengths containing different elements are not equal");
+
+ // Sparse arrays.
+ ok(_.isEqual(Array(3), Array(3)), "Sparse arrays of identical lengths are equal");
+ ok(!_.isEqual(Array(3), Array(6)), "Sparse arrays of different lengths are not equal");
+
+ // According to the Microsoft deviations spec, section 2.1.26, JScript 5.x treats `undefined`
+ // elements in arrays as elisions. Thus, sparse arrays and dense arrays containing `undefined`
+ // values are equivalent.
+ if (0 in [undefined]) {
+ ok(!_.isEqual(Array(3), [undefined, undefined, undefined]), "Sparse and dense arrays are not equal");
+ ok(!_.isEqual([undefined, undefined, undefined], Array(3)), "Commutative equality is implemented for sparse and dense arrays");
+ }
+
+ // Simple objects.
+ ok(_.isEqual({a: "Curly", b: 1, c: true}, {a: "Curly", b: 1, c: true}), "Objects containing identical primitives are equal");
+ ok(_.isEqual({a: /Curly/g, b: new Date(2009, 11, 13)}, {a: /Curly/g, b: new Date(2009, 11, 13)}), "Objects containing equivalent members are equal");
+ ok(!_.isEqual({a: 63, b: 75}, {a: 61, b: 55}), "Objects of identical sizes with different values are not equal");
+ ok(!_.isEqual({a: 63, b: 75}, {a: 61, c: 55}), "Objects of identical sizes with different property names are not equal");
+ ok(!_.isEqual({a: 1, b: 2}, {a: 1}), "Objects of different sizes are not equal");
+ ok(!_.isEqual({a: 1}, {a: 1, b: 2}), "Commutative equality is implemented for objects");
+ ok(!_.isEqual({x: 1, y: undefined}, {x: 1, z: 2}), "Objects with identical keys and different values are not equivalent");
+
+ // `A` contains nested objects and arrays.
+ a = {
+ name: new String("Moe Howard"),
+ age: new Number(77),
+ stooge: true,
+ hobbies: ["acting"],
+ film: {
+ name: "Sing a Song of Six Pants",
+ release: new Date(1947, 9, 30),
+ stars: [new String("Larry Fine"), "Shemp Howard"],
+ minutes: new Number(16),
+ seconds: 54
+ }
+ };
+
+ // `B` contains equivalent nested objects and arrays.
+ b = {
+ name: new String("Moe Howard"),
+ age: new Number(77),
+ stooge: true,
+ hobbies: ["acting"],
+ film: {
+ name: "Sing a Song of Six Pants",
+ release: new Date(1947, 9, 30),
+ stars: [new String("Larry Fine"), "Shemp Howard"],
+ minutes: new Number(16),
+ seconds: 54
+ }
+ };
+ ok(_.isEqual(a, b), "Objects with nested equivalent members are recursively compared");
+
+ // Instances.
+ ok(_.isEqual(new First, new First), "Object instances are equal");
+ ok(_.isEqual(new First, new Second), "Objects with different constructors and identical own properties are equal");
+ ok(_.isEqual({value: 1}, new First), "Object instances and objects sharing equivalent properties are identical");
+ ok(!_.isEqual({value: 2}, new Second), "The prototype chain of objects should not be examined");
+
+ // Circular Arrays.
+ (a = []).push(a);
+ (b = []).push(b);
+ ok(_.isEqual(a, b), "Arrays containing circular references are equal");
+ a.push(new String("Larry"));
+ b.push(new String("Larry"));
+ ok(_.isEqual(a, b), "Arrays containing circular references and equivalent properties are equal");
+ a.push("Shemp");
+ b.push("Curly");
+ ok(!_.isEqual(a, b), "Arrays containing circular references and different properties are not equal");
+
+ // Circular Objects.
+ a = {abc: null};
+ b = {abc: null};
+ a.abc = a;
+ b.abc = b;
+ ok(_.isEqual(a, b), "Objects containing circular references are equal");
+ a.def = 75;
+ b.def = 75;
+ ok(_.isEqual(a, b), "Objects containing circular references and equivalent properties are equal");
+ a.def = new Number(75);
+ b.def = new Number(63);
+ ok(!_.isEqual(a, b), "Objects containing circular references and different properties are not equal");
+
+ // Cyclic Structures.
+ a = [{abc: null}];
+ b = [{abc: null}];
+ (a[0].abc = a).push(a);
+ (b[0].abc = b).push(b);
+ ok(_.isEqual(a, b), "Cyclic structures are equal");
+ a[0].def = "Larry";
+ b[0].def = "Larry";
+ ok(_.isEqual(a, b), "Cyclic structures containing equivalent properties are equal");
+ a[0].def = new String("Larry");
+ b[0].def = new String("Curly");
+ ok(!_.isEqual(a, b), "Cyclic structures containing different properties are not equal");
+
+ // Complex Circular References.
+ a = {foo: {b: {foo: {c: {foo: null}}}}};
+ b = {foo: {b: {foo: {c: {foo: null}}}}};
+ a.foo.b.foo.c.foo = a;
+ b.foo.b.foo.c.foo = b;
+ ok(_.isEqual(a, b), "Cyclic structures with nested and identically-named properties are equal");
+
+ // Chaining.
+ ok(!_.isEqual(_({x: 1, y: undefined}).chain(), _({x: 1, z: 2}).chain()), 'Chained objects containing different values are not equal');
+ equals(_({x: 1, y: 2}).chain().isEqual(_({x: 1, y: 2}).chain()).value(), true, '`isEqual` can be chained');
+
+ // Custom `isEqual` methods.
+ var isEqualObj = {isEqual: function (o) { return o.isEqual == this.isEqual; }, unique: {}};
+ var isEqualObjClone = {isEqual: isEqualObj.isEqual, unique: {}};
+
+ ok(_.isEqual(isEqualObj, isEqualObjClone), 'Both objects implement identical `isEqual` methods');
+ ok(_.isEqual(isEqualObjClone, isEqualObj), 'Commutative equality is implemented for objects with custom `isEqual` methods');
+ ok(!_.isEqual(isEqualObj, {}), 'Objects that do not implement equivalent `isEqual` methods are not equal');
+ ok(!_.isEqual({}, isEqualObj), 'Commutative equality is implemented for objects with different `isEqual` methods');
});
test("objects: isEmpty", function() {
@@ -113,14 +322,14 @@ $(document).ready(function() {
parent.iElement = document.createElement('div');\
parent.iArguments = (function(){ return arguments; })(1, 2, 3);\
parent.iArray = [1, 2, 3];\
- parent.iString = 'hello';\
- parent.iNumber = 100;\
+ parent.iString = new String('hello');\
+ parent.iNumber = new Number(100);\
parent.iFunction = (function(){});\
parent.iDate = new Date();\
parent.iRegExp = /hi/;\
parent.iNaN = NaN;\
parent.iNull = null;\
- parent.iBoolean = false;\
+ parent.iBoolean = new Boolean(false);\
parent.iUndefined = undefined;\
"
);
diff --git a/test/utility.js b/test/utility.js
index 94252a654..976b3b996 100644
--- a/test/utility.js
+++ b/test/utility.js
@@ -1,6 +1,6 @@
$(document).ready(function() {
- module("Utility functions (uniqueId, template)");
+ module("Utility");
test("utility: noConflict", function() {
var underscore = _.noConflict();
@@ -81,6 +81,10 @@ $(document).ready(function() {
var withNewlinesAndTabs = _.template('This\n\t\tis: <%= x %>.\n\tok.\nend.');
equals(withNewlinesAndTabs({x: 'that'}), 'This\n\t\tis: that.\n\tok.\nend.');
+ var template = _.template("<%- value %>");
+ var result = template({value: "