github-pages-deploy-action/node_modules/onetime/index.js

40 lines
709 B
JavaScript
Raw Normal View History

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