UNPKG

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