X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FUtils.ts;h=502401263e2d8b89097857a59e084dcabc837f22;hb=1fe16c9c1f11b81be83aa2059ecefe63e524929d;hp=3782beeb306148c90914b2de216b584b07311cbf;hpb=a3868ec4e6c4782ba51066ddbba74f9730dbba19;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 3782beeb..50240126 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -104,11 +104,11 @@ export default class Utils { throw new RangeError('Invalid interval'); } const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff; - const sign = (negative && randomPositiveFloat < 0.5) ? 1 : -1; + const sign = (negative && randomPositiveFloat < 0.5) ? -1 : 1; return sign * (randomPositiveFloat * (max - min) + min); } - public static getRandomInt(max: number, min = 0): number { + public static getRandomInteger(max: number, min = 0): number { if (max < 0) { throw new RangeError('Invalid interval'); } @@ -235,6 +235,24 @@ export default class Utils { return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL; } + public static async promiseWithTimeout( + promise: Promise, + timeoutMs: number, + timeoutError: Error, + timeoutCallback: () => void = () => { /* This is intentional */ } + ): Promise { + // Create a timeout promise that rejects in timeout milliseconds + const timeoutPromise = new Promise((_, reject) => { + setTimeout(() => { + timeoutCallback(); + reject(timeoutError); + }, timeoutMs); + }); + + // Returns a race between timeout promise and the passed promise + return Promise.race([promise, timeoutPromise]); + } + /** * Generate a cryptographically secure random number in the [0,1[ range *