Created
December 29, 2018 13:44
-
-
Save nodew/765e106dca5c1b3e9f301d31483b0c8a to your computer and use it in GitHub Desktop.
Test if two variables in JavaScript are deep equal
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
const baseTypes = [ | |
"[object Number]", | |
"[object String]", | |
"[object Undefined]", | |
"[object Boolean]", | |
"[object Symbol]", | |
"[object Function]" | |
] | |
function deepEqual(a, b) { | |
const typeOfA = Object.prototype.toString.call(a); | |
const typeOfB = Object.prototype.toString.call(b); | |
if (typeOfA !== typeOfB) { | |
return false; | |
} | |
if (baseTypes.includes(typeOfA)) { | |
return a === b; | |
} | |
if (typeOfA === "[object Array]") { | |
if (a.length !== b.length) { | |
return false; | |
} | |
for (let i = 0; i < a.length; i++) { | |
if (!deepEqual(a[i], b[i])) { | |
return false | |
} | |
} | |
} | |
if (typeOfA === "[object Object]") { | |
const keysOfA = Object.keys(a); | |
const keysOfB = Object.keys(b); | |
if (keysOfA.length !== keysOfB.length) { | |
return false; | |
} | |
for (let i = 0; i < keysOfA.length; i++) { | |
let key = keysOfA[i]; | |
if (!deepEqual(a[key], b[key])) { | |
return false | |
} | |
} | |
} | |
return true; | |
} | |
console.log(deepEqual({a: 1, b: [1, 2]}, {a: 1, b: [1, 2, 3]})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment