Making a Cache Key That Can Be Found Again
In this lesson, you port the desk’s price cache to JavaScript and give it a key it can find again. The desk prices a request in pence: the word count times the rate per word, a stand-in for real pricing work that lets you count the calculations.
In Python, @lru_cache(maxsize=None) caches price(). Quoting the 400-word museum guide at 12
pence a word twice prints 4800 twice, and the counter shows one calculation: the second call found
the first call’s result.
JavaScript has no lru_cache, so you write the wrapper yourself. memoize creates a Map and
returns an arrow function, a closure that keeps that Map between calls. Its rest
parameter collects the arguments into an array, the nearest thing to Python’s tuple of arguments,
and the first port uses that array as the key. If the Map has no entry for the key, the wrapper
stores the calculation’s result, then returns the stored value.
In that wrapper, fn(...args) spreads the array back into the call, like *args in a Python call.
Called twice with the same request, the port logs 4800 twice, but its counter logs 2.