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