Scriptdrill

Level 5: Async and functions Exercise 41 of 45 Pro

Memoize

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

`fn` takes one argument. Return a function that computes `fn(x)` only the first time it sees `x` and returns the stored result after that. Arguments are told apart the way a `Map` tells keys apart, so `1` and `"1"` are different. Results such as `0`, `false` and `undefined` are cached too. Each memoized function has its own cache.

What this exercise teaches

A Map keeps keys with their type, which a plain object would turn into strings. Asking has() rather than testing the cached value keeps falsy results cached, and creating the Map inside memoize gives every memoized function its own cache.

A hint if you get stuck

Create a `new Map()` inside `memoize`. In the returned function, use `cache.has(x)` (not the stored value) to decide whether to call `fn`.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Async and functions