Skip to content

Instantly share code, notes, and snippets.

@sebmarkbage
Last active September 28, 2018 14:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebmarkbage/1b474f3e2d8bc99df1210b93822ffe8f to your computer and use it in GitHub Desktop.
Save sebmarkbage/1b474f3e2d8bc99df1210b93822ffe8f to your computer and use it in GitHub Desktop.
function shallowCompare(a, b) {
if (a === b) {
return true;
}
if (typeof a === 'object' && typeof b === 'object' && hiddenClass(a) === hiddenClass(b)) {
return !memcmp(a, b, sizeOfClass(a));
}
if (typeof a === 'function' && typeof b === 'function') {
if (sourceLocation(a) === sourceLocation(b)) {
return shallowCompare(getClosureContextOf(a), getClosureContextOf(b));
}
}
return false;
}
function memoize(fn) {
var lastArg, lastResult;
return function(arg) {
if (lastArg && shallowCompare(lastArg, arg)) {
return lastResult;
}
lastArg = arg;
lastResult = fn(arg);
return lastResult;
};
}
var memoizedRender = memoize(render);
var obj = {};
memoizedRender({ a: 123, b: obj });
memoizedRender({ a: 123, b: obj }); // fast path
var captured = 123;
function renderWithCallback() {
return memoizedRender(function foo() {
return captured;
});
}
renderWithCallback();
renderWithCallback(); // fast path because the result is memoized
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment