memoize-one
Version:
A memoization library which only remembers the latest invocation
65 lines (64 loc) • 2.54 kB
JavaScript
/**
* The default equality check used by `memoizeOne`.
*
* Returns `true` when both lists have the same length,
* and each item is the same value according to `Object.is`.
*/
export function areInputsEqual(newInputs, lastInputs) {
// no checks needed if the inputs length has changed
if (newInputs.length !== lastInputs.length) {
return false;
}
// Using for loop for speed. It generally performs better than array.every
// https://github.com/alexreardon/memoize-one/pull/59
for (let i = 0; i < newInputs.length; i++) {
if (!Object.is(newInputs[i], lastInputs[i])) {
return false;
}
}
return true;
}
/**
* Memoize a function so that it only remembers the latest arguments and result.
*
* The result function is called again when `this` or the arguments change.
* By default, arguments are compared with `areInputsEqual` (`Object.is` on each argument).
*
* @param resultFn The function to memoize
* @param isEqual An optional custom equality function for the arguments
*/
export function memoizeOne(resultFn,
// `TFunc & {}` makes TypeScript infer `TFunc` from `resultFn` first. Without it, an
// equality function typed as `EqualityFn` or `EqualityFn<any>` would change `TFunc`.
// The equality function is still used when `resultFn` has no parameter types.
// The TypeScript team says `T & {}` is a lower priority inference site by design:
// https://github.com/microsoft/TypeScript/issues/14829#issuecomment-320754731
isEqual = areInputsEqual) {
let cache = null;
// breaking cache when context (this) or arguments change
function memoized(...newArgs) {
if (cache && Object.is(cache.lastThis, this) && isEqual(newArgs, cache.lastArgs)) {
return cache.lastResult;
}
// Throwing during an assignment aborts the assignment: https://codepen.io/alexreardon/pen/RYKoaz
// Doing the lastResult assignment first so that if it throws
// the cache will not be overwritten
const lastResult = resultFn.apply(this, newArgs);
cache = {
lastResult,
lastArgs: newArgs,
lastThis: this,
};
return lastResult;
}
// Adding the ability to clear the cache of a memoized function
memoized.clear = function clear() {
cache = null;
};
return memoized;
}
/**
* The same function as the named `memoizeOne` export.
* Kept so that `import memoizeOne from 'memoize-one'` from v6 still works.
*/
export default memoizeOne;