index.js 709 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. const mimicFn = require('mimic-fn');
  3. module.exports = (fn, opts) => {
  4. // TODO: Remove this in v3
  5. if (opts === true) {
  6. throw new TypeError('The second argument is now an options object');
  7. }
  8. if (typeof fn !== 'function') {
  9. throw new TypeError('Expected a function');
  10. }
  11. opts = opts || {};
  12. let ret;
  13. let called = false;
  14. const fnName = fn.displayName || fn.name || '<anonymous>';
  15. const onetime = function () {
  16. if (called) {
  17. if (opts.throw === true) {
  18. throw new Error(`Function \`${fnName}\` can only be called once`);
  19. }
  20. return ret;
  21. }
  22. called = true;
  23. ret = fn.apply(this, arguments);
  24. fn = null;
  25. return ret;
  26. };
  27. mimicFn(onetime, fn);
  28. return onetime;
  29. };