Function/Since
1.38.0once
Creates a function that invokes the given function only once and returns the result from the first invocation for all subsequent calls.
once(fn):(...args: TArgs) => TResultParameters
fn(...args: TArgs) => TResultrequiredThe function to invoke only once.
Returns
(...args: TArgs) => TResultReturns a function that executes the original function only on its first call and returns the stored result afterward.
Examples
01
Basic usage
The original function is executed only on the first call.
TypeScript
const initialize = once(() => {
console.log("Initialized");
return "ready";
});
console.log(initialize());
// Initialized
// ready
console.log(initialize());
// ready
console.log(initialize());
// ready02
First result is reused
After the first invocation, the stored result is returned even when later calls use different arguments.
TypeScript
const getValue = once((value: number) => value * 2);
console.log(getValue(5));
// 10
console.log(getValue(10));
// 10
console.log(getValue(20));
// 1003
Passing multiple arguments
All arguments from the first call are passed to the original function.
TypeScript
const createMessage = once(
(name: string, age: number) => {
return `${name} is ${age} years old`;
},
);
console.log(createMessage("Amir", 20));
// Amir is 20 years old
console.log(createMessage("Ali", 25));
// Amir is 20 years old04
Useful for initialization
once can be used when an operation should happen only during the first invocation.
TypeScript
const setup = once(() => {
console.log("Setup completed");
return true;
});
setup();
// Setup completed
setup();
// No output05
Original function is not called again
Once the function has been called, subsequent calls return the stored result without invoking the original function.
TypeScript
let count = 0;
const increment = once(() => {
count += 1;
return count;
});
console.log(increment());
// 1
console.log(increment());
// 1
console.log(count);
// 1Built with@cyref/js·Official documentation