Created
September 28, 2022 16:00
-
-
Save SmashingQuasar/1463a1359a43bccd08915735aa7a9d12 to your computer and use it in GitHub Desktop.
Deep object evaluation with by-value method comparison (TypeScript)
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
| function evaluate( | |
| objectA: Record<number | string | symbol, unknown>, | |
| objectB: Record<number | string | symbol, unknown>, | |
| ): boolean { | |
| const keysA: Array<number | string | symbol> = Object.keys(objectA); | |
| const keysB: Array<number | string | symbol> = Object.keys(objectB); | |
| if (keysA.length !== keysB.length) { | |
| return false; | |
| } | |
| for (const key of keysA) { | |
| if (typeof objectA[key] !== typeof objectB[key]) { | |
| return false; | |
| } | |
| if (typeof objectA[key] === 'object') { | |
| if ( | |
| !evaluate( | |
| <Record<number | string | symbol, unknown>>objectA[key], | |
| <Record<number | string | symbol, unknown>>objectB[key], | |
| ) | |
| ) { | |
| return false; | |
| } | |
| continue; | |
| } | |
| if (typeof objectA[key] === 'function') { | |
| return ( | |
| (<() => unknown>objectA[key]).toString().replace((<() => unknown>objectA[key]).name, '') === | |
| (<() => unknown>objectB[key]).toString().replace((<() => unknown>objectB[key]).name, '') | |
| ); | |
| } | |
| if (objectA[key] !== objectB[key]) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| export { evaluate }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment