Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

index.js 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. const mimicFn = require('mimic-fn');
  3. const calledFunctions = new WeakMap();
  4. const onetime = (function_, options = {}) => {
  5. if (typeof function_ !== 'function') {
  6. throw new TypeError('Expected a function');
  7. }
  8. let returnValue;
  9. let callCount = 0;
  10. const functionName = function_.displayName || function_.name || '<anonymous>';
  11. const onetime = function (...arguments_) {
  12. calledFunctions.set(onetime, ++callCount);
  13. if (callCount === 1) {
  14. returnValue = function_.apply(this, arguments_);
  15. function_ = null;
  16. } else if (options.throw === true) {
  17. throw new Error(`Function \`${functionName}\` can only be called once`);
  18. }
  19. return returnValue;
  20. };
  21. mimicFn(onetime, function_);
  22. calledFunctions.set(onetime, callCount);
  23. return onetime;
  24. };
  25. module.exports = onetime;
  26. // TODO: Remove this for the next major release
  27. module.exports.default = onetime;
  28. module.exports.callCount = function_ => {
  29. if (!calledFunctions.has(function_)) {
  30. throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
  31. }
  32. return calledFunctions.get(function_);
  33. };