Memoize a function and confirm it only really runs once.
Acceptance criteria
- 1.#out should show 1.
JavaScript Tutorial · JavaScript Performance
These 10 tasks go with the JavaScript Memoization chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “Memoization caches a function's results so the same input never does the same work twice.” .
1.Cache a function's resultexercise · easy · 10 min
Memoize a function and confirm it only really runs once.
Passes when: #out should show 1.
2.Return the cached valueexercise · easy · 10 min · practice plan
Confirm the memoized function still returns the right answer.
Passes when: #out should show 16.
3.Cache different inputs separatelyexercise · easy · 10 min · practice plan
Call with two different inputs and count the real calls.
Passes when: #out should show 2.
4.Speed up recursive Fibonacciexercise · easy · 10 min · practice plan
Memoize a recursive Fibonacci and get a value that would be slow otherwise.
Passes when: #out should show 6765.
5.Build a key from two argumentsexercise · medium · 10 min · practice plan
Memoize a two-argument function using a combined key.
Passes when: #out should show 1.
6.Fix the cache never checkedbug fix · easy · 8 min
Without checking the cache first, every call runs the real function.
Passes when: #out should show 1.
7.Fix the cache declared inside the wrapperbug fix · easy · 8 min · practice plan
A new cache on every call means nothing is ever remembered.
Passes when: #out should show 1.
8.Fix the two arguments sharing one keybug fix · easy · 8 min · practice plan
Different inputs must not overwrite each other in the cache.
Passes when: #out should show 2.
9.Fix an impure function memoizedbug fix · easy · 8 min · practice plan
Memoizing Math.random always returns the very first value forever.
Passes when: #out should show changes each time.
10.Fix the result stored before computing itbug fix · easy · 8 min · practice plan
The value must be computed before it can be cached.
Passes when: #out should show 16.
Between them these tasks cover Caching results, Map-based cache and Pure functions.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.