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