Typed memoize in TypeScript
Memoization that keeps the original signature intact.
function memoize<A extends unknown[], R>(
fn: (...args: A) => R,
): (...args: A) => R {
const cache = new Map<string, R>();
return (...args: A): R => {
const key = JSON.stringify(args);
if (!cache.has(key)) {
cache.set(key, fn(...args));
}
return cache.get(key) as R;
};
}
Keywords and builtins used here
AJSONMapasconstextendsfunctionifreturnstring
The run, in numbers
- Lines
- 12
- Characters to type
- 272
- Tokens
- 103
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 59 seconds.
Step 1 of 5 in Timing & memory, step 14 of 19 in Classes & patterns.