wishthis/node_modules/onetime/index.js

45 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-01-21 08:28:41 +00:00
'use strict';
const mimicFn = require('mimic-fn');
2022-04-07 07:06:43 +00:00
const calledFunctions = new WeakMap();
2022-01-21 08:28:41 +00:00
2022-04-07 07:06:43 +00:00
const onetime = (function_, options = {}) => {
if (typeof function_ !== 'function') {
2022-01-21 08:28:41 +00:00
throw new TypeError('Expected a function');
}
2022-04-07 07:06:43 +00:00
let returnValue;
let callCount = 0;
const functionName = function_.displayName || function_.name || '<anonymous>';
2022-01-21 08:28:41 +00:00
2022-04-07 07:06:43 +00:00
const onetime = function (...arguments_) {
calledFunctions.set(onetime, ++callCount);
2022-01-21 08:28:41 +00:00
2022-04-07 07:06:43 +00:00
if (callCount === 1) {
returnValue = function_.apply(this, arguments_);
function_ = null;
} else if (options.throw === true) {
throw new Error(`Function \`${functionName}\` can only be called once`);
2022-01-21 08:28:41 +00:00
}
2022-04-07 07:06:43 +00:00
return returnValue;
2022-01-21 08:28:41 +00:00
};
2022-04-07 07:06:43 +00:00
mimicFn(onetime, function_);
calledFunctions.set(onetime, callCount);
2022-01-21 08:28:41 +00:00
return onetime;
};
2022-04-07 07:06:43 +00:00
module.exports = onetime;
// TODO: Remove this for the next major release
module.exports.default = onetime;
module.exports.callCount = function_ => {
if (!calledFunctions.has(function_)) {
throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
}
return calledFunctions.get(function_);
};