Clean up the oopsie. Rebuild the blank exercises.

This commit is contained in:
Michael Frank
2021-05-09 00:39:21 +12:00
parent b984cb4c6f
commit d28d80c46f
1565 changed files with 27186 additions and 199003 deletions
+28 -23
View File
@@ -1,39 +1,44 @@
'use strict';
const mimicFn = require('mimic-fn');
module.exports = (fn, opts) => {
// TODO: Remove this in v3
if (opts === true) {
throw new TypeError('The second argument is now an options object');
}
const calledFunctions = new WeakMap();
if (typeof fn !== 'function') {
const onetime = (function_, options = {}) => {
if (typeof function_ !== 'function') {
throw new TypeError('Expected a function');
}
opts = opts || {};
let returnValue;
let callCount = 0;
const functionName = function_.displayName || function_.name || '<anonymous>';
let ret;
let called = false;
const fnName = fn.displayName || fn.name || '<anonymous>';
const onetime = function (...arguments_) {
calledFunctions.set(onetime, ++callCount);
const onetime = function () {
if (called) {
if (opts.throw === true) {
throw new Error(`Function \`${fnName}\` can only be called once`);
}
return ret;
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`);
}
called = true;
ret = fn.apply(this, arguments);
fn = null;
return ret;
return returnValue;
};
mimicFn(onetime, fn);
mimicFn(onetime, function_);
calledFunctions.set(onetime, callCount);
return onetime;
};
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_);
};