build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
1 import { randomBytes, randomInt, randomUUID, webcrypto } from 'node:crypto';
2 import { env, nextTick } from 'node:process';
3 import { inspect } from 'node:util';
4
5 import {
6 formatDuration,
7 hoursToMinutes,
8 hoursToSeconds,
9 isDate,
10 millisecondsToHours,
11 millisecondsToMinutes,
12 millisecondsToSeconds,
13 minutesToSeconds,
14 secondsToMilliseconds,
15 } from 'date-fns';
16
17 import { Constants } from './Constants';
18 import { type TimestampedData, WebSocketCloseEventStatusString } from '../types';
19
20 export const logPrefix = (prefixString = ''): string => {
21 return `${new Date().toLocaleString()}${prefixString}`;
22 };
23
24 export const generateUUID = (): string => {
25 return randomUUID();
26 };
27
28 export const validateUUID = (uuid: string): boolean => {
29 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(
30 uuid,
31 );
32 };
33
34 export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
35 return new Promise<NodeJS.Timeout>((resolve) => setTimeout(resolve as () => void, milliSeconds));
36 };
37
38 export const formatDurationMilliSeconds = (duration: number): string => {
39 duration = convertToInt(duration);
40 if (duration < 0) {
41 throw new RangeError('Duration cannot be negative');
42 }
43 const days = Math.floor(duration / (24 * 3600 * 1000));
44 const hours = Math.floor(millisecondsToHours(duration) - days * 24);
45 const minutes = Math.floor(
46 millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours),
47 );
48 const seconds = Math.floor(
49 millisecondsToSeconds(duration) -
50 days * 24 * 3600 -
51 hoursToSeconds(hours) -
52 minutesToSeconds(minutes),
53 );
54 if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) {
55 return formatDuration({ seconds }, { zero: true });
56 }
57 return formatDuration({
58 days,
59 hours,
60 minutes,
61 seconds,
62 });
63 };
64
65 export const formatDurationSeconds = (duration: number): string => {
66 return formatDurationMilliSeconds(secondsToMilliseconds(duration));
67 };
68
69 // More efficient time validation function than the one provided by date-fns
70 export const isValidTime = (date: unknown): boolean => {
71 if (typeof date === 'number') {
72 return !isNaN(date);
73 } else if (isDate(date)) {
74 return !isNaN((date as Date).getTime());
75 }
76 return false;
77 };
78
79 export const convertToDate = (value: Date | string | number | undefined): Date | undefined => {
80 if (isNullOrUndefined(value)) {
81 return value as undefined;
82 }
83 if (isDate(value)) {
84 return value as Date;
85 }
86 if (isString(value) || typeof value === 'number') {
87 const valueToDate = new Date(value as string | number);
88 if (isNaN(valueToDate.getTime())) {
89 throw new Error(`Cannot convert to date: '${value as string | number}'`);
90 }
91 return valueToDate;
92 }
93 };
94
95 export const convertToInt = (value: unknown): number => {
96 if (!value) {
97 return 0;
98 }
99 let changedValue: number = value as number;
100 if (Number.isSafeInteger(value)) {
101 return value as number;
102 }
103 if (typeof value === 'number') {
104 return Math.trunc(value);
105 }
106 if (isString(value)) {
107 changedValue = parseInt(value as string);
108 }
109 if (isNaN(changedValue)) {
110 throw new Error(`Cannot convert to integer: '${String(value)}'`);
111 }
112 return changedValue;
113 };
114
115 export const convertToFloat = (value: unknown): number => {
116 if (!value) {
117 return 0;
118 }
119 let changedValue: number = value as number;
120 if (isString(value)) {
121 changedValue = parseFloat(value as string);
122 }
123 if (isNaN(changedValue)) {
124 throw new Error(`Cannot convert to float: '${String(value)}'`);
125 }
126 return changedValue;
127 };
128
129 export const convertToBoolean = (value: unknown): boolean => {
130 let result = false;
131 if (value) {
132 // Check the type
133 if (typeof value === 'boolean') {
134 return value;
135 } else if (isString(value) && ((value as string).toLowerCase() === 'true' || value === '1')) {
136 result = true;
137 } else if (typeof value === 'number' && value === 1) {
138 result = true;
139 }
140 }
141 return result;
142 };
143
144 export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => {
145 if (max < min) {
146 throw new RangeError('Invalid interval');
147 }
148 if (max - min === Infinity) {
149 throw new RangeError('Invalid interval');
150 }
151 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min;
152 };
153
154 export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => {
155 max = Math.floor(max);
156 if (!isNullOrUndefined(min) && min !== 0) {
157 min = Math.ceil(min);
158 return Math.floor(randomInt(min, max + 1));
159 }
160 return Math.floor(randomInt(max + 1));
161 };
162
163 /**
164 * Rounds the given number to the given scale.
165 * The rounding is done using the "round half away from zero" method.
166 *
167 * @param numberValue - The number to round.
168 * @param scale - The scale to round to.
169 * @returns The rounded number.
170 */
171 export const roundTo = (numberValue: number, scale: number): number => {
172 const roundPower = Math.pow(10, scale);
173 return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower;
174 };
175
176 export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => {
177 if (min) {
178 return roundTo(getRandomFloat(max, min), scale);
179 }
180 return roundTo(getRandomFloat(max), scale);
181 };
182
183 export const getRandomFloatFluctuatedRounded = (
184 staticValue: number,
185 fluctuationPercent: number,
186 scale = 2,
187 ): number => {
188 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
189 throw new RangeError(
190 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
191 );
192 }
193 if (fluctuationPercent === 0) {
194 return roundTo(staticValue, scale);
195 }
196 const fluctuationRatio = fluctuationPercent / 100;
197 return getRandomFloatRounded(
198 staticValue * (1 + fluctuationRatio),
199 staticValue * (1 - fluctuationRatio),
200 scale,
201 );
202 };
203
204 export const extractTimeSeriesValues = (timeSeries: Array<TimestampedData>): number[] => {
205 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
206 };
207
208 export const isObject = (item: unknown): boolean => {
209 return (
210 isNullOrUndefined(item) === false && typeof item === 'object' && Array.isArray(item) === false
211 );
212 };
213
214 type CloneableData =
215 | number
216 | string
217 | boolean
218 | null
219 | undefined
220 | Date
221 | CloneableData[]
222 | { [key: string]: CloneableData };
223
224 type FormatKey = (key: string) => string;
225
226 const deepClone = <I extends CloneableData, O extends CloneableData = I>(
227 value: I,
228 formatKey?: FormatKey,
229 refs: Map<I, O> = new Map<I, O>(),
230 ): O => {
231 const ref = refs.get(value);
232 if (ref !== undefined) {
233 return ref;
234 }
235 if (Array.isArray(value)) {
236 const clone: CloneableData[] = [];
237 refs.set(value, clone as O);
238 for (let i = 0; i < value.length; i++) {
239 clone[i] = deepClone(value[i], formatKey, refs);
240 }
241 return clone as O;
242 }
243 if (value instanceof Date) {
244 return new Date(value.valueOf()) as O;
245 }
246 if (typeof value !== 'object' || value === null) {
247 return value as unknown as O;
248 }
249 const clone: Record<string, CloneableData> = {};
250 refs.set(value, clone as O);
251 for (const key of Object.keys(value)) {
252 clone[typeof formatKey === 'function' ? formatKey(key) : key] = deepClone(
253 value[key],
254 formatKey,
255 refs,
256 );
257 }
258 return clone as O;
259 };
260
261 export const cloneObject = <T>(object: T): T => {
262 return deepClone(object as CloneableData) as T;
263 };
264
265 export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => {
266 return isObject(object) && Object.hasOwn(object as object, property);
267 };
268
269 export const isCFEnvironment = (): boolean => {
270 return !isNullOrUndefined(env.VCAP_APPLICATION);
271 };
272
273 export const isIterable = <T>(obj: T): boolean => {
274 return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false;
275 };
276
277 const isString = (value: unknown): boolean => {
278 return typeof value === 'string';
279 };
280
281 export const isEmptyString = (value: unknown): boolean => {
282 return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0);
283 };
284
285 export const isNotEmptyString = (value: unknown): boolean => {
286 return isString(value) && (value as string).trim().length > 0;
287 };
288
289 export const isUndefined = (value: unknown): boolean => {
290 return value === undefined;
291 };
292
293 export const isNullOrUndefined = (value: unknown): boolean => {
294 // eslint-disable-next-line eqeqeq, no-eq-null
295 return value == null;
296 };
297
298 export const isEmptyArray = (object: unknown): boolean => {
299 return Array.isArray(object) && object.length === 0;
300 };
301
302 export const isNotEmptyArray = (object: unknown): boolean => {
303 return Array.isArray(object) && object.length > 0;
304 };
305
306 export const isEmptyObject = (obj: object): boolean => {
307 if (obj?.constructor !== Object) {
308 return false;
309 }
310 // Iterates over the keys of an object, if
311 // any exist, return false.
312 for (const _ in obj) {
313 return false;
314 }
315 return true;
316 };
317
318 export const insertAt = (str: string, subStr: string, pos: number): string =>
319 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
320
321 /**
322 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
323 *
324 * @param retryNumber - the number of retries that have already been attempted
325 * @param delayFactor - the base delay factor in milliseconds
326 * @returns delay in milliseconds
327 */
328 export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
329 const delay = Math.pow(2, retryNumber) * delayFactor;
330 const randomSum = delay * 0.2 * secureRandom(); // 0-20% of the delay
331 return delay + randomSum;
332 };
333
334 const isPromisePending = (promise: Promise<unknown>): boolean => {
335 return inspect(promise).includes('pending');
336 };
337
338 export const promiseWithTimeout = async <T>(
339 promise: Promise<T>,
340 timeoutMs: number,
341 timeoutError: Error,
342 timeoutCallback: () => void = () => {
343 /* This is intentional */
344 },
345 ): Promise<T> => {
346 // Creates a timeout promise that rejects in timeout milliseconds
347 const timeoutPromise = new Promise<never>((_, reject) => {
348 setTimeout(() => {
349 if (isPromisePending(promise)) {
350 timeoutCallback();
351 // FIXME: The original promise shall be canceled
352 }
353 reject(timeoutError);
354 }, timeoutMs);
355 });
356
357 // Returns a race between timeout promise and the passed promise
358 return Promise.race<T>([promise, timeoutPromise]);
359 };
360
361 /**
362 * Generates a cryptographically secure random number in the [0,1[ range
363 *
364 * @returns A number in the [0,1[ range
365 */
366 export const secureRandom = (): number => {
367 return webcrypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
368 };
369
370 export const JSONStringifyWithMapSupport = (
371 obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
372 space?: number,
373 ): string => {
374 return JSON.stringify(
375 obj,
376 (_, value: Record<string, unknown>) => {
377 if (value instanceof Map) {
378 return {
379 dataType: 'Map',
380 value: [...value],
381 };
382 }
383 return value;
384 },
385 space,
386 );
387 };
388
389 /**
390 * Converts websocket error code to human readable string message
391 *
392 * @param code - websocket error code
393 * @returns human readable string message
394 */
395 export const getWebSocketCloseEventStatusString = (code: number): string => {
396 if (code >= 0 && code <= 999) {
397 return '(Unused)';
398 } else if (code >= 1016) {
399 if (code <= 1999) {
400 return '(For WebSocket standard)';
401 } else if (code <= 2999) {
402 return '(For WebSocket extensions)';
403 } else if (code <= 3999) {
404 return '(For libraries and frameworks)';
405 } else if (code <= 4999) {
406 return '(For applications)';
407 }
408 }
409 if (
410 !isUndefined(
411 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString],
412 )
413 ) {
414 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString];
415 }
416 return '(Unknown)';
417 };
418
419 export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => {
420 for (let index = 0; index < array.length - 1; ++index) {
421 if (compareFn(array[index], array[index + 1]) > 0) {
422 return false;
423 }
424 }
425 return true;
426 };
427
428 // eslint-disable-next-line @typescript-eslint/no-explicit-any
429 export const once = <T, A extends any[], R>(
430 fn: (...args: A) => R,
431 context: T,
432 ): ((...args: A) => R) => {
433 let result: R;
434 return (...args: A) => {
435 if (fn) {
436 result = fn.apply<T, A, R>(context, args);
437 (fn as unknown as undefined) = (context as unknown as undefined) = undefined;
438 }
439 return result;
440 };
441 };
442
443 export const min = (...args: number[]): number =>
444 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity);
445
446 export const max = (...args: number[]): number =>
447 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity);
448
449 export const throwErrorInNextTick = (error: Error): void => {
450 nextTick(() => {
451 throw error;
452 });
453 };