Run A Function Only Once

Wrap sync and async functions so initialization runs at most once, sharing the cached result or in-flight promise.

JavascriptResilience

Code

snippet
export function once(fn) {
  if (typeof fn !== "function") throw new TypeError("fn must be a function");
  let called = false;
  let result;
  return function onceWrapper(...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

export function onceAsync(fn) {
  if (typeof fn !== "function") throw new TypeError("fn must be a function");
  let promise;
  return function onceAsyncWrapper(...args) {
    if (!promise) {
      promise = Promise.resolve().then(() => fn.apply(this, args));
    }
    return promise;
  };
}