1. 1 : /* eslint-disable @typescript-eslint/no-unused-vars */
  2. 2 : /// <reference path="./globals.d.ts" />
  3. 3 :
  4. 4 : interface Callable {
  5. 5 : (text: string): void;
  6. 6 : /**
  7. 7 : * indicator if this function was called
  8. 8 : */
  9. 9 : wasCalled?: boolean;
  10. 10 : }
  11. 11 :
  12. 12 : /**
  13. 13 : * Class Callable Decorator
  14. 14 : * @example
  15. 15 : * // definition for below classes
  16. 16 : * // can be called with `new`
  17. 17 : * new yourclass();
  18. 18 : * new yourclass(arg, arg1);
  19. 19 : * // can be called directly like function
  20. 20 : * yourclass();
  21. 21 : * yourclass(arg, arg1);
  22. 22 : */
  23. 23 : export interface ClassCallable extends Callable {
  24. 24 : new (...args: any[]): ClassDecorator;
  25. 25 : new (): ClassDecorator;
  26. 26 : }
  27. 27 :
  28. 28 : Function.prototype.once = function (this: Callable, param?) {
  29. 29 : if (!this.wasCalled) {
  30. 30 : this.apply(param);
  31. 31 : this.wasCalled = true;
  32. 32 : }
  33. 33 : };
  34. 34 :
  35. 35 : /**
  36. 36 : * Run the function only once
  37. 37 : * @param fn
  38. 38 : * @see {@link https://stackoverflow.com/a/41000535/6404439}
  39. 39 : * @returns
  40. 40 : */
  41. 41 : function runOnce(fn: Callable) {
  42. 42 : let done = false;
  43. 43 : return function (...args: any) {
  44. 44 : if (!done) {
  45. 45 : done = true;
  46. 46 : return fn.apply(this, args);
  47. 47 : }
  48. 48 : };
  49. 49 : }
  50. 50 :
  51. 51 : if (typeof module.exports != 'undefined') {
  52. 52 : module.exports = {
  53. 53 : runOnce,
  54. 54 : };
  55. 55 : }