es-next-tools
Version:
A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.
24 lines (23 loc) • 600 B
JavaScript
/**
* Creates a function that is restricted to invoking the original function only once.
* @param {T} fn - The function to restrict.
* @returns {T} The new restricted function.
* @template T
* @example
* let count = 0;
* const incrementOnce = once(() => ++count);
* console.log(incrementOnce()); // 1
* console.log(incrementOnce()); // 1
* console.log(count); // 1
*/
export function once(fn) {
let hasRun = false;
let result;
return ((...args) => {
if (!hasRun) {
hasRun = true;
result = fn(...args);
}
return result;
});
}