Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Memoized Selector

Derived Statehard

Course · Section 10: A Closer Look at Functions · Lecture 144: Closures

Implement `createSelector(fn)` returning a function that caches its last result and only recomputes when called with a different (by reference) argument, like a reselect selector.

Examples

Input: selector doubles state.value; call with s1, s1, then s2
Output: results [10, 10, 20], fn called 2 times
The repeated s1 call hits the cache; only new references recompute.

Sample tests

Input: recomputes only on new reference
Output: [10,10,20,2]
Input: same reference is cached
Output: 1

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Deep-comparing arguments defeats the cheap reference check selectors rely on.

Learning resources

  • React: Choosing the State Structure
Approach & explanation (try first)

A closure caches the last input and output, recomputing only on a new reference, which is how memoized selectors avoid redundant derived-state work.

Loading...
⌘/Ctrl + Enter

Run your code to see results.