Skip to content

Instantly share code, notes, and snippets.

@romgrk
Last active June 2, 2023 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romgrk/505b068b08384cafe47ef7f094495aa3 to your computer and use it in GitHub Desktop.
Save romgrk/505b068b08384cafe47ef7f094495aa3 to your computer and use it in GitHub Desktop.
Fastest shallow compare
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