JavaScript · Level 3 Functions

Higher-Order Functions

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

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

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.

solution.js
Test Suites Pending
Output