UNPKG

1.06 kBJavaScriptView Raw
1'use strict';
2const mimicFn = require('mimic-fn');
3
4const calledFunctions = new WeakMap();
5
6const 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
40module.exports = oneTime;
41// TODO: Remove this for the next major release
42module.exports.default = oneTime;
43
44module.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};