es-toolkit/docs/reference/function/once.md
Dayong Lee 22701d5c23
fix(before,once): allow accepting arguments for once and fix types of before and once (#647)
* Fix before once

* Fix lint error

* Apply suggestions from code review

Co-authored-by: Sojin Park <raon0211@gmail.com>

* Fix once

* Fix once types

---------

Co-authored-by: Sojin Park <raon0211@gmail.com>
2024-10-03 18:08:37 +09:00

725 B

once

Creates a function that is restricted to invoking the provided function func once. Repeated calls to the function will return the value from the first invocation.

Signature

function once<F extends () => any>(func: F): F;
function once<F extends (...args: any[]) => void>(func: F): F;

Parameters

  • func (F extends (() => any) | ((...args: any[]) => void)): The function to restrict.

Returns

(F): A new function that invokes func once and caches the result.

Examples

const initialize = once(() => {
  console.log('Initialized!');
  return true;
});

initialize(); // Logs: 'Initialized!' and returns true
initialize(); // Returns true without logging