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