fix: add date validation check in date conversion helper
[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 import deepClone from 'deep-clone';
16
17 import { Constants } from './Constants';
18 import { type TimestampedData, WebSocketCloseEventStatusString } from '../types';
19
20 export const logPrefix = (prefixString = ''): string => {
21 return `${new Date().toLocaleString()}${prefixString}`;
22 };
23
24 export const generateUUID = (): string => {
25 return randomUUID();
26 };
27
28 export 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(
30 uuid,
31 );
32 };
33
34 export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
35 return new Promise<NodeJS.Timeout>((resolve) => setTimeout(resolve as () => void, milliSeconds));
36 };
37
38 export const formatDurationMilliSeconds = (duration: number): string => {
39 duration = convertToInt(duration);
40 const days = Math.floor(duration / (24 * 3600 * 1000));
41 const hours = Math.floor(millisecondsToHours(duration) - days * 24);
42 const minutes = Math.floor(
43 millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours),
44 );
45 const seconds = Math.floor(
46 millisecondsToSeconds(duration) -
47 days * 24 * 3600 -
48 hoursToSeconds(hours) -
49 minutesToSeconds(minutes),
50 );
51 return formatDuration({
52 days,
53 hours,
54 minutes,
55 seconds,
56 });
57 };
58
59 export const formatDurationSeconds = (duration: number): string => {
60 return formatDurationMilliSeconds(secondsToMilliseconds(duration));
61 };
62
63 // More efficient time validation function than the one provided by date-fns
64 export const isValidTime = (date: unknown): boolean => {
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
73 export const convertToDate = (
74 value: Date | string | number | null | undefined,
75 ): Date | null | undefined => {
76 if (isNullOrUndefined(value)) {
77 return value as null | undefined;
78 }
79 if (isDate(value)) {
80 return value as Date;
81 }
82 if (isString(value) || typeof value === 'number') {
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;
88 }
89 return null;
90 };
91
92 export const convertToInt = (value: unknown): number => {
93 if (!value) {
94 return 0;
95 }
96 let changedValue: number = value as number;
97 if (Number.isSafeInteger(value)) {
98 return value as number;
99 }
100 if (typeof value === 'number') {
101 return Math.trunc(value);
102 }
103 if (isString(value)) {
104 changedValue = parseInt(value as string);
105 }
106 if (isNaN(changedValue)) {
107 throw new Error(`Cannot convert to integer: ${String(value)}`);
108 }
109 return changedValue;
110 };
111
112 export const convertToFloat = (value: unknown): number => {
113 if (!value) {
114 return 0;
115 }
116 let changedValue: number = value as number;
117 if (isString(value)) {
118 changedValue = parseFloat(value as string);
119 }
120 if (isNaN(changedValue)) {
121 throw new Error(`Cannot convert to float: ${String(value)}`);
122 }
123 return changedValue;
124 };
125
126 export 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;
136 }
137 }
138 return result;
139 };
140
141 export 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
151 export 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 */
168 export 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
173 export 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
180 export const getRandomFloatFluctuatedRounded = (
181 staticValue: number,
182 fluctuationPercent: number,
183 scale = 2,
184 ): number => {
185 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
186 throw new RangeError(
187 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
188 );
189 }
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),
197 scale,
198 );
199 };
200
201 export const extractTimeSeriesValues = (timeSeries: Array<TimestampedData>): number[] => {
202 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
203 };
204
205 export const isObject = (item: unknown): boolean => {
206 return (
207 isNullOrUndefined(item) === false && typeof item === 'object' && Array.isArray(item) === false
208 );
209 };
210
211 type CloneableData =
212 | number
213 | string
214 | boolean
215 | null
216 | undefined
217 | Date
218 | CloneableData[]
219 | { [key: string]: CloneableData };
220
221 export const cloneObject = <T>(object: T): T => {
222 // eslint-disable-next-line @typescript-eslint/no-unsafe-call
223 return deepClone(object as CloneableData) as T;
224 };
225
226 export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => {
227 return isObject(object) && Object.hasOwn(object as object, property);
228 };
229
230 export const isCFEnvironment = (): boolean => {
231 return !isNullOrUndefined(process.env.VCAP_APPLICATION);
232 };
233
234 export const isIterable = <T>(obj: T): boolean => {
235 return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false;
236 };
237
238 const isString = (value: unknown): boolean => {
239 return typeof value === 'string';
240 };
241
242 export const isEmptyString = (value: unknown): boolean => {
243 return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0);
244 };
245
246 export const isNotEmptyString = (value: unknown): boolean => {
247 return isString(value) && (value as string).trim().length > 0;
248 };
249
250 export const isUndefined = (value: unknown): boolean => {
251 return value === undefined;
252 };
253
254 export const isNullOrUndefined = (value: unknown): boolean => {
255 // eslint-disable-next-line eqeqeq, no-eq-null
256 return value == null;
257 };
258
259 export const isEmptyArray = (object: unknown): boolean => {
260 return Array.isArray(object) && object.length === 0;
261 };
262
263 export const isNotEmptyArray = (object: unknown): boolean => {
264 return Array.isArray(object) && object.length > 0;
265 };
266
267 export 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
279 export 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
286 * @param maxDelayRatio - the maximum ratio of the delay that can be randomized
287 * @returns delay in milliseconds
288 */
289 export const exponentialDelay = (retryNumber = 0, maxDelayRatio = 0.2): number => {
290 const delay = Math.pow(2, retryNumber) * 100;
291 const randomSum = delay * maxDelayRatio * secureRandom(); // 0-(maxDelayRatio*100)% of the delay
292 return delay + randomSum;
293 };
294
295 const isPromisePending = (promise: Promise<unknown>): boolean => {
296 return inspect(promise).includes('pending');
297 };
298
299 export const promiseWithTimeout = async <T>(
300 promise: Promise<T>,
301 timeoutMs: number,
302 timeoutError: Error,
303 timeoutCallback: () => void = () => {
304 /* This is intentional */
305 },
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
313 }
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 */
327 export const secureRandom = (): number => {
328 return randomBytes(4).readUInt32LE() / 0x100000000;
329 };
330
331 export const JSONStringifyWithMapSupport = (
332 obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
333 space?: number,
334 ): string => {
335 return JSON.stringify(
336 obj,
337 (_, value: Record<string, unknown>) => {
338 if (value instanceof Map) {
339 return {
340 dataType: 'Map',
341 value: [...value],
342 };
343 }
344 return value;
345 },
346 space,
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 */
356 export 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)';
368 }
369 }
370 if (
371 !isUndefined(
372 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString],
373 )
374 ) {
375 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString];
376 }
377 return '(Unknown)';
378 };
379
380 export 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) {
383 return false;
384 }
385 }
386 return true;
387 };