Lesson 3 of 8

Memoizing function results

Goal

Never compute the same thing twice

01

Explanation

If a function is pure, meaning it always returns the same output for the same input and changes nothing outside itself, then computing it twice for the same input is wasted work.

The idea behind memoize is to wrap the function and store each result under a key that represents its inputs. If the key is already stored, you return its result; otherwise you compute the result and then store it.

A Map suits this better than a plain object, because it accepts any type as a key and doesn't inherit properties that might clash with your keys.

Warning: don't use this technique on a function that isn't pure. If it reads the time or depends on state outside itself, it will hand you a stale result.

02

Your task

Write memoize(fn) so the original function is never called twice for the same input.

Checks

6 checks
  1. memoize returns a function
  2. The result is correct
  3. The same input is computed once
  4. A different input is computed again
  5. Tells multiple arguments apart
  6. Three calls on the page needed one computation
03

Hints

0/3
Track lessons0 of 8 done

Find out where your page really loses time, and how to win it back by adding elements in one go, making fewer calls and never computing the same thing twice.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Find out where your page really loses time, and how to win it back by adding elements in one go, making fewer calls and never computing the same thing twice.

Advanced level, 8 lessons, 1.5 hours in total.