typestar

Memoize in JavaScript

Caches a function's results by argument so the second call is free.

function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (!cache.has(key)) {
      cache.set(key, fn.apply(this, args));
    }
    return cache.get(key);
  };
}

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
200
Tokens
70
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 42 seconds.

Type this snippet

Step 3 of 4 in Closures, step 3 of 16 in Functions & patterns.

← Previous Next →