UNPKG

1.45 kBMarkdownView Raw
1# onetime [![Build Status](https://travis-ci.org/sindresorhus/onetime.svg?branch=master)](https://travis-ci.org/sindresorhus/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
10## Install
11
12```
13$ npm install onetime
14```
15
16
17## Usage
18
19```js
20const onetime = require('onetime');
21
22let i = 0;
23
24const foo = onetime(() => ++i);
25
26foo(); //=> 0
27foo(); //=> 0
28foo(); //=> 0
29
30onetime.callCount(foo); //=> 3
31```
32
33```js
34const onetime = require('onetime');
35
36const foo = onetime(() => {}, {throw: true});
37
38foo();
39
40foo();
41//=> Error: Function `foo` can only be called once
42```
43
44
45## API
46
47### onetime(fn, [options])
48
49Returns a function that only calls `fn` once.
50
51#### fn
52
53Type: `Function`
54
55Function that should only be called once.
56
57#### options
58
59Type: `Object`
60
61##### throw
62
63Type: `boolean`<br>
64Default: `false`
65
66Throw an error when called more than once.
67
68### onetime.callCount(fn)
69
70Returns a number representing how many times `fn` has been called.
71
72Note: It throws an error if you pass in a function that is not wrapped by `onetime`.
73
74```js
75const foo = onetime(() => {});
76
77foo();
78foo();
79foo();
80
81console.log(onetime.callCount(foo));
82//=> 3
83```
84
85#### fn
86
87Type: `Function`
88
89Function to get call count from.
90
91
92## License
93
94MIT © [Sindre Sorhus](https://sindresorhus.com)