Last active
August 30, 2016 22:01
-
-
Save heatherbooker/e9592a064135067efe730728e21fedcb to your computer and use it in GitHub Desktop.
Implementation of recursive 'deepEqual' function as suggested in Eloquent Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// deepEqual takes two variables and tests for property/value equality, recursively for objects. | |
// Idea for function and some examples for testing borrowed from ch.4 in Marijn Haverbeke's "Eloquent Javascript". | |
function deepEqual(obj1, obj2) { | |
if (typeof obj1 === typeof obj2) { | |
if (obj1 === obj2) { | |
return true; | |
} else if (obj1 && obj2) { | |
if (typeof obj1 === 'object' && typeof obj2 === 'object') { | |
for (var prop in obj1) { | |
for (var prop2 in obj2) { | |
if (prop === prop2) { | |
if (!deepEqual(obj1[prop], obj2[prop2])) { | |
return false; | |
} | |
} | |
} | |
} | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
function testDeepEqual() { | |
var obj = {here: {is: 'an'}, object: 2}; | |
console.log('You should see alternating true/false, starting and ending with false.'); | |
console.log(deepEqual(obj, 2)); | |
// -> false | |
console.log(deepEqual('a string', 'a string')); | |
// -> true | |
console.log(deepEqual(null, obj)); | |
// -> false | |
console.log(deepEqual(obj, obj)); | |
// → true | |
console.log(deepEqual(obj, {here: 1, object: 2})); | |
// → false | |
console.log(deepEqual(obj, {here: {is: 'an'}, object: 2})); | |
// → true | |
console.log(deepEqual(null, undefined)); | |
// -> false | |
} | |
testDeepEqual(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment