index.js 608 B

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. module.exports = function (fn, errMsg) {
  3. if (typeof fn !== 'function') {
  4. throw new TypeError('Expected a function');
  5. }
  6. var ret;
  7. var called = false;
  8. var fnName = fn.displayName || fn.name || (/function ([^\(]+)/.exec(fn.toString()) || [])[1];
  9. var onetime = function () {
  10. if (called) {
  11. if (errMsg === true) {
  12. fnName = fnName ? fnName + '()' : 'Function';
  13. throw new Error(fnName + ' can only be called once.');
  14. }
  15. return ret;
  16. }
  17. called = true;
  18. ret = fn.apply(this, arguments);
  19. fn = null;
  20. return ret;
  21. };
  22. onetime.displayName = fnName;
  23. return onetime;
  24. };