-
-
Save gajus/1651f58bbcab629f9401 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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