readme.md (1824B)
1 # 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 ## Install 10 11 ``` 12 $ npm install onetime 13 ``` 14 15 ## Usage 16 17 ```js 18 import onetime from 'onetime'; 19 20 let index = 0; 21 22 const foo = onetime(() => ++index); 23 24 foo(); //=> 1 25 foo(); //=> 1 26 foo(); //=> 1 27 28 onetime.callCount(foo); //=> 3 29 ``` 30 31 ```js 32 import onetime from 'onetime'; 33 34 const foo = onetime(() => {}, {throw: true}); 35 36 foo(); 37 38 foo(); 39 //=> Error: Function `foo` can only be called once 40 ``` 41 42 ## API 43 44 ### onetime(fn, options?) 45 46 Returns a function that only calls `fn` once. 47 48 #### fn 49 50 Type: `Function` 51 52 Function that should only be called once. 53 54 #### options 55 56 Type: `object` 57 58 ##### throw 59 60 Type: `boolean`\ 61 Default: `false` 62 63 Throw an error when called more than once. 64 65 ### onetime.callCount(fn) 66 67 Returns a number representing how many times `fn` has been called. 68 69 Note: It throws an error if you pass in a function that is not wrapped by `onetime`. 70 71 ```js 72 import onetime from 'onetime'; 73 74 const foo = onetime(() => {}); 75 76 foo(); 77 foo(); 78 foo(); 79 80 console.log(onetime.callCount(foo)); 81 //=> 3 82 ``` 83 84 #### fn 85 86 Type: `Function` 87 88 Function to get call count from. 89 90 ## onetime for enterprise 91 92 Available as part of the Tidelift Subscription. 93 94 The 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)