Last active
November 10, 2015 22:33
-
-
Save rkatic/e08612b1e1a1b705a32c to your computer and use it in GitHub Desktop.
shallow equality
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
/*eslint-env es6*/ | |
const hasOwn = ({}).hasOwnProperty; | |
// Check if two objects are equal by comparing own enumerable properties. | |
const isEqualShallow = (a, b) => { | |
if (a === b) return true; | |
if (!a || !b) return false; | |
const akeys = Object.keys(a); | |
const bkeys = Object.keys(b); | |
if (akeys.length !== bkeys.length) return false; | |
const n = akeys.length; | |
while (n--) { | |
const k = akeys[n]; | |
if (!hasOwn.call(b, k) || a[k] !== b[k]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
// Check if two plain-objects have same properties. | |
const arePropsEqual = (a, b) => { | |
let k, n = 0; | |
for (k in a) { | |
if (!hasOwn.call(b, k) || a[k] !== b[k]) { | |
return false; | |
} | |
++n; | |
} | |
for (k in b) --n; | |
return !n; | |
} | |
// Example of shouldComponentUpdate in React for pure components. | |
function propsAreChanged(newProps) { | |
return !arePropsEqual(this.props, newProps); | |
} | |
module.exports = { | |
isEqualShallow, | |
arePropsEqual, | |
propsAreChanged | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment