wishthis/node_modules/onetime/index.js

40 lines
709 B
JavaScript
Raw Normal View History

2022-01-21 08:28:41 +00:00
'use strict';
const mimicFn = require('mimic-fn');
2022-05-29 09:24:36 +00:00
module.exports = (fn, opts) => {
// TODO: Remove this in v3
if (opts === true) {
throw new TypeError('The second argument is now an options object');
}
2022-01-21 08:28:41 +00:00
2022-05-29 09:24:36 +00:00
if (typeof fn !== 'function') {
2022-01-21 08:28:41 +00:00
throw new TypeError('Expected a function');
}
2022-05-29 09:24:36 +00:00
opts = opts || {};
let ret;
let called = false;
const fnName = fn.displayName || fn.name || '<anonymous>';
2022-01-21 08:28:41 +00:00
2022-05-29 09:24:36 +00:00
const onetime = function () {
if (called) {
if (opts.throw === true) {
throw new Error(`Function \`${fnName}\` can only be called once`);
}
2022-01-21 08:28:41 +00:00
2022-05-29 09:24:36 +00:00
return ret;
2022-01-21 08:28:41 +00:00
}
2022-05-29 09:24:36 +00:00
called = true;
ret = fn.apply(this, arguments);
fn = null;
return ret;
2022-01-21 08:28:41 +00:00
};
2022-05-29 09:24:36 +00:00
mimicFn(onetime, fn);
2022-01-21 08:28:41 +00:00
return onetime;
};