Skip to content

Instantly share code, notes, and snippets.

@gunn
Created February 16, 2021 08:44
Show Gist options
  • Save gunn/9e52d3914f6cfd561401ba8f3681582a to your computer and use it in GitHub Desktop.
Save gunn/9e52d3914f6cfd561401ba8f3681582a to your computer and use it in GitHub Desktop.
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