fix(simulator): handle close to zero duration formatting
[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);
17b07e47
JB
40 if (duration < 0) {
41 throw new RangeError('Duration cannot be negative');
42 }
a675e34b 43 const days = Math.floor(duration / (24 * 3600 * 1000));
f0c6601c 44 const hours = Math.floor(millisecondsToHours(duration) - days * 24);
be4c6702
JB
45 const minutes = Math.floor(
46 millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours),
47 );
f0c6601c 48 const seconds = Math.floor(
be4c6702
JB
49 millisecondsToSeconds(duration) -
50 days * 24 * 3600 -
51 hoursToSeconds(hours) -
52 minutesToSeconds(minutes),
f0c6601c 53 );
17b07e47
JB
54 return formatDuration(
55 {
56 days,
57 hours,
58 minutes,
59 seconds,
60 },
61 { zero: true },
62 );
9bf0ef23 63};
7dde0b73 64
9bf0ef23 65export const formatDurationSeconds = (duration: number): string => {
a675e34b 66 return formatDurationMilliSeconds(secondsToMilliseconds(duration));
9bf0ef23 67};
7dde0b73 68
0bd926c1
JB
69// More efficient time validation function than the one provided by date-fns
70export const isValidTime = (date: unknown): boolean => {
b5c19509
JB
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
85cce27f 79export const convertToDate = (value: Date | string | number | undefined): Date | undefined => {
9bf0ef23 80 if (isNullOrUndefined(value)) {
85cce27f 81 return value as undefined;
7dde0b73 82 }
0bd926c1
JB
83 if (isDate(value)) {
84 return value as Date;
a6e68f34 85 }
9bf0ef23 86 if (isString(value) || typeof value === 'number') {
85cce27f
JB
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}'`);
43ff25b8 90 }
85cce27f 91 return valueToDate;
560bcf5b 92 }
9bf0ef23 93};
560bcf5b 94
9bf0ef23
JB
95export const convertToInt = (value: unknown): number => {
96 if (!value) {
97 return 0;
560bcf5b 98 }
9bf0ef23
JB
99 let changedValue: number = value as number;
100 if (Number.isSafeInteger(value)) {
101 return value as number;
6d3a11a0 102 }
9bf0ef23
JB
103 if (typeof value === 'number') {
104 return Math.trunc(value);
7dde0b73 105 }
9bf0ef23
JB
106 if (isString(value)) {
107 changedValue = parseInt(value as string);
9ccca265 108 }
9bf0ef23 109 if (isNaN(changedValue)) {
85cce27f 110 throw new Error(`Cannot convert to integer: '${String(value)}'`);
dada83ec 111 }
9bf0ef23
JB
112 return changedValue;
113};
dada83ec 114
9bf0ef23
JB
115export const convertToFloat = (value: unknown): number => {
116 if (!value) {
117 return 0;
dada83ec 118 }
9bf0ef23
JB
119 let changedValue: number = value as number;
120 if (isString(value)) {
121 changedValue = parseFloat(value as string);
560bcf5b 122 }
9bf0ef23 123 if (isNaN(changedValue)) {
85cce27f 124 throw new Error(`Cannot convert to float: '${String(value)}'`);
5a2a53cf 125 }
9bf0ef23
JB
126 return changedValue;
127};
5a2a53cf 128
9bf0ef23
JB
129export 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;
e7aeea18 139 }
c37528f1 140 }
9bf0ef23
JB
141 return result;
142};
143
144export 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
154export 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 */
171export 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
176export 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
183export const getRandomFloatFluctuatedRounded = (
184 staticValue: number,
185 fluctuationPercent: number,
5edd8ba0 186 scale = 2,
9bf0ef23
JB
187): number => {
188 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
189 throw new RangeError(
5edd8ba0 190 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
fe791818
JB
191 );
192 }
9bf0ef23
JB
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),
5edd8ba0 200 scale,
9bf0ef23
JB
201 );
202};
203
da55bd34
JB
204export const extractTimeSeriesValues = (timeSeries: Array<TimestampedData>): number[] => {
205 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
206};
207
9bf0ef23
JB
208export const isObject = (item: unknown): boolean => {
209 return (
210 isNullOrUndefined(item) === false && typeof item === 'object' && Array.isArray(item) === false
211 );
212};
213
32f5e42d
JB
214type CloneableData =
215 | number
216 | string
217 | boolean
218 | null
219 | undefined
220 | Date
221 | CloneableData[]
222 | { [key: string]: CloneableData };
223
661ac64b
JB
224type FormatKey = (key: string) => string;
225
015f3404 226const deepClone = <I extends CloneableData, O extends CloneableData = I>(
661ac64b
JB
227 value: I,
228 formatKey?: FormatKey,
229 refs: Map<I, O> = new Map<I, O>(),
015f3404 230): O => {
661ac64b
JB
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;
015f3404 259};
661ac64b 260
32f5e42d 261export const cloneObject = <T>(object: T): T => {
32f5e42d 262 return deepClone(object as CloneableData) as T;
9bf0ef23
JB
263};
264
265export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => {
266 return isObject(object) && Object.hasOwn(object as object, property);
267};
268
269export const isCFEnvironment = (): boolean => {
10687422 270 return !isNullOrUndefined(env.VCAP_APPLICATION);
9bf0ef23
JB
271};
272
273export const isIterable = <T>(obj: T): boolean => {
a37fc6dc 274 return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false;
9bf0ef23
JB
275};
276
277const isString = (value: unknown): boolean => {
278 return typeof value === 'string';
279};
280
281export const isEmptyString = (value: unknown): boolean => {
282 return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0);
283};
284
285export const isNotEmptyString = (value: unknown): boolean => {
286 return isString(value) && (value as string).trim().length > 0;
287};
288
289export const isUndefined = (value: unknown): boolean => {
290 return value === undefined;
291};
292
293export const isNullOrUndefined = (value: unknown): boolean => {
294 // eslint-disable-next-line eqeqeq, no-eq-null
295 return value == null;
296};
297
298export const isEmptyArray = (object: unknown): boolean => {
299 return Array.isArray(object) && object.length === 0;
300};
301
302export const isNotEmptyArray = (object: unknown): boolean => {
303 return Array.isArray(object) && object.length > 0;
304};
305
306export 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
318export 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
45abd3c6 325 * @param delayFactor - the base delay factor in milliseconds
9bf0ef23
JB
326 * @returns delay in milliseconds
327 */
45abd3c6
JB
328export 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
9bf0ef23
JB
331 return delay + randomSum;
332};
333
334const isPromisePending = (promise: Promise<unknown>): boolean => {
335 return inspect(promise).includes('pending');
336};
337
338export const promiseWithTimeout = async <T>(
339 promise: Promise<T>,
340 timeoutMs: number,
341 timeoutError: Error,
342 timeoutCallback: () => void = () => {
343 /* This is intentional */
5edd8ba0 344 },
9bf0ef23 345): Promise<T> => {
20558952 346 // Creates a timeout promise that rejects in timeout milliseconds
9bf0ef23
JB
347 const timeoutPromise = new Promise<never>((_, reject) => {
348 setTimeout(() => {
349 if (isPromisePending(promise)) {
350 timeoutCallback();
351 // FIXME: The original promise shall be canceled
5e3cb728 352 }
9bf0ef23
JB
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 *
ab93b184 364 * @returns A number in the [0,1[ range
9bf0ef23
JB
365 */
366export const secureRandom = (): number => {
ab93b184 367 return webcrypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
9bf0ef23
JB
368};
369
370export const JSONStringifyWithMapSupport = (
371 obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
5edd8ba0 372 space?: number,
9bf0ef23
JB
373): string => {
374 return JSON.stringify(
375 obj,
58ddf341 376 (_, value: Record<string, unknown>) => {
9bf0ef23
JB
377 if (value instanceof Map) {
378 return {
379 dataType: 'Map',
380 value: [...value],
381 };
382 }
383 return value;
384 },
5edd8ba0 385 space,
9bf0ef23
JB
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 */
395export 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)';
5e3cb728 407 }
5e3cb728 408 }
a37fc6dc
JB
409 if (
410 !isUndefined(
411 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString],
412 )
413 ) {
414 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString];
9bf0ef23
JB
415 }
416 return '(Unknown)';
417};
80c58041 418
991fb26b
JB
419export 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) {
80c58041
JB
422 return false;
423 }
424 }
425 return true;
426};
5f742aac
JB
427
428// eslint-disable-next-line @typescript-eslint/no-explicit-any
429export 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};
5adf6ca4
JB
442
443export const min = (...args: number[]): number =>
444 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity);
445
446export const max = (...args: number[]): number =>
447 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity);