Javascript Fundamentals · Interview Challenges

Run a function once

once

Run a function once

A user double-clicks a submit button, and the order goes out twice. A setup routine runs again on every render, re-opening a connection it already opened. Both want the same thing: do this the first time, and ignore every call after.

once wraps a function so it runs at most one time, no matter how many times the wrapper is called. The first call runs the original and keeps its result; every later call skips the original and returns that same first result. That is the run-once pattern.

The shape keeps a flag and the result in a closure:

function once(fn) {
  let called = false;
  let result;
  return (...args) => {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
}

called starts false, so the first call runs fn, stores its result, and sets called to true. From then on the guard is closed, fn is skipped, and the stored result is returned — so the wrapper is idempotent even when later calls pass different arguments. The flag lives in the closure, so every call of the returned function shares it; the guarantee is per wrapper, not global.

Export once from index.js. Your job is to make the wrapped function run at most one time and reuse its first result.

Challenge

A double-click sends the same submit twice, and a setup routine re-runs when it should not. Export a once function from index.js to make the wrapped function run at most one time.

once takes a function and returns a new function that runs the original at most one time: the first call runs it and stores the result, while every later call skips it and returns that stored result. Calling the returned function several times, even with different arguments, runs the original exactly once.

index.js
export function once(fn) {
  return (...args) => fn(...args);
}

export function render(mount) {
  let calls = 0;
  const greetOnce = once((name) => {
    calls += 1;
    return `Hi ${name}`;
  });

  const first = greetOnce('Ada');
  const second = greetOnce('Grace');

  const line = document.createElement('p');
  line.textContent = `${first}, then ${second} (calls: ${calls})`;
  mount.replaceChildren(line);
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.