Skip to content

Instantly share code, notes, and snippets.

@shrkw
Created February 15, 2021 05:29
Show Gist options
  • Save shrkw/ea931381eed5ce4813da932f8ac74ae2 to your computer and use it in GitHub Desktop.
Save shrkw/ea931381eed5ce4813da932f8ac74ae2 to your computer and use it in GitHub Desktop.
check equality depp
function is(x: unknown, y: unknown): boolean {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
export function deepEquals<T>(objA: T, objB: T): boolean {
if (is(objA, objB)) return true;
if (
typeof objA !== "object" ||
objA === null ||
typeof objB !== "object" ||
objB === null
) {
return false;
}
type tk = keyof T;
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (let i = 0; i < keysA.length; i++) {
if (!Object.prototype.hasOwnProperty.call(objB, keysA[i])) return false;
if (typeof objA[keysA[i] as tk] === "object") {
if (!deepEquals(objA[keysA[i] as tk], objB[keysA[i] as tk])) return false;
} else {
if (!is(objA[keysA[i] as tk], objB[keysA[i] as tk])) return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment