Overview
Implement once(fn) — returns a function that calls fn at most once. Subsequent calls return the first result.
Examples
const add = once((a, b) => a + b); add(1, 2); // 3 add(3, 4); // 3
Solution
Reveal solution
function once(fn) {
let called = false, result;
return function(...args) {
if (!called) { called = true; result = fn.apply(this, args); }
return result;
};
}once.js
Once
easycodingJavaScriptFunctions
Overview
Implement once(fn) — returns a function that calls fn at most once. Subsequent calls return the first result.
Examples
const add = once((a, b) => a + b); add(1, 2); // 3 add(3, 4); // 3
Solution
Reveal solution
function once(fn) {
let called = false, result;
return function(...args) {
if (!called) { called = true; result = fn.apply(this, args); }
return result;
};
}NameTopicDifficulty
103 of 103 problems