Created
February 27, 2022 04:12
-
-
Save ZacharyL2/26b1ba8b54c220b85fbfff1ae87d1a64 to your computer and use it in GitHub Desktop.
shallowEqual in React
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 shallowEqual(objA, objB) { | |
// P1 | |
if (Object.is(objA, objB)) { | |
return true; | |
} | |
// P2 | |
if ( | |
typeof objA !== 'object' || | |
objA === null || | |
typeof objB !== 'object' || | |
objB === null | |
) { | |
return false; | |
} | |
// P3 | |
var keysA = Object.keys(objA); | |
var keysB = Object.keys(objB); | |
if (keysA.length !== keysB.length) { | |
return false; | |
} | |
for (var i = 0; i < keysA.length; i++) { | |
if ( | |
!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || | |
!Object.is(objA[keysA[i]], objB[keysA[i]]) | |
) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment