JavaScript utilities · Core · about 10 minutes
Once
Implement once(fn). The returned function runs fn on the first call, with that call's arguments and this, and gives back that same result on every later call without running fn again. A first result of undefined still counts. Two functions made by once are independent. The answer shows the results and how many times fn ran.
Start from
function once(fn) {
// Return a function that runs fn only the first time.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Keep a flag and the result in the closure.
Hint 2
Use a separate boolean for 'already ran'. Testing the result itself fails when fn returns undefined.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function once(fn) {
let done = false;
let result;
return function (...args) {
if (!done) {
done = true;
result = fn.apply(this, args);
}
return result;
};
}What an interviewer looks for
A warm-up that checks closures and attention to edge cases: the flag, this, and what later calls return.