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