onetime
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
mimic-fn | 2.1.0 | 2.07 kB | MIT | prod |
The "onetime" npm package is designed to ensure that a particular function in your JavaScript code is only called once. When the function wrapped by "onetime" is called multiple times, it returns the return value from the first call, effectively enforcing its execution once. This can be useful in avoiding recurring calls to the same function, saving computational resources and helping to maintain cleaner, more efficient code.
Installing and using "onetime" is straightforward. Firstly, you'll need to add it to your project with npm:
$ npm install onetime
Here is a basic example of how to use "onetime":
import onetime from 'onetime';
let index = 0;
const foo = onetime(() => ++index);
foo(); //=> 1
foo(); //=> 1
foo(); //=> 1
onetime.callCount(foo); //=> 3
In this case, the foo
function increments the index
variable. However, despite foo
being called thrice, the resulting value is '1', proving that the function only actually executed once. Then, the onetime.callCount(foo)
checks how many times foo
has been called, returning '3'.
You can also opt to throw an error when a function is called more than once:
import onetime from 'onetime';
const foo = onetime(() => {}, {throw: true});
foo();
foo();
//=> Error: Function `foo` can only be called once
In this case, calling foo
a second time throws an error, making it explicit when the function is mistakenly called more than once.
The documentation for the "onetime" npm package can be found within its README file on the GitHub repository. The README file provides a comprehensive description of the functionality, including the API methods onetime(fn, options?)
and onetime.callCount(fn)
. It also provides usage examples for learning purposes. You may access the official docs here. Make sure to fully read the documentation to understand all the capabilities of the "onetime" npm package.