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