Skip to curriculum
Jump to the editor

8.8. Memoize methods per object

Hard
Topics

This question is in

8. Currying and memoization
30–45 min

A 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

JAVASCRIPT
function memoizeMethod(fn) // returns the memoized method
memoized.clear(target)     // forgets every result cached for target
  • fn: the method body. It may read this and take any number of arguments.
  • The returned function runs fn with its own this and arguments, and returns fn's result.
  • clear(target), a property of the returned function, returns undefined.

Requirements

  1. memoizeMethod(fn) returns a function and does not call fn. Used as a method, fn runs with the object as this and every argument, and the call returns fn's result.
  2. Calling it again on the same object with the same arguments returns the stored result (the same value, not a copy) without running fn.
  3. Different objects never share results, and filling one object's cache does not touch another's.
  4. Arguments are compared one by one, in order, as Map keys are: 1 and "1" differ, NaN matches NaN, 0 and -0 match, and objects match only themselves. The number of arguments counts too: f(1) and f(1, undefined) are different calls, and so are f() and f(undefined).
  5. Every result is cached, undefined and other falsy values included. If fn throws, the error reaches the caller and nothing is cached.
  6. clear(target) forgets that object's results and no other's. It never throws, whatever it is given.
  7. 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, a Set or an array.
  8. When this is not an object or a function (a number, a string, undefined, null), fn runs every time, uncached, and nothing throws. A function as this, as in a static method, is cached like an object.
  9. Each memoized method has its own cache. A method that calls itself through this uses the cache.

Examples

JAVASCRIPT
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 object
JAVASCRIPT
const run = memoizeMethod((...args) => args.length);
const obj = { run };
obj.run(1);            // 1
obj.run(1, undefined); // 2: a different call
JAVASCRIPT
Converter.prototype.convert.clear(inr);
inr.convert(10); // logs again; eur's results are still cached

Environment

  • Plain JavaScript in a browser page; the tests call the global memoizeMethod from memoize-method.js. The file starts with "use strict";: keep it, so that a plain call gets undefined as this instead 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

  1. Which built-in collection can use an object as a key without keeping the object alive?
  2. 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) from f(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
Back to the question
Loading the editor…