Last active
June 12, 2021 08:50
-
-
Save pjchender/59ec49c69dedab9afaca8d77755d2f7c to your computer and use it in GitHub Desktop.
shallowEqual
This file contains hidden or 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
// source code: https://github.com/facebook/react/blob/master/packages/shared/shallowEqual.js | |
// TS Playgound: https://tsplay.dev/Nr272N | |
const shallowEqual = (objA: any, objB: any): boolean => { | |
if (Object.is(objA, objB)) { | |
return true; | |
} | |
if ( | |
typeof objA !== 'object' || | |
objA === null || | |
typeof objB !== 'object' || | |
objB === null | |
) { | |
return false; | |
} | |
const keysA = Object.keys(objA); | |
const keysB = Object.keys(objB); | |
if (keysA.length !== keysB.length) { | |
return false; | |
} | |
for (let i = 0; i < keysA.length; i++) { | |
if ( | |
!objB.hasOwnProperty(keysA[i]) || // objB 中沒有該屬性 | |
!Object.is(objA[keysA[i]], objB[keysA[i]]) // objA 和 objB 中該屬性的值不同 | |
) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
console.log(shallowEqual({ foo: 'foo' }, { foo: 'foo' })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment