UNPKG

1.82 kBMarkdownView Raw
1# onetime
2
3> Ensure a function is only called once
4
5When called multiple times it will return the return value from the first call.
6
7*Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty and extending `Function.prototype`.*
8
9## Install
10
11```
12$ npm install onetime
13```
14
15## Usage
16
17```js
18import onetime from 'onetime';
19
20let index = 0;
21
22const foo = onetime(() => ++index);
23
24foo(); //=> 1
25foo(); //=> 1
26foo(); //=> 1
27
28onetime.callCount(foo); //=> 3
29```
30
31```js
32import onetime from 'onetime';
33
34const foo = onetime(() => {}, {throw: true});
35
36foo();
37
38foo();
39//=> Error: Function `foo` can only be called once
40```
41
42## API
43
44### onetime(fn, options?)
45
46Returns a function that only calls `fn` once.
47
48#### fn
49
50Type: `Function`
51
52Function that should only be called once.
53
54#### options
55
56Type: `object`
57
58##### throw
59
60Type: `boolean`\
61Default: `false`
62
63Throw an error when called more than once.
64
65### onetime.callCount(fn)
66
67Returns a number representing how many times `fn` has been called.
68
69Note: It throws an error if you pass in a function that is not wrapped by `onetime`.
70
71```js
72import onetime from 'onetime';
73
74const foo = onetime(() => {});
75
76foo();
77foo();
78foo();
79
80console.log(onetime.callCount(foo));
81//=> 3
82```
83
84#### fn
85
86Type: `Function`
87
88Function to get call count from.
89
90## onetime for enterprise
91
92Available as part of the Tidelift Subscription.
93
94The maintainers of onetime and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-onetime?utm_source=npm-onetime&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)