8.8. Memoize methods per object
Topics
This question is in
8. Currying and memoizationA plain memoize keyed by arguments is wrong for a method. Two Converter objects with different rates both call convert(10), and the second would get the first one's answer, because the result also depends on this. Caching per object fixes that, but brings a new problem: a cache that holds the object keeps it in memory forever, even after the page has dropped it. In a long-running page that creates and discards thousands of objects, that is a memory leak.
Write memoizeMethod(fn) in memoize-method.js. It returns a function to use as a method, on a class prototype or an object. Its results are cached separately for each object it is called on, keyed by the full list of arguments, and the cache disappears together with the object.
Signature
function memoizeMethod(fn) // returns the memoized method
memoized.clear(target) // forgets every result cached for targetfn: the method body. It may readthisand take any number of arguments.- The returned function runs
fnwith its ownthisand arguments, and returnsfn's result. clear(target), a property of the returned function, returnsundefined.
Requirements
memoizeMethod(fn)returns a function and does not callfn. Used as a method,fnruns with the object asthisand every argument, and the call returnsfn's result.- Calling it again on the same object with the same arguments returns the stored result (the same value, not a copy) without running
fn. - Different objects never share results, and filling one object's cache does not touch another's.
- Arguments are compared one by one, in order, as
Mapkeys are:1and"1"differ,NaNmatchesNaN,0and-0match, and objects match only themselves. The number of arguments counts too:f(1)andf(1, undefined)are different calls, and so aref()andf(undefined). - Every result is cached,
undefinedand other falsy values included. Iffnthrows, the error reaches the caller and nothing is cached. clear(target)forgets that object's results and no other's. It never throws, whatever it is given.- The cache adds no property to the object, works on frozen objects, and does not keep the object alive: it is never stored in a
Map, aSetor an array. - When
thisis not an object or a function (a number, a string,undefined,null),fnruns every time, uncached, and nothing throws. A function asthis, as in a static method, is cached like an object. - Each memoized method has its own cache. A method that calls itself through
thisuses the cache.
Examples
class Converter {
constructor(rate) { this.rate = rate; }
}
Converter.prototype.convert = memoizeMethod(function (amount) {
console.log("computing", amount, "at", this.rate);
return amount * this.rate;
});
const inr = new Converter(83);
const eur = new Converter(0.9);
inr.convert(10); // logs, returns 830
inr.convert(10); // 830, no log
eur.convert(10); // logs, returns 9: a different objectconst run = memoizeMethod((...args) => args.length);
const obj = { run };
obj.run(1); // 1
obj.run(1, undefined); // 2: a different callConverter.prototype.convert.clear(inr);
inr.convert(10); // logs again; eur's results are still cachedEnvironment
- Plain JavaScript in a browser page; the tests call the global
memoizeMethodfrommemoize-method.js. The file starts with"use strict";: keep it, so that a plain call getsundefinedasthisinstead of the global object. - A size limit and expiry are not part of this problem. Argument objects may be kept in memory for as long as the object they were used with.
- Simpler versions are problem 8.6 (one argument) and problem 8.7 (a key resolver and a size limit).
Hints
- Which built-in collection can use an object as a key without keeping the object alive?
- A list of arguments of any length can be looked up one argument at a time. What do you need to know at the end of that walk to tell
f(1)fromf(1, 2)?
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