X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FUtils.ts;h=6557a588446455506656c7f7133e8fe85c5881f0;hb=b40b5cb39eb44088100f2ce5efc2a6fdf4b84f26;hp=2fde488376ad9a2c74a75b86c925abf577c6353c;hpb=088ee3c1ea0466521948c3911da0db8517ea5b97;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 2fde4883..6557a588 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -1,7 +1,9 @@ -import crypto from 'crypto'; +import crypto from 'node:crypto'; +import util from 'node:util'; import clone from 'just-clone'; +import Constants from './Constants'; import { WebSocketCloseEventStatusString } from '../types/WebSocket'; export default class Utils { @@ -10,7 +12,7 @@ export default class Utils { } public static logPrefix(prefixString = ''): string { - return new Date().toLocaleString() + prefixString; + return `${new Date().toLocaleString()}${prefixString}`; } public static generateUUID(): string { @@ -37,22 +39,24 @@ export default class Utils { let secondsStr = seconds.toString(); if (hours < 10) { - hoursStr = '0' + hours.toString(); + hoursStr = `0${hours.toString()}`; } if (minutes < 10) { - minutesStr = '0' + minutes.toString(); + minutesStr = `0${minutes.toString()}`; } if (seconds < 10) { - secondsStr = '0' + seconds.toString(); + secondsStr = `0${seconds.toString()}`; } - return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6); + return `${hoursStr}:${minutesStr}:${secondsStr.substring(0, 6)}`; } public static formatDurationSeconds(duration: number): string { return Utils.formatDurationMilliSeconds(duration * 1000); } - public static convertToDate(value: unknown): Date | null | undefined { + public static convertToDate( + value: Date | string | number | null | undefined + ): Date | null | undefined { if (Utils.isNullOrUndefined(value)) { return value as null | undefined; } @@ -60,7 +64,7 @@ export default class Utils { return value; } if (Utils.isString(value) || typeof value === 'number') { - return new Date(value as string | number); + return new Date(value); } return null; } @@ -74,11 +78,14 @@ export default class Utils { return value as number; } if (typeof value === 'number') { - changedValue = Math.trunc(value); + return Math.trunc(value); } if (Utils.isString(value)) { changedValue = parseInt(value as string); } + if (isNaN(changedValue)) { + throw new Error(`Cannot convert to integer: ${value.toString()}`); + } return changedValue; } @@ -90,6 +97,9 @@ export default class Utils { if (Utils.isString(value)) { changedValue = parseFloat(value as string); } + if (isNaN(changedValue)) { + throw new Error(`Cannot convert to float: ${value.toString()}`); + } return changedValue; } @@ -98,7 +108,7 @@ export default class Utils { if (value) { // Check the type if (typeof value === 'boolean') { - result = value; + return value; } else if ( Utils.isString(value) && ((value as string).toLowerCase() === 'true' || value === '1') @@ -120,16 +130,13 @@ export default class Utils { return sign * (randomPositiveFloat * (max - min) + min); } - public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number { - if (max < min || max < 0 || min < 0) { - throw new RangeError('Invalid interval'); - } + public static getRandomInteger(max = Constants.MAX_RANDOM_INTEGER, min = 0): number { max = Math.floor(max); if (!Utils.isNullOrUndefined(min) && min !== 0) { min = Math.ceil(min); - return Math.floor(Utils.secureRandom() * (max - min + 1)) + min; + return Math.floor(crypto.randomInt(min, max + 1)); } - return Math.floor(Utils.secureRandom() * (max + 1)); + return Math.floor(crypto.randomInt(max + 1)); } public static roundTo(numberValue: number, scale: number): number { @@ -165,12 +172,20 @@ export default class Utils { ); } + public static isObject(item: unknown): boolean { + return ( + Utils.isNullOrUndefined(item) === false && + typeof item === 'object' && + Array.isArray(item) === false + ); + } + public static cloneObject(object: T): T { return clone(object); } - public static isIterable(obj: T): boolean { - return obj ? typeof obj[Symbol.iterator] === 'function' : false; + public static isIterable>(obj: T): boolean { + return !Utils.isNullOrUndefined(obj) ? typeof obj[Symbol.iterator] === 'function' : false; } public static isString(value: unknown): boolean { @@ -182,7 +197,7 @@ export default class Utils { } public static isUndefined(value: unknown): boolean { - return typeof value === 'undefined'; + return value === undefined; } public static isNullOrUndefined(value: unknown): boolean { @@ -216,7 +231,7 @@ export default class Utils { `${str.slice(0, pos)}${subStr}${str.slice(pos)}`; /** - * @param [retryNumber=0] + * @param retryNumber - the number of retries that have already been attempted * @returns delay in milliseconds */ public static exponentialDelay(retryNumber = 0): number { @@ -225,6 +240,10 @@ export default class Utils { return delay + randomSum; } + public static isPromisePending(promise: Promise): boolean { + return util.inspect(promise).includes('pending'); + } + public static async promiseWithTimeout( promise: Promise, timeoutMs: number, @@ -236,7 +255,10 @@ export default class Utils { // Create a timeout promise that rejects in timeout milliseconds const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { - timeoutCallback(); + if (Utils.isPromisePending(promise)) { + timeoutCallback(); + // FIXME: The original promise shall be canceled + } reject(timeoutError); }, timeoutMs); }); @@ -255,7 +277,7 @@ export default class Utils { } public static JSONStringifyWithMapSupport( - obj: Record | Record[], + obj: Record | Record[] | Map, space?: number ): string { return JSON.stringify( @@ -276,7 +298,7 @@ export default class Utils { /** * Convert websocket error code to human readable string message * - * @param code websocket error code + * @param code - websocket error code * @returns human readable string message */ public static getWebSocketCloseEventStatusString(code: number): string {