Overview
Wrap any function in another one to change how it behaves — here, a run-once guard like the ones apps put around their setup code.
- Functions as arguments and return values
- Forwarding arguments with ...args
- A flag remembered in a closure
Short Course
A higher-order function takes or returns a function. The trap when
remembering a result: keep a separate called flag, because the first result
may itself be undefined.
function logged(fn) {
return (...args) => {
console.log("calling with", args);
return fn(...args);
};
}
const add = logged((a, b) => a + b);
add(1, 2); // logs, then returns 3
Task
Write once(fn), which returns a function that calls fn (with its
arguments) only the first time and returns that first result on every later
call, e.g. add(2, 3) then add(10, 10) both return 5.
Test Suites
Pending
Next
Output