Skip to content

Instantly share code, notes, and snippets.

@qb20nh
Created September 27, 2023 17:03
Show Gist options
  • Save qb20nh/8510f1cc94dc4a5cc966aade0b06d818 to your computer and use it in GitHub Desktop.
Save qb20nh/8510f1cc94dc4a5cc966aade0b06d818 to your computer and use it in GitHub Desktop.
deepEqual.js
function deepEqual(a, b) {
// Handle edge cases and primitives using Object.is
if (Object.is(a, b)) return true;
// Handle arrays
const isArray = Array.isArray(a) && Array.isArray(b);
const isTypedArray = ArrayBuffer.isView(a) && ArrayBuffer.isView(b);
if (isArray || isTypedArray) {
if (isTypedArray) {
// Check if both are of the same type
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
}
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (isTypedArray) {
if (a[i] !== b[i]) return false;
} else if (!deepEqual(a[i], b[i])) return false;
}
return true;
}
// Handle maps
if (a instanceof Map && b instanceof Map) {
if (a.size !== b.size) return false;
for (const key of a.keys()) {
if (!b.has(key)) return false;
}
for (const [key, value] of a) {
if (!deepEqual(value, b.get(key))) return false;
}
return true;
}
// Handle sets
if (a instanceof Set && b instanceof Set) {
if (a.size !== b.size) return false;
for (const value of a) {
if (!b.has(value)) return false;
}
return true;
}
// Handle Date objects
if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime();
}
// Handle RegExp objects
if (a instanceof RegExp && b instanceof RegExp) {
return a.source === b.source && a.flags === b.flags;
}
// Handle objects
if (a instanceof Object && b instanceof Object) {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (!deepEqual(keysA, keysB)) return false;
for (let key of keysA) {
if (!deepEqual(a[key], b[key])) return false;
}
return true;
}
// If none of the above checks pass, the objects are not deep equal
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment