1 | 'use strict';
|
2 | const mimicFn = require('mimic-fn');
|
3 |
|
4 | const calledFunctions = new WeakMap();
|
5 |
|
6 | const oneTime = (fn, options = {}) => {
|
7 | if (typeof fn !== 'function') {
|
8 | throw new TypeError('Expected a function');
|
9 | }
|
10 |
|
11 | let ret;
|
12 | let isCalled = false;
|
13 | let callCount = 0;
|
14 | const functionName = fn.displayName || fn.name || '<anonymous>';
|
15 |
|
16 | const onetime = function (...args) {
|
17 | calledFunctions.set(onetime, ++callCount);
|
18 |
|
19 | if (isCalled) {
|
20 | if (options.throw === true) {
|
21 | throw new Error(`Function \`${functionName}\` can only be called once`);
|
22 | }
|
23 |
|
24 | return ret;
|
25 | }
|
26 |
|
27 | isCalled = true;
|
28 | ret = fn.apply(this, args);
|
29 | fn = null;
|
30 |
|
31 | return ret;
|
32 | };
|
33 |
|
34 | mimicFn(onetime, fn);
|
35 | calledFunctions.set(onetime, callCount);
|
36 |
|
37 | return onetime;
|
38 | };
|
39 |
|
40 | module.exports = oneTime;
|
41 |
|
42 | module.exports.default = oneTime;
|
43 |
|
44 | module.exports.callCount = fn => {
|
45 | if (!calledFunctions.has(fn)) {
|
46 | throw new Error(`The given function \`${fn.name}\` is not wrapped by the \`onetime\` package`);
|
47 | }
|
48 |
|
49 | return calledFunctions.get(fn);
|
50 | };
|