Created
February 16, 2021 08:44
-
-
Save gunn/9e52d3914f6cfd561401ba8f3681582a to your computer and use it in GitHub Desktop.
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
function isRecord(record): boolean { | |
// Could be improved, perhaps with use of a Symbol: | |
return record && record._id && (typeof record._id)=="string" | |
} | |
function isSimple(obj): boolean { | |
return !obj || isRecord(obj) || (typeof obj)!="object" | |
} | |
function shallowEqual(objA: any, objB: any): boolean { | |
const simpleComparison = isSimple(objA) || isSimple(objB) | |
if (simpleComparison) { | |
return objA === objB | |
} | |
if (Array.isArray(objA) && Array.isArray(objB)) { | |
if (objA.length !== objB.length) return false | |
return objA.every((e, i)=> | |
objB[i] === e | |
) | |
} | |
if (typeof objA == 'object' && typeof objB == 'object') { | |
const keysA = Object.keys(objA) | |
const keysB = Object.keys(objB) | |
if (keysA.length !== keysB.length) return false | |
return keysA.every(key=> | |
objA[key] === objB[key] | |
) | |
} | |
return false | |
} | |
export default shallowEqual |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment