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