Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Run Once

A Closer Look at Functionsmedium

Course · Section 10: A Closer Look at Functions · Lecture 139: Functions Returning Functions

Implement `once(fn)` returning a function that invokes `fn` only on its first call and returns that first result on every later call.

Examples

Input: init runs a side effect; const f = once(init); f(); f()
Output: both return 'done', side effect runs once
The wrapped function executes only on the first call.

Sample tests

Input: runs fn once, caches result
Output: ["done","done",1]
Input: ignores later arguments
Output: [10,10]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Returning undefined on later calls instead of the cached first result.
Visualize this concept: Currying →
Approach & explanation (try first)

A closure flag ensures fn runs only the first time; the stored result is returned thereafter.

Loading...
⌘/Ctrl + Enter

Run your code to see results.