Created
December 14, 2022 09:56
-
-
Save MarcelloDiSimone/464a334becbf65f024c89dcf313ab928 to your computer and use it in GitHub Desktop.
Method to equal nested objects
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
const deepEqual = (objA: any, objB: any, map = new WeakMap()) => { | |
if (Object.is(objA, objB)) { | |
return true; | |
} | |
if (objA instanceof Date && objB instanceof Date) { | |
return objA.getTime() === objB.getTime(); | |
} | |
if (objA instanceof RegExp && objB instanceof RegExp) { | |
return objA.toString() === objB.toString(); | |
} | |
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { | |
return false; | |
} | |
if (map.get(objA) === objB) { | |
return true; | |
} | |
map.set(objA, objB); | |
const keysA = Reflect.ownKeys(objA); | |
const keysB = Reflect.ownKeys(objB); | |
if (keysA.length !== keysB.length) { | |
return false; | |
} | |
for (let i = 0; i < keysA.length; i++) { | |
if (!Reflect.has(objB, keysA[i]) || !deepEqual(objA[keysA[i]], objB[keysA[i]], map)) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment