2 const mimicFn = require('mimic-fn');
4 const calledFunctions = new WeakMap();
6 const onetime = (function_, options = {}) => {
7 if (typeof function_ !== 'function') {
8 throw new TypeError('Expected a function');
13 const functionName = function_.displayName || function_.name || '<anonymous>';
15 const onetime = function (...arguments_) {
16 calledFunctions.set(onetime, ++callCount);
18 if (callCount === 1) {
19 returnValue = function_.apply(this, arguments_);
21 } else if (options.throw === true) {
22 throw new Error(`Function \`${functionName}\` can only be called once`);
28 mimicFn(onetime, function_);
29 calledFunctions.set(onetime, callCount);
34 module.exports = onetime;
35 // TODO: Remove this for the next major release
36 module.exports.default = onetime;
38 module.exports.callCount = function_ => {
39 if (!calledFunctions.has(function_)) {
40 throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
43 return calledFunctions.get(function_);