summaryrefslogtreecommitdiff
path: root/u/leftpadesque/memoize.ts
blob: 95e6019a0a4fa0789d1e7ee631ec8126e32450c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import type { Callable } from "@emprespresso/pengueno";

export const memoize = <R, F extends Callable<R>>(fn: F): F => {
  const cache = new Map<string, R>();
  return ((...args: unknown[]): R => {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      return cache.get(key)!;
    }
    const res = fn.apply(args);
    cache.set(key, res);
    return res;
  }) as F;
};