Skip to content
SDETRole
SDETRole

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 calls fn the first time only. Every later call returns the first call’s result without calling fn again.
  • memoize(fn) returns a function that caches results per argument list, so the same arguments never cause a second call to fn.
  • Both wrappers forward this and all arguments to fn.
  • 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.

Type to search across SDETRole.

Full-text search by Pagefind · runs in your browser Open search page →