once() and memoize()
intermediate Closures Challenge 7 of 18
Implement two higher-order functions that rely on closures.
Requirements
once(fn)returns a function that callsfnthe first time only. Every later call returns the first call’s result without callingfnagain.memoize(fn)returns a function that caches results per argument list, so the same arguments never cause a second call tofn.- Both wrappers forward
thisand all arguments tofn. - Cached results that are falsy (
0,'',undefined) must still count as cached.
Expected output
const init = once(() => 42); init(); init() → 42, and the wrapped function ran once const sq = memoize((n) => n * n); sq(4); sq(4) → 16, computed once
Test cases (6)
- ○once calls the function only one time
- ○once returns the first result on later calls
- ○once forwards this and arguments
- ○memoize caches by arguments
- ○memoize distinguishes multiple arguments
- ○memoize caches falsy results
solution.jsExecutes in your browser
Ctrl/⌘ + Enter to run tests · your code is saved in this browser
Results
Run the tests to see results here.