fix(simulator): fix mocha tests
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
1 import crypto from 'node:crypto';
2 import util from 'node:util';
3
4 import clone from 'just-clone';
5
6 // import { Constants } from './internal';
7 import { Constants } from './Constants';
8 import { WebSocketCloseEventStatusString } from '../types';
9
10 export class Utils {
11 private constructor() {
12 // This is intentional
13 }
14
15 public static logPrefix = (prefixString = ''): string => {
16 return `${new Date().toLocaleString()}${prefixString}`;
17 };
18
19 public static generateUUID(): string {
20 return crypto.randomUUID();
21 }
22
23 public static validateUUID(uuid: string): boolean {
24 return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(
25 uuid
26 );
27 }
28
29 public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
30 return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
31 }
32
33 public static formatDurationMilliSeconds(duration: number): string {
34 duration = Utils.convertToInt(duration);
35 const hours = Math.floor(duration / (3600 * 1000));
36 const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
37 const seconds = duration / 1000 - hours * 3600 - minutes * 60;
38 let hoursStr = hours.toString();
39 let minutesStr = minutes.toString();
40 let secondsStr = seconds.toString();
41
42 if (hours < 10) {
43 hoursStr = `0${hours.toString()}`;
44 }
45 if (minutes < 10) {
46 minutesStr = `0${minutes.toString()}`;
47 }
48 if (seconds < 10) {
49 secondsStr = `0${seconds.toString()}`;
50 }
51 return `${hoursStr}:${minutesStr}:${secondsStr.substring(0, 6)}`;
52 }
53
54 public static formatDurationSeconds(duration: number): string {
55 return Utils.formatDurationMilliSeconds(duration * 1000);
56 }
57
58 public static convertToDate(
59 value: Date | string | number | null | undefined
60 ): Date | null | undefined {
61 if (Utils.isNullOrUndefined(value)) {
62 return value as null | undefined;
63 }
64 if (value instanceof Date) {
65 return value;
66 }
67 if (Utils.isString(value) || typeof value === 'number') {
68 return new Date(value);
69 }
70 return null;
71 }
72
73 public static convertToInt(value: unknown): number {
74 if (!value) {
75 return 0;
76 }
77 let changedValue: number = value as number;
78 if (Number.isSafeInteger(value)) {
79 return value as number;
80 }
81 if (typeof value === 'number') {
82 return Math.trunc(value);
83 }
84 if (Utils.isString(value)) {
85 changedValue = parseInt(value as string);
86 }
87 if (isNaN(changedValue)) {
88 throw new Error(`Cannot convert to integer: ${value.toString()}`);
89 }
90 return changedValue;
91 }
92
93 public static convertToFloat(value: unknown): number {
94 if (!value) {
95 return 0;
96 }
97 let changedValue: number = value as number;
98 if (Utils.isString(value)) {
99 changedValue = parseFloat(value as string);
100 }
101 if (isNaN(changedValue)) {
102 throw new Error(`Cannot convert to float: ${value.toString()}`);
103 }
104 return changedValue;
105 }
106
107 public static convertToBoolean(value: unknown): boolean {
108 let result = false;
109 if (value) {
110 // Check the type
111 if (typeof value === 'boolean') {
112 return value;
113 } else if (
114 Utils.isString(value) &&
115 ((value as string).toLowerCase() === 'true' || value === '1')
116 ) {
117 result = true;
118 } else if (typeof value === 'number' && value === 1) {
119 result = true;
120 }
121 }
122 return result;
123 }
124
125 public static getRandomFloat(max = Number.MAX_VALUE, min = 0): number {
126 if (max < min) {
127 throw new RangeError('Invalid interval');
128 }
129 if (max - min === Infinity) {
130 throw new RangeError('Invalid interval');
131 }
132 return (crypto.randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min;
133 }
134
135 public static getRandomInteger(max = Constants.MAX_RANDOM_INTEGER, min = 0): number {
136 max = Math.floor(max);
137 if (!Utils.isNullOrUndefined(min) && min !== 0) {
138 min = Math.ceil(min);
139 return Math.floor(crypto.randomInt(min, max + 1));
140 }
141 return Math.floor(crypto.randomInt(max + 1));
142 }
143
144 public static roundTo(numberValue: number, scale: number): number {
145 const roundPower = Math.pow(10, scale);
146 return Math.round(numberValue * roundPower) / roundPower;
147 }
148
149 public static truncTo(numberValue: number, scale: number): number {
150 const truncPower = Math.pow(10, scale);
151 return Math.trunc(numberValue * truncPower) / truncPower;
152 }
153
154 public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number {
155 if (min) {
156 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
157 }
158 return Utils.roundTo(Utils.getRandomFloat(max), scale);
159 }
160
161 public static getRandomFloatFluctuatedRounded(
162 staticValue: number,
163 fluctuationPercent: number,
164 scale = 2
165 ): number {
166 if (fluctuationPercent === 0) {
167 return Utils.roundTo(staticValue, scale);
168 }
169 const fluctuationRatio = fluctuationPercent / 100;
170 return Utils.getRandomFloatRounded(
171 staticValue * (1 + fluctuationRatio),
172 staticValue * (1 - fluctuationRatio),
173 scale
174 );
175 }
176
177 public static isObject(item: unknown): boolean {
178 return (
179 Utils.isNullOrUndefined(item) === false &&
180 typeof item === 'object' &&
181 Array.isArray(item) === false
182 );
183 }
184
185 public static cloneObject<T extends object>(object: T): T {
186 return clone<T>(object);
187 }
188
189 public static hasOwnProp(object: unknown, property: PropertyKey): boolean {
190 return Utils.isObject(object) && Object.hasOwn(object as object, property);
191 }
192
193 public static isCFEnvironment(): boolean {
194 return process.env.VCAP_APPLICATION !== undefined;
195 }
196
197 public static isIterable<T>(obj: T): boolean {
198 return !Utils.isNullOrUndefined(obj) ? typeof obj[Symbol.iterator] === 'function' : false;
199 }
200
201 public static isString(value: unknown): boolean {
202 return typeof value === 'string';
203 }
204
205 public static isEmptyString(value: unknown): boolean {
206 return (
207 Utils.isNullOrUndefined(value) ||
208 (Utils.isString(value) && (value as string).trim().length === 0)
209 );
210 }
211
212 public static isNotEmptyString(value: unknown): boolean {
213 return Utils.isString(value) && (value as string).trim().length > 0;
214 }
215
216 public static isUndefined(value: unknown): boolean {
217 return value === undefined;
218 }
219
220 public static isNullOrUndefined(value: unknown): boolean {
221 // eslint-disable-next-line eqeqeq, no-eq-null
222 return value == null;
223 }
224
225 public static isEmptyArray(object: unknown | unknown[]): boolean {
226 if (Array.isArray(object) && object.length === 0) {
227 return true;
228 }
229 return false;
230 }
231
232 public static isNotEmptyArray(object: unknown | unknown[]): boolean {
233 if (Array.isArray(object) && object.length > 0) {
234 return true;
235 }
236 return false;
237 }
238
239 public static isEmptyObject(obj: object): boolean {
240 if (obj?.constructor !== Object) {
241 return false;
242 }
243 // Iterates over the keys of an object, if
244 // any exist, return false.
245 for (const _ in obj) {
246 return false;
247 }
248 return true;
249 }
250
251 public static insertAt = (str: string, subStr: string, pos: number): string =>
252 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
253
254 /**
255 * @param retryNumber - the number of retries that have already been attempted
256 * @returns delay in milliseconds
257 */
258 public static exponentialDelay(retryNumber = 0): number {
259 const delay = Math.pow(2, retryNumber) * 100;
260 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
261 return delay + randomSum;
262 }
263
264 public static isPromisePending(promise: Promise<unknown>): boolean {
265 return util.inspect(promise).includes('pending');
266 }
267
268 public static async promiseWithTimeout<T>(
269 promise: Promise<T>,
270 timeoutMs: number,
271 timeoutError: Error,
272 timeoutCallback: () => void = () => {
273 /* This is intentional */
274 }
275 ): Promise<T> {
276 // Create a timeout promise that rejects in timeout milliseconds
277 const timeoutPromise = new Promise<never>((_, reject) => {
278 setTimeout(() => {
279 if (Utils.isPromisePending(promise)) {
280 timeoutCallback();
281 // FIXME: The original promise shall be canceled
282 }
283 reject(timeoutError);
284 }, timeoutMs);
285 });
286
287 // Returns a race between timeout promise and the passed promise
288 return Promise.race<T>([promise, timeoutPromise]);
289 }
290
291 /**
292 * Generate a cryptographically secure random number in the [0,1[ range
293 *
294 * @returns
295 */
296 public static secureRandom(): number {
297 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
298 }
299
300 public static JSONStringifyWithMapSupport(
301 obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
302 space?: number
303 ): string {
304 return JSON.stringify(
305 obj,
306 (key, value: Record<string, unknown>) => {
307 if (value instanceof Map) {
308 return {
309 dataType: 'Map',
310 value: [...value],
311 };
312 }
313 return value;
314 },
315 space
316 );
317 }
318
319 /**
320 * Convert websocket error code to human readable string message
321 *
322 * @param code - websocket error code
323 * @returns human readable string message
324 */
325 public static getWebSocketCloseEventStatusString(code: number): string {
326 if (code >= 0 && code <= 999) {
327 return '(Unused)';
328 } else if (code >= 1016) {
329 if (code <= 1999) {
330 return '(For WebSocket standard)';
331 } else if (code <= 2999) {
332 return '(For WebSocket extensions)';
333 } else if (code <= 3999) {
334 return '(For libraries and frameworks)';
335 } else if (code <= 4999) {
336 return '(For applications)';
337 }
338 }
339 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
340 return WebSocketCloseEventStatusString[code] as string;
341 }
342 return '(Unknown)';
343 }
344 }