UNPKG

2.9 kBJavaScriptView Raw
1
2// Taken from node's assert module, because it sucks
3// and exposes next to nothing useful.
4
5module.exports = _deepEqual;
6
7function _deepEqual(actual, expected) {
8 // 7.1. All identical values are equivalent, as determined by ===.
9 if (actual === expected) {
10 return true;
11
12 } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
13 if (actual.length != expected.length) return false;
14
15 for (var i = 0; i < actual.length; i++) {
16 if (actual[i] !== expected[i]) return false;
17 }
18
19 return true;
20
21 // 7.2. If the expected value is a Date object, the actual value is
22 // equivalent if it is also a Date object that refers to the same time.
23 } else if (actual instanceof Date && expected instanceof Date) {
24 return actual.getTime() === expected.getTime();
25
26 // 7.3. Other pairs that do not both pass typeof value == "object",
27 // equivalence is determined by ==.
28 } else if (typeof actual != 'object' && typeof expected != 'object') {
29 return actual === expected;
30
31 // 7.4. For all other Object pairs, including Array objects, equivalence is
32 // determined by having the same number of owned properties (as verified
33 // with Object.prototype.hasOwnProperty.call), the same set of keys
34 // (although not necessarily the same order), equivalent values for every
35 // corresponding key, and an identical "prototype" property. Note: this
36 // accounts for both named and indexed properties on Arrays.
37 } else {
38 return objEquiv(actual, expected);
39 }
40}
41
42function isUndefinedOrNull (value) {
43 return value === null || value === undefined;
44}
45
46function isArguments (object) {
47 return Object.prototype.toString.call(object) == '[object Arguments]';
48}
49
50function objEquiv (a, b) {
51 if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
52 return false;
53 // an identical "prototype" property.
54 if (a.prototype !== b.prototype) return false;
55 //~~~I've managed to break Object.keys through screwy arguments passing.
56 // Converting to array solves the problem.
57 if (isArguments(a)) {
58 if (!isArguments(b)) {
59 return false;
60 }
61 a = pSlice.call(a);
62 b = pSlice.call(b);
63 return _deepEqual(a, b);
64 }
65 try{
66 var ka = Object.keys(a),
67 kb = Object.keys(b),
68 key, i;
69 } catch (e) {//happens when one is a string literal and the other isn't
70 return false;
71 }
72 // having the same number of owned properties (keys incorporates hasOwnProperty)
73 if (ka.length != kb.length)
74 return false;
75 //the same set of keys (although not necessarily the same order),
76 ka.sort();
77 kb.sort();
78 //~~~cheap key test
79 for (i = ka.length - 1; i >= 0; i--) {
80 if (ka[i] != kb[i])
81 return false;
82 }
83 //equivalent values for every corresponding key, and
84 //~~~possibly expensive deep test
85 for (i = ka.length - 1; i >= 0; i--) {
86 key = ka[i];
87 if (!_deepEqual(a[key], b[key] ))
88 return false;
89 }
90 return true;
91}