fix: add date validation check in date conversion helper
[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';
32f5e42d 15import deepClone from 'deep-clone';
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
9bf0ef23 73export const convertToDate = (
5edd8ba0 74 value: Date | string | number | null | undefined,
9bf0ef23
JB
75): Date | null | undefined => {
76 if (isNullOrUndefined(value)) {
77 return value as null | undefined;
7dde0b73 78 }
0bd926c1
JB
79 if (isDate(value)) {
80 return value as Date;
a6e68f34 81 }
9bf0ef23 82 if (isString(value) || typeof value === 'number') {
43ff25b8
JB
83 value = new Date(value as string | number);
84 if (isNaN(value.getTime())) {
85 throw new Error(`Cannot convert to date: ${String(value)}`);
86 }
87 return value;
560bcf5b 88 }
9bf0ef23
JB
89 return null;
90};
560bcf5b 91
9bf0ef23
JB
92export const convertToInt = (value: unknown): number => {
93 if (!value) {
94 return 0;
560bcf5b 95 }
9bf0ef23
JB
96 let changedValue: number = value as number;
97 if (Number.isSafeInteger(value)) {
98 return value as number;
6d3a11a0 99 }
9bf0ef23
JB
100 if (typeof value === 'number') {
101 return Math.trunc(value);
7dde0b73 102 }
9bf0ef23
JB
103 if (isString(value)) {
104 changedValue = parseInt(value as string);
9ccca265 105 }
9bf0ef23 106 if (isNaN(changedValue)) {
43ff25b8 107 throw new Error(`Cannot convert to integer: ${String(value)}`);
dada83ec 108 }
9bf0ef23
JB
109 return changedValue;
110};
dada83ec 111
9bf0ef23
JB
112export const convertToFloat = (value: unknown): number => {
113 if (!value) {
114 return 0;
dada83ec 115 }
9bf0ef23
JB
116 let changedValue: number = value as number;
117 if (isString(value)) {
118 changedValue = parseFloat(value as string);
560bcf5b 119 }
9bf0ef23 120 if (isNaN(changedValue)) {
43ff25b8 121 throw new Error(`Cannot convert to float: ${String(value)}`);
5a2a53cf 122 }
9bf0ef23
JB
123 return changedValue;
124};
5a2a53cf 125
9bf0ef23
JB
126export const convertToBoolean = (value: unknown): boolean => {
127 let result = false;
128 if (value) {
129 // Check the type
130 if (typeof value === 'boolean') {
131 return value;
132 } else if (isString(value) && ((value as string).toLowerCase() === 'true' || value === '1')) {
133 result = true;
134 } else if (typeof value === 'number' && value === 1) {
135 result = true;
e7aeea18 136 }
c37528f1 137 }
9bf0ef23
JB
138 return result;
139};
140
141export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => {
142 if (max < min) {
143 throw new RangeError('Invalid interval');
144 }
145 if (max - min === Infinity) {
146 throw new RangeError('Invalid interval');
147 }
148 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min;
149};
150
151export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => {
152 max = Math.floor(max);
153 if (!isNullOrUndefined(min) && min !== 0) {
154 min = Math.ceil(min);
155 return Math.floor(randomInt(min, max + 1));
156 }
157 return Math.floor(randomInt(max + 1));
158};
159
160/**
161 * Rounds the given number to the given scale.
162 * The rounding is done using the "round half away from zero" method.
163 *
164 * @param numberValue - The number to round.
165 * @param scale - The scale to round to.
166 * @returns The rounded number.
167 */
168export const roundTo = (numberValue: number, scale: number): number => {
169 const roundPower = Math.pow(10, scale);
170 return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower;
171};
172
173export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => {
174 if (min) {
175 return roundTo(getRandomFloat(max, min), scale);
176 }
177 return roundTo(getRandomFloat(max), scale);
178};
179
180export const getRandomFloatFluctuatedRounded = (
181 staticValue: number,
182 fluctuationPercent: number,
5edd8ba0 183 scale = 2,
9bf0ef23
JB
184): number => {
185 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
186 throw new RangeError(
5edd8ba0 187 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
fe791818
JB
188 );
189 }
9bf0ef23
JB
190 if (fluctuationPercent === 0) {
191 return roundTo(staticValue, scale);
192 }
193 const fluctuationRatio = fluctuationPercent / 100;
194 return getRandomFloatRounded(
195 staticValue * (1 + fluctuationRatio),
196 staticValue * (1 - fluctuationRatio),
5edd8ba0 197 scale,
9bf0ef23
JB
198 );
199};
200
da55bd34
JB
201export const extractTimeSeriesValues = (timeSeries: Array<TimestampedData>): number[] => {
202 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
203};
204
9bf0ef23
JB
205export const isObject = (item: unknown): boolean => {
206 return (
207 isNullOrUndefined(item) === false && typeof item === 'object' && Array.isArray(item) === false
208 );
209};
210
32f5e42d
JB
211type CloneableData =
212 | number
213 | string
214 | boolean
215 | null
216 | undefined
217 | Date
218 | CloneableData[]
219 | { [key: string]: CloneableData };
220
221export const cloneObject = <T>(object: T): T => {
222 // eslint-disable-next-line @typescript-eslint/no-unsafe-call
223 return deepClone(object as CloneableData) as T;
9bf0ef23
JB
224};
225
226export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => {
227 return isObject(object) && Object.hasOwn(object as object, property);
228};
229
230export const isCFEnvironment = (): boolean => {
231 return !isNullOrUndefined(process.env.VCAP_APPLICATION);
232};
233
234export const isIterable = <T>(obj: T): boolean => {
a37fc6dc 235 return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false;
9bf0ef23
JB
236};
237
238const isString = (value: unknown): boolean => {
239 return typeof value === 'string';
240};
241
242export const isEmptyString = (value: unknown): boolean => {
243 return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0);
244};
245
246export const isNotEmptyString = (value: unknown): boolean => {
247 return isString(value) && (value as string).trim().length > 0;
248};
249
250export const isUndefined = (value: unknown): boolean => {
251 return value === undefined;
252};
253
254export const isNullOrUndefined = (value: unknown): boolean => {
255 // eslint-disable-next-line eqeqeq, no-eq-null
256 return value == null;
257};
258
259export const isEmptyArray = (object: unknown): boolean => {
260 return Array.isArray(object) && object.length === 0;
261};
262
263export const isNotEmptyArray = (object: unknown): boolean => {
264 return Array.isArray(object) && object.length > 0;
265};
266
267export const isEmptyObject = (obj: object): boolean => {
268 if (obj?.constructor !== Object) {
269 return false;
270 }
271 // Iterates over the keys of an object, if
272 // any exist, return false.
273 for (const _ in obj) {
274 return false;
275 }
276 return true;
277};
278
279export const insertAt = (str: string, subStr: string, pos: number): string =>
280 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
281
282/**
283 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
284 *
285 * @param retryNumber - the number of retries that have already been attempted
d467756c 286 * @param maxDelayRatio - the maximum ratio of the delay that can be randomized
9bf0ef23
JB
287 * @returns delay in milliseconds
288 */
289export const exponentialDelay = (retryNumber = 0, maxDelayRatio = 0.2): number => {
290 const delay = Math.pow(2, retryNumber) * 100;
d467756c 291 const randomSum = delay * maxDelayRatio * secureRandom(); // 0-(maxDelayRatio*100)% of the delay
9bf0ef23
JB
292 return delay + randomSum;
293};
294
295const isPromisePending = (promise: Promise<unknown>): boolean => {
296 return inspect(promise).includes('pending');
297};
298
299export const promiseWithTimeout = async <T>(
300 promise: Promise<T>,
301 timeoutMs: number,
302 timeoutError: Error,
303 timeoutCallback: () => void = () => {
304 /* This is intentional */
5edd8ba0 305 },
9bf0ef23
JB
306): Promise<T> => {
307 // Create a timeout promise that rejects in timeout milliseconds
308 const timeoutPromise = new Promise<never>((_, reject) => {
309 setTimeout(() => {
310 if (isPromisePending(promise)) {
311 timeoutCallback();
312 // FIXME: The original promise shall be canceled
5e3cb728 313 }
9bf0ef23
JB
314 reject(timeoutError);
315 }, timeoutMs);
316 });
317
318 // Returns a race between timeout promise and the passed promise
319 return Promise.race<T>([promise, timeoutPromise]);
320};
321
322/**
323 * Generates a cryptographically secure random number in the [0,1[ range
324 *
325 * @returns
326 */
327export const secureRandom = (): number => {
328 return randomBytes(4).readUInt32LE() / 0x100000000;
329};
330
331export const JSONStringifyWithMapSupport = (
332 obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
5edd8ba0 333 space?: number,
9bf0ef23
JB
334): string => {
335 return JSON.stringify(
336 obj,
58ddf341 337 (_, value: Record<string, unknown>) => {
9bf0ef23
JB
338 if (value instanceof Map) {
339 return {
340 dataType: 'Map',
341 value: [...value],
342 };
343 }
344 return value;
345 },
5edd8ba0 346 space,
9bf0ef23
JB
347 );
348};
349
350/**
351 * Converts websocket error code to human readable string message
352 *
353 * @param code - websocket error code
354 * @returns human readable string message
355 */
356export const getWebSocketCloseEventStatusString = (code: number): string => {
357 if (code >= 0 && code <= 999) {
358 return '(Unused)';
359 } else if (code >= 1016) {
360 if (code <= 1999) {
361 return '(For WebSocket standard)';
362 } else if (code <= 2999) {
363 return '(For WebSocket extensions)';
364 } else if (code <= 3999) {
365 return '(For libraries and frameworks)';
366 } else if (code <= 4999) {
367 return '(For applications)';
5e3cb728 368 }
5e3cb728 369 }
a37fc6dc
JB
370 if (
371 !isUndefined(
372 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString],
373 )
374 ) {
375 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString];
9bf0ef23
JB
376 }
377 return '(Unknown)';
378};
80c58041 379
991fb26b
JB
380export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => {
381 for (let index = 0; index < array.length - 1; ++index) {
382 if (compareFn(array[index], array[index + 1]) > 0) {
80c58041
JB
383 return false;
384 }
385 }
386 return true;
387};