Last active
June 2, 2023 12:08
-
-
Save romgrk/505b068b08384cafe47ef7f094495aa3 to your computer and use it in GitHub Desktop.
Fastest shallow compare
This file contains 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 is = Object.is; | |
export function fastObjectShallowCompare<T extends Record<string, any> | null>(a: T, b: T) { | |
if (a === b) { | |
return true; | |
} | |
if (!(a instanceof Object) || !(b instanceof Object)) { | |
return false; | |
} | |
let aLength = 0; | |
let bLength = 0; | |
/* eslint-disable no-restricted-syntax */ | |
/* eslint-disable guard-for-in */ | |
for (const key in a) { | |
aLength += 1; | |
if (!(key in b)) { | |
return false; | |
} | |
if (!is(a[key], b[key])) { | |
return false; | |
} | |
} | |
for (const _ in b) { | |
bLength += 1; | |
} | |
/* eslint-enable no-restricted-syntax */ | |
/* eslint-enable guard-for-in */ | |
return aLength === bLength; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment