index.js 924 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. /**
  3. * Wrap callbacks to prevent double execution.
  4. *
  5. * @param {Function} fn Function that should only be called once.
  6. * @returns {Function} A wrapped callback which prevents execution.
  7. * @api public
  8. */
  9. module.exports = function one(fn) {
  10. var called = 0
  11. , value;
  12. /**
  13. * The function that prevents double execution.
  14. *
  15. * @api private
  16. */
  17. function onetime() {
  18. if (called) return value;
  19. called = 1;
  20. value = fn.apply(this, arguments);
  21. fn = null;
  22. return value;
  23. }
  24. //
  25. // To make debugging more easy we want to use the name of the supplied
  26. // function. So when you look at the functions that are assigned to event
  27. // listeners you don't see a load of `onetime` functions but actually the
  28. // names of the functions that this module will call.
  29. //
  30. onetime.displayName = fn.displayName || fn.name || onetime.displayName || onetime.name;
  31. return onetime;
  32. };