Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var MAX_DEPTH_OF_CHECK = 6;
function objectsAreEqual(first, second, depthOfCheck) {
var isFirstObject = isObject(first);
var isSecondObject = isObject(second);
if (!isFirstObject && !isSecondObject) { // both are not objects, compare primitives
return first === second;
} else if (!isFirstObject || !isSecondObject) { // one of them is not object
return false;
}
if (depthOfCheck >= MAX_DEPTH_OF_CHECK) { // do not check object up to infinite loop
return false;
} else {
depthOfCheck++;
}
var compareFunctions = false;
if (isFunction(first)) {
if (!isFunction(second)) { // one is function, another is object
return false;
}
compareFunctions = true;
}
var firstProps = Object.keys(first);
var secondProps = Object.keys(second);
if (firstProps.length !== secondProps.length) { // not equal amount of properties
return false;
}
if (!firstProps.length) { // empty objects, nothing to compare
return true;
}
var diffProps = firstProps.filter(function (val) {
return secondProps.indexOf(val) < 0;
});
if (diffProps.length) {
return false; // names of props are not equal
}
firstProps = firstProps.sort(function (a, b) {
return convertTypeToWeight(first[b]) - convertTypeToWeight(first[a]);
});
for (var i = 0, len = firstProps.length; i < len; i++) {
var key = firstProps[i];
var firstItem = first[key];
var secondItem = second[key];
var objectsEqual = objectsAreEqual(firstItem, secondItem, depthOfCheck);
if (!objectsEqual) {
return false;
}
}
if (compareFunctions) {
if (first.name === second.name) { // functions are equal by name
return true;
} else {
return first.toString() === second.toString(); // functions are equal by code
}
}
return true;
}
function shouldComponentUpdate(nextProps, nextState) {
var depthOfCheck = 0;
try {
var statesAreEqual = objectsAreEqual(this.state, nextState, depthOfCheck);
var propsAreEqual = objectsAreEqual(this.props, nextProps, depthOfCheck);
var shouldUpdate = !statesAreEqual || !propsAreEqual;
return shouldUpdate;
} catch (e) {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment