Skip to content

once

Create a function that runs at most once

169 bytes

Usage

Create a wrapper around a given function such that it executes at most once. Subsequent calls to the wrapped function return the result from the first execution, regardless of the arguments provided. This behavior is akin to memoization but specifically designed for single-use functions. The result of the first call is stored internally, allowing for efficient retrieval without recomputation.

import * as _ from 'radashi'
const fn = once(() => Math.random())
fn() // 0.5
fn() // 0.5

Resetting the function

The once.reset function clears the stored result of a function that was previously wrapped with once. This allows the function to be executed again as if it were never called before, enabling dynamic reuse of the function with fresh computations.

import * as _ from 'radashi'
const fn = once(() => Math.random())
fn() // 0.5
fn() // 0.5
once.reset(fn)
fn() // 0.3
fn() // 0.3