Last active
August 29, 2015 14:01
-
-
Save jremmen/738f9d36330937a19020 to your computer and use it in GitHub Desktop.
js: object/array isEqual method
This file contains hidden or 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
Object.prototype.isEqual = function(obj) { | |
function iter(a, b) { | |
for(p in a) { | |
if(a.hasOwnProperty(p)) { | |
if(!b.hasOwnProperty(p)) return false; | |
else if(['array', 'object'].indexOf(typeof b[p]) > -1) { | |
if(!iter(b[p], a[p])) return false; | |
} | |
else if(b[p] !== a[p]) return false; | |
} | |
} | |
return true; | |
} | |
return iter(obj, this) && iter(this, obj); | |
} | |
mittens = {color: 'white', age: 1, eyes: 'blue', sex: 'female', toys: ['yarn', 'catnip']} | |
furball = {color: 'black', age: 2, eyes: 'yellow', sex: 'male', toys: ['mice', 'lizards']} | |
purrster = {color: 'orange', age: 1, eyes: 'blue', sex: 'male', toys: ['boxes', 'shadows']} | |
blankinclaws = {color: 'brown', age: 21, eyes: 'brown', sex: 'male', toys: ['balls']} | |
a = {animals: [mittens, furball, purrster]} | |
b = {animals: [mittens, furball, purrster]} | |
c = {animals: [mittens, furball, purrster, blankinclaws ]} | |
a.isEqual(b) // true | |
b.isEqual(a) // true | |
c.isEqual(a) // false | |
a.isEqual(c) // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment