index.js 1.0 KB

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