Skip to content

Instantly share code, notes, and snippets.

@rkatic
Last active November 10, 2015 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rkatic/e08612b1e1a1b705a32c to your computer and use it in GitHub Desktop.
Save rkatic/e08612b1e1a1b705a32c to your computer and use it in GitHub Desktop.
shallow equality
/*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