2 const mimicFn = require('mimic-fn');
4 const calledFunctions = new WeakMap();
6 const oneTime = (fn, options = {}) => {
7 if (typeof fn !== 'function') {
8 throw new TypeError('Expected a function');
14 const functionName = fn.displayName || fn.name || '<anonymous>';
16 const onetime = function (...args) {
17 calledFunctions.set(onetime, ++callCount);
20 if (options.throw === true) {
21 throw new Error(`Function \`${functionName}\` can only be called once`);
28 ret = fn.apply(this, args);
35 calledFunctions.set(onetime, callCount);
40 module.exports = oneTime;
41 // TODO: Remove this for the next major release
42 module.exports.default = oneTime;
44 module.exports.callCount = fn => {
45 if (!calledFunctions.has(fn)) {
46 throw new Error(`The given function \`${fn.name}\` is not wrapped by the \`onetime\` package`);
49 return calledFunctions.get(fn);