Skip to content

Instantly share code, notes, and snippets.

@gajus
Last active August 29, 2015 14:27
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 gajus/1651f58bbcab629f9401 to your computer and use it in GitHub Desktop.
Save gajus/1651f58bbcab629f9401 to your computer and use it in GitHub Desktop.
(function () {
function createSelectorCreator (valueEquals) {
return (selectors, resultFunc) => {
if (!Array.isArray(selectors)) {
selectors = [selectors];
}
const memoizedResultFunc = memoize(resultFunc, valueEquals);
return state => {
const params = selectors.map(selector => selector(state));
return memoizedResultFunc(params);
}
};
}
function createSelector () {
return createSelectorCreator(defaultValueEquals).apply(null, arguments);
}
function defaultValueEquals (a, b) {
return a === b;
}
// the memoize function only caches one set of arguments. This
// actually good enough, rather surprisingly. This is because during
// calculation of a selector result the arguments won't
// change if called multiple times. If a new state comes in, we *want*
// recalculation if and only if the arguments are different.
function memoize (func, valueEquals) {
let lastArgs = null;
let lastResult = null;
return (args) => {
if (lastArgs !== null && argsEquals(args, lastArgs, valueEquals)) {
return lastResult;
}
lastArgs = args;
lastResult = func(...args);
return lastResult;
}
}
function argsEquals(a, b, valueEquals) {
return a.every((value, index) => valueEquals(value, b[index]));
}
window.reselect = {
createSelectorCreator: createSelectorCreator,
createSelector: createSelector
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment