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