es-toolkit/docs/reference/function/once.md
Minsoo Kim cf65b2c601
style(*): Setup prettier and apply formatting (#24)
* chore: add prettierrc

* chore: apply format with prettier config

* chore: eslint error fix
2024-06-04 17:19:26 +09:00

631 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;

Parameters

  • func (F extends () => any): 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