Skip to content

Instantly share code, notes, and snippets.

@SmashingQuasar
Created September 28, 2022 16:00
Show Gist options
  • Select an option

  • Save SmashingQuasar/1463a1359a43bccd08915735aa7a9d12 to your computer and use it in GitHub Desktop.

Select an option

Save SmashingQuasar/1463a1359a43bccd08915735aa7a9d12 to your computer and use it in GitHub Desktop.
Deep object evaluation with by-value method comparison (TypeScript)
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