index.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import mimicFunction from 'mimic-function';
  2. const calledFunctions = new WeakMap();
  3. const onetime = (function_, options = {}) => {
  4. if (typeof function_ !== 'function') {
  5. throw new TypeError('Expected a function');
  6. }
  7. let returnValue;
  8. let callCount = 0;
  9. const functionName = function_.displayName || function_.name || '<anonymous>';
  10. const onetime = function (...arguments_) {
  11. calledFunctions.set(onetime, ++callCount);
  12. if (callCount === 1) {
  13. returnValue = function_.apply(this, arguments_);
  14. function_ = undefined;
  15. } else if (options.throw === true) {
  16. throw new Error(`Function \`${functionName}\` can only be called once`);
  17. }
  18. return returnValue;
  19. };
  20. mimicFunction(onetime, function_);
  21. calledFunctions.set(onetime, callCount);
  22. return onetime;
  23. };
  24. onetime.callCount = function_ => {
  25. if (!calledFunctions.has(function_)) {
  26. throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
  27. }
  28. return calledFunctions.get(function_);
  29. };
  30. export default onetime;