Skip to content

Instantly share code, notes, and snippets.

@christianscott
Last active January 7, 2019 23:31
Show Gist options
  • Save christianscott/eae24fc312f6c6a685005865e7a2df2a to your computer and use it in GitHub Desktop.
Save christianscott/eae24fc312f6c6a685005865e7a2df2a to your computer and use it in GitHub Desktop.
const NO_ARGUMENTS_YET = Symbol("no arguments yet");
function allEqual<Arr extends any[]>(first: Arr, second: Arr): boolean {
return first.every((value, i) => value === second[i]);
}
export function memoizeOnce<ArgsT extends any[], ReturnT>(
fn: (...args: ArgsT) => ReturnT,
comparator: (prevArgs: ArgsT, nextArgs: ArgsT) => boolean = allEqual
) {
let lastCalledWithArgs: ArgsT | typeof NO_ARGUMENTS_YET = NO_ARGUMENTS_YET;
let cachedResult: ReturnT;
return (...args: ArgsT) => {
if (
lastCalledWithArgs !== NO_ARGUMENTS_YET &&
comparator(lastCalledWithArgs, args)
) {
return cachedResult;
}
lastCalledWithArgs = args;
cachedResult = fn(...args);
return cachedResult;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment