This commit is contained in:
2020-09-15 08:58:02 -07:00
parent 823c1bc751
commit 2b36dc1e7f
6 changed files with 460 additions and 22 deletions

View File

@@ -140,7 +140,42 @@ function renderChildren(element, domElement, prevElement = { props: { children:
});
}
function defaultAreEqual(oldProps, newProps) {
if (typeof oldProps !== 'object' || typeof newProps !== 'object') {
return false;
}
const oldKeys = Object.keys(oldProps);
const newKeys = Object.keys(newProps);
if (oldKeys.length !== newKeys.length) {
return false;
}
for (let i = 0; i < oldKeys.length; i++) {
// Object.is - the comparison to note
if (!oldProps.hasOwnProperty(newKeys[i]) ||
!Object.is(oldProps[newKeys[i]], newProps[newKeys[i]])) {
return false;
}
}
return true;
}
function memo(component, areEqual = defaultAreEqual) {
let oldProps = {};
let lastResult = false;
return (props) => {
if (lastResult && areEqual(oldProps, props) {
return lastResult;
} else {
lastResult = component(props);
oldProps = Object.assign({}, props); // shallow copy
return lastResult;
}
};
}
var Hello = memo(({ dateTime }) => {
return ['h1', {}, [`It is: ${dateTime}`]];