8.7. Memoize with a key resolver and a size limit
Topics
This question is in
8. Currying and memoizationA plain memoize keys its cache by the first argument and never forgets. Both are problems in real code. A function such as price(productId, currency) needs both arguments in the key. And a cache that keeps every result forever turns into a memory leak in a page that runs for hours: a search box memoized by query would keep every query ever typed.
Write memoize(fn, options) in memoize.js. It caches fn's results under a key that a resolver function can build from all the arguments, and with a maxSize it keeps only that many entries, dropping the least recently used one when it needs room.
Signature
function memoize(fn, options) // returns the memoized functionfn: the function to memoize.options(optional): an object with two optional fields.resolver: a function that receives the same arguments andthisasfn, and returns the cache key.maxSize: the most entries to keep;Infinitywhen missing.
- The memoized function takes any arguments and returns
fn's result for their key.
Requirements
memoizereturns a function, and does not callfnitself.- Each call works out a key:
resolver's return value when there is a resolver, otherwise the first argument. The resolver runs on every call, with every argument and the caller'sthis. - When the key is cached, the call returns the stored result without running
fn. Otherwisefnruns with the caller'sthisand every argument, and its result is stored under the key and returned. - Keys are compared as
Mapkeys are:1and"1"differ, objects match only themselves,NaNmatchesNaN. A result ofundefinedis cached like any other. - The cache never holds more than
maxSizeentries. Storing an entry beyond that removes the entry that was used longest ago, where a cache hit counts as a use. Up tomaxSizeentries, nothing is removed. - An error from
fnor fromresolverreaches the caller, nothing is stored, and no entry is removed. maxSizethat is not a number, or is below 1 orNaN, makesmemoizethrow aRangeError.- Each memoized function has its own cache and limit.
Examples
const price = memoize(
(id, currency) => lookUpPrice(id, currency),
{ resolver: (id, currency) => id + ":" + currency }
);
price(7, "INR"); // runs lookUpPrice
price(7, "USD"); // runs it again: a different key
price(7, "INR"); // cachedconst square = memoize((n) => n * n, { maxSize: 2 });
square(1); // runs: cache holds 1
square(2); // runs: cache holds 1, 2
square(1); // hit: 1 is now the most recently used
square(3); // runs: the cache is full, so 2 (used longest ago) is removed
square(2); // runs againmemoize(fn, { maxSize: 0 }); // RangeErrorEnvironment
- Plain JavaScript in a browser page; the tests call the global
memoizefrommemoize.js. - Time-based expiry and a way to clear the cache are not part of this problem.
- The basic version, keyed by one argument with no limit, is problem 8.6.
Hints
- A
Mapremembers the order in which keys were added. How can that order also say which key was used most recently? - Which key is the first one a
Mapgives you?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it