Deviopath › TypeScript

Typed Memoize with Stats

Hard · Generics

Write memoize(fn, options) that returns a function with the same types as fn, plus two methods.

- The cache key is options.key(...args) if given, otherwise JSON.stringify(args).

- A hit returns the cached result without calling fn; a miss calls fn and stores the result. Count both.

- The cache holds at most options.maxSize entries. When a NEW key must be stored and the cache is full, first delete the entry INSERTED earliest (first in, first out; hits do not refresh it).

- stats() returns { hits, misses, size } (size = current number of entries).

- clear() empties the cache but keeps the counters.

The driver runMemo(maxSize, ops, sortedKey) memoizes an add function; with sortedKey it passes a key that ignores argument order. Its stats output also has how many times the real function ran (computed).

Next: Evaluate an Expression Tree