diff --git a/index.js b/index.js index 753cfd1..1e04c8f 100644 --- a/index.js +++ b/index.js @@ -40,5 +40,43 @@ function diff( opts, subjects ){ } function isStrictEqual( a, b ){ + /* Date */ + if (a instanceof Date && !(b instanceof Date)) return false; + else if (!(a instanceof Date) && b instanceof Date) return false; + else if (a instanceof Date && b instanceof Date) + return a.getTime() === b.getTime(); + + /* Array */ + else if (Array.isArray(a) && !Array.isArray(b)) return false; + else if (!Array.isArray(a) && Array.isArray(b)) return false; + else if (Array.isArray(a) && Array.isArray(b)) { + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + + return true; + } + /* Object */ + else if (typeof a === 'object' && typeof b !== 'object') return false; + else if (typeof a !== 'object' && typeof b === 'object') return false; + else if (typeof a == 'object' && typeof b === 'object') { + var keysA = Object.keys(a); + var keysB = Object.keys(b); + if (keysA.length != keysB.length) return false; + for (var i = 0; i < keysA.length; i++) { + if (typeof b[keysA[i]] === 'undefined') return false; + if (!isStrictEqual(a[keysA[i]], b[keysA[i]])) return false; + } + + for (var i = 0; i < keysB.length; i++) { + if (typeof a[keysB[i]] === 'undefined') return false; + if (!isStrictEqual(a[keysB[i]], b[keysB[i]])) return false; + } + + return true; + } + + /* Value */ return a === b; } diff --git a/test.js b/test.js index d2df132..95af979 100644 --- a/test.js +++ b/test.js @@ -9,6 +9,7 @@ test(function( t ) { power: 54, height: undefined, level: 1, + skills: ['magic', 'running'] }; var b = { @@ -16,6 +17,7 @@ test(function( t ) { power: 22, // changed level: undefined, // changed weight: 10, // added + skills: ['magic', 'running'] // unchanged }; t.deepEqual(diff(a, b), { @@ -30,6 +32,7 @@ test(function( t ) { level: 100, // changed material: 'steel', // added location: undefined, // added but undefined + skills: ['magic', 'running', 'climbing'] // changed }; t.deepEqual(diff(a, b, c), { @@ -38,6 +41,7 @@ test(function( t ) { level: 100, weight: 10, material: 'steel', + skills: ['magic', 'running', 'climbing'] }); t.deepEqual(diff({}, {}), {}); @@ -60,8 +64,7 @@ test('Custom equality', function( t ) { }; t.deepEqual(diff(a, b), { - created: new Date(created), - updated: now, + updated: now }, 'expected default behavior'); t.deepEqual(diff.custom({