Some functions are slow but always give the same result for the same input: parsing a date format, finding the factors of a number, computing a layout for a given width. Memoizing such a function means remembering each result the first time it is computed, and returning the remembered result on later calls with the same input, without running the function again.
Write memoize(fn) in memoize.js for functions of one argument. It returns a new function that behaves like fn, but runs fn at most once per distinct argument.
memoize(fn) returns a function, and does not call fn itself.
The first call with an argument runs fn and returns its result; later calls with the same argument return the same value (the same object, not a copy) without running fn.
Arguments are compared as Map keys are: 1 and "1" are different, two objects are the same only if they are the same object, and NaN matches NaN.
Falsy arguments (0, "", false, null, undefined) each get their own entry, and falsy results, undefined included, are cached like any other.
If fn throws, the error reaches the caller and nothing is cached: the next call with that argument runs fn again.
Each memoized function has its own cache.
fn runs with the this of the call, so the memoized function works as a method. It is fn itself that runs, even when fn has its own property named call or apply.
A recursive fn that calls its own memoized version benefits from the cache.