Full answer
Higher-order functions take or return functions. Utility wrappers show closures at work, because the wrapper keeps private state (a counter or a result) between calls.
once(fn): the first call runs fn and stores the result. Later calls return the stored result without calling fn. Keep a called flag, and keep the result, so that a function that returns undefined is not run again. Set the reference to fn to null after the first call so the original can be garbage collected.
before(n, fn): allow the first n - 1 calls to run fn, then keep returning the last result. after(n, fn): ignore the first n - 1 calls, and run fn from call number n onward. A common use of after is to run a callback once all of n tasks have reported in.
negate(predicate): returns a function that gives the opposite boolean, so items.filter(negate(isEven)) reads well.
unary(fn): calls fn with only the first argument. This fixes ['1', '2', '3'].map(parseInt), which returns [1, NaN, NaN]. map calls the function with the value, the index, and the array, and parseInt reads the index as the radix. The same trap affects any function with optional second parameters.
Implementation rules for all of them: return a regular function and use fn.apply(this, args) so that methods keep their this; copy extra properties only if needed; and do not share state between separate wrappers, which a closure per call of the utility gives you for free. If the wrapped function can throw, decide whether once should cache the failure or run again. The usual choice is that a failed first call does not count, but state it clearly.
These utilities are also the building blocks of memoize, debounce, and retry wrappers.
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
result = fn.apply(this, args);
called = true;
fn = null;
}
return result;
};
}
const before = (n, fn) => {
let calls = 0;
let result;
return function (...args) {
if (++calls < n) result = fn.apply(this, args);
return result;
};
};
const after = (n, fn) => {
let calls = 0;
return function (...args) {
if (++calls >= n) return fn.apply(this, args);
};
};
const negate = (predicate) => function (...args) {
return !predicate.apply(this, args);
};
const unary = (fn) => function (first) {
return fn.call(this, first);
};
let initialized = 0;
const init = once(() => ++initialized);
console.log(init(), init(), init(), 'run count:', initialized);
const returnsNothing = once(() => { initialized++; });
returnsNothing();
returnsNothing();
console.log('function returning undefined ran once:', initialized === 2);
const log = [];
const firstTwo = before(3, (x) => { log.push('before ' + x); return x; });
console.log(firstTwo('a'), firstTwo('b'), firstTwo('c'), firstTwo('d'), log);
const done = after(3, () => 'all three reported');
console.log(done(), done(), done(), done());
const isEven = (n) => n % 2 === 0;
console.log([1, 2, 3, 4, 5].filter(negate(isEven)));
console.log(['1', '2', '3'].map(parseInt), ['1', '2', '3'].map(unary(parseInt)));
const user = { name: 'Asha', greet: once(function () { return 'hi ' + this.name; }) };
console.log(user.greet(), user.greet());Run with Node.js v24.22.1 as js-123.js; two runs gave identical output. Output: 1 1 1 run count: 1 function returning undefined ran once: true a b b b [ 'before a', 'before b' ] undefined undefined all three reported all three reported [ 1, 3, 5 ] [ 1, NaN, NaN ] [ 1, 2, 3 ] hi Asha hi Asha
Key points
- Wrappers take a function, return a function, and keep state in a closure.
- once caches the result with a flag, not by checking for undefined.
- before limits and after delays the calls of the original; after is useful to wait for n results.
- negate flips a predicate; unary fixes map with parseInt.
- Use a regular function and apply to preserve this; decide how errors count for once.
Common mistakes
- Using an arrow function wrapper and losing this for methods.
- Detecting the first call with result being undefined, so functions that return undefined run again.
- Forgetting that map passes index and array to the callback.
- Sharing one counter across wrappers instead of one closure each.
Follow-ups
- How would you write once so that a failed first call can be retried?
- What other callbacks have the map and parseInt problem?
- How would you build debounce from these ideas?
Tips
- Explain that the closure holds the state.
- Use map with parseInt as the motivating example for unary.
- Mention this and arguments preservation.