Last active
January 7, 2019 23:31
-
-
Save christianscott/eae24fc312f6c6a685005865e7a2df2a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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