Wrap a function so it runs once and caches its result
Some setup work must happen exactly once no matter how many places ask for it: loading an analytics script, opening a database connection, registering a service worker. Callers should be able to call the setup function freely and always get the same result back.
Implement once(fn). It returns a new function that calls fn the first time it is called and returns the result. Every later call returns that same result without calling fn again.
once(fn) // => wrapped function
this value to fn.undefined, null, or a promise (the same promise object is returned).fn throws, the wrapper rethrows the same error and does not remember the call. The next call tries fn again. Only a call that returns normally is remembered.once creates an independent wrapper, even for the same fn.let connections = 0;
const connect = once((host) => {
connections++;
return { host, id: connections };
});
connect('db-eu-1'); // => { host: 'db-eu-1', id: 1 }
connect('db-us-2'); // => the same object: { host: 'db-eu-1', id: 1 }
connections; // => 1
const widget = {
name: 'chat',
mount: once(function () {
return `mounted ${this.name}`;
}),
};
widget.mount(); // => 'mounted chat'
let attempts = 0;
const loadConfig = once(() => {
attempts++;
if (attempts === 1) throw new Error('network down');
return { region: 'eu' };
});
loadConfig(); // throws Error('network down')
loadConfig(); // => { region: 'eu' }
loadConfig(); // => the same object; attempts is still 2