UNPKG

1.02 kBJavaScriptView Raw
1import mimicFunction from 'mimic-fn';
2
3const calledFunctions = new WeakMap();
4
5const onetime = (function_, options = {}) => {
6 if (typeof function_ !== 'function') {
7 throw new TypeError('Expected a function');
8 }
9
10 let returnValue;
11 let callCount = 0;
12 const functionName = function_.displayName || function_.name || '<anonymous>';
13
14 const onetime = function (...arguments_) {
15 calledFunctions.set(onetime, ++callCount);
16
17 if (callCount === 1) {
18 returnValue = function_.apply(this, arguments_);
19 function_ = null;
20 } else if (options.throw === true) {
21 throw new Error(`Function \`${functionName}\` can only be called once`);
22 }
23
24 return returnValue;
25 };
26
27 mimicFunction(onetime, function_);
28 calledFunctions.set(onetime, callCount);
29
30 return onetime;
31};
32
33onetime.callCount = function_ => {
34 if (!calledFunctions.has(function_)) {
35 throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
36 }
37
38 return calledFunctions.get(function_);
39};
40
41export default onetime;