perf: convert deepClone() to arrow function
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
1 import { randomBytes, randomInt, randomUUID } from 'node:crypto';
2 import { inspect } from 'node:util';
3
4 import {
5 formatDuration,
6 hoursToMinutes,
7 hoursToSeconds,
8 isDate,
9 millisecondsToHours,
10 millisecondsToMinutes,
11 millisecondsToSeconds,
12 minutesToSeconds,
13 secondsToMilliseconds,
14 } from 'date-fns';
15
16 import { Constants } from './Constants';
17 import { type TimestampedData, WebSocketCloseEventStatusString } from '../types';
18
19 export const logPrefix = (prefixString = ''): string => {
20 return `${new Date().toLocaleString()}${prefixString}`;
21 };
22
23 export const generateUUID = (): string => {
24 return randomUUID();
25 };
26
27 export 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(
29 uuid,
30 );
31 };
32
33 export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
34 return new Promise<NodeJS.Timeout>((resolve) => setTimeout(resolve as () => void, milliSeconds));
35 };
36
37 export const formatDurationMilliSeconds = (duration: number): string => {
38 duration = convertToInt(duration);
39 const days = Math.floor(duration / (24 * 3600 * 1000));
40 const hours = Math.floor(millisecondsToHours(duration) - days * 24);
41 const minutes = Math.floor(
42 millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours),
43 );
44 const seconds = Math.floor(
45 millisecondsToSeconds(duration) -
46 days * 24 * 3600 -
47 hoursToSeconds(hours) -
48 minutesToSeconds(minutes),
49 );
50 return formatDuration({
51 days,
52 hours,
53 minutes,
54 seconds,
55 });
56 };
57
58 export const formatDurationSeconds = (duration: number): string => {
59 return formatDurationMilliSeconds(secondsToMilliseconds(duration));
60 };
61
62 // More efficient time validation function than the one provided by date-fns
63 export const isValidTime = (date: unknown): boolean => {
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
72 export const convertToDate = (value: Date | string | number | undefined): Date | undefined => {
73 if (isNullOrUndefined(value)) {
74 return value as undefined;
75 }
76 if (isDate(value)) {
77 return value as Date;
78 }
79 if (isString(value) || typeof value === 'number') {
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}'`);
83 }
84 return valueToDate;
85 }
86 };
87
88 export const convertToInt = (value: unknown): number => {
89 if (!value) {
90 return 0;
91 }
92 let changedValue: number = value as number;
93 if (Number.isSafeInteger(value)) {
94 return value as number;
95 }
96 if (typeof value === 'number') {
97 return Math.trunc(value);
98 }
99 if (isString(value)) {
100 changedValue = parseInt(value as string);
101 }
102 if (isNaN(changedValue)) {
103 throw new Error(`Cannot convert to integer: '${String(value)}'`);
104 }
105 return changedValue;
106 };
107
108 export const convertToFloat = (value: unknown): number => {
109 if (!value) {
110 return 0;
111 }
112 let changedValue: number = value as number;
113 if (isString(value)) {
114 changedValue = parseFloat(value as string);
115 }
116 if (isNaN(changedValue)) {
117 throw new Error(`Cannot convert to float: '${String(value)}'`);
118 }
119 return changedValue;
120 };
121
122 export 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;
132 }
133 }
134 return result;
135 };
136
137 export 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
147 export 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 */
164 export 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
169 export 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
176 export const getRandomFloatFluctuatedRounded = (
177 staticValue: number,
178 fluctuationPercent: number,
179 scale = 2,
180 ): number => {
181 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
182 throw new RangeError(
183 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
184 );
185 }
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),
193 scale,
194 );
195 };
196
197 export const extractTimeSeriesValues = (timeSeries: Array<TimestampedData>): number[] => {
198 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
199 };
200
201 export const isObject = (item: unknown): boolean => {
202 return (
203 isNullOrUndefined(item) === false && typeof item === 'object' && Array.isArray(item) === false
204 );
205 };
206
207 type CloneableData =
208 | number
209 | string
210 | boolean
211 | null
212 | undefined
213 | Date
214 | CloneableData[]
215 | { [key: string]: CloneableData };
216
217 type FormatKey = (key: string) => string;
218
219 const deepClone = <I extends CloneableData, O extends CloneableData = I>(
220 value: I,
221 formatKey?: FormatKey,
222 refs: Map<I, O> = new Map<I, O>(),
223 ): O => {
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;
252 };
253
254 export const cloneObject = <T>(object: T): T => {
255 return deepClone(object as CloneableData) as T;
256 };
257
258 export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => {
259 return isObject(object) && Object.hasOwn(object as object, property);
260 };
261
262 export const isCFEnvironment = (): boolean => {
263 return !isNullOrUndefined(process.env.VCAP_APPLICATION);
264 };
265
266 export const isIterable = <T>(obj: T): boolean => {
267 return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false;
268 };
269
270 const isString = (value: unknown): boolean => {
271 return typeof value === 'string';
272 };
273
274 export const isEmptyString = (value: unknown): boolean => {
275 return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0);
276 };
277
278 export const isNotEmptyString = (value: unknown): boolean => {
279 return isString(value) && (value as string).trim().length > 0;
280 };
281
282 export const isUndefined = (value: unknown): boolean => {
283 return value === undefined;
284 };
285
286 export const isNullOrUndefined = (value: unknown): boolean => {
287 // eslint-disable-next-line eqeqeq, no-eq-null
288 return value == null;
289 };
290
291 export const isEmptyArray = (object: unknown): boolean => {
292 return Array.isArray(object) && object.length === 0;
293 };
294
295 export const isNotEmptyArray = (object: unknown): boolean => {
296 return Array.isArray(object) && object.length > 0;
297 };
298
299 export 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
311 export 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
318 * @param delayFactor - the base delay factor in milliseconds
319 * @returns delay in milliseconds
320 */
321 export 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
324 return delay + randomSum;
325 };
326
327 const isPromisePending = (promise: Promise<unknown>): boolean => {
328 return inspect(promise).includes('pending');
329 };
330
331 export const promiseWithTimeout = async <T>(
332 promise: Promise<T>,
333 timeoutMs: number,
334 timeoutError: Error,
335 timeoutCallback: () => void = () => {
336 /* This is intentional */
337 },
338 ): Promise<T> => {
339 // Creates a timeout promise that rejects in timeout milliseconds
340 const timeoutPromise = new Promise<never>((_, reject) => {
341 setTimeout(() => {
342 if (isPromisePending(promise)) {
343 timeoutCallback();
344 // FIXME: The original promise shall be canceled
345 }
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 */
359 export const secureRandom = (): number => {
360 return randomBytes(4).readUInt32LE() / 0x100000000;
361 };
362
363 export const JSONStringifyWithMapSupport = (
364 obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
365 space?: number,
366 ): string => {
367 return JSON.stringify(
368 obj,
369 (_, value: Record<string, unknown>) => {
370 if (value instanceof Map) {
371 return {
372 dataType: 'Map',
373 value: [...value],
374 };
375 }
376 return value;
377 },
378 space,
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 */
388 export 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)';
400 }
401 }
402 if (
403 !isUndefined(
404 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString],
405 )
406 ) {
407 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString];
408 }
409 return '(Unknown)';
410 };
411
412 export 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) {
415 return false;
416 }
417 }
418 return true;
419 };
420
421 // eslint-disable-next-line @typescript-eslint/no-explicit-any
422 export 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 };
435
436 export const min = (...args: number[]): number =>
437 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity);
438
439 export const max = (...args: number[]): number =>
440 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity);