5841ca1910f810670296b5824e051ef267cdce16
[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 { formatDuration, secondsToMilliseconds } from 'date-fns';
5 import clone from 'just-clone';
6
7 import { Constants } from './Constants';
8 import { type TimestampedData, WebSocketCloseEventStatusString } from '../types';
9
10 export const logPrefix = (prefixString = ''): string => {
11 return `${new Date().toLocaleString()}${prefixString}`;
12 };
13
14 export const generateUUID = (): string => {
15 return randomUUID();
16 };
17
18 export const validateUUID = (uuid: string): boolean => {
19 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(
20 uuid,
21 );
22 };
23
24 export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
25 return new Promise<NodeJS.Timeout>((resolve) => setTimeout(resolve as () => void, milliSeconds));
26 };
27
28 export const formatDurationMilliSeconds = (duration: number): string => {
29 duration = convertToInt(duration);
30 const days = Math.floor(duration / (24 * 3600 * 1000));
31 const hours = Math.floor(duration / (3600 * 1000) - days * 24);
32 const minutes = Math.floor(duration / (60 * 1000) - days * 24 * 60 - hours * 60);
33 const seconds = Math.floor(duration / 1000 - days * 24 * 3600 - hours * 3600 - minutes * 60);
34 return formatDuration({
35 days,
36 hours,
37 minutes,
38 seconds,
39 });
40 };
41
42 export const formatDurationSeconds = (duration: number): string => {
43 return formatDurationMilliSeconds(secondsToMilliseconds(duration));
44 };
45
46 export const convertToDate = (
47 value: Date | string | number | null | undefined,
48 ): Date | null | undefined => {
49 if (isNullOrUndefined(value)) {
50 return value as null | undefined;
51 }
52 if (value instanceof Date) {
53 return value;
54 }
55 if (isString(value) || typeof value === 'number') {
56 return new Date(value!);
57 }
58 return null;
59 };
60
61 export const convertToInt = (value: unknown): number => {
62 if (!value) {
63 return 0;
64 }
65 let changedValue: number = value as number;
66 if (Number.isSafeInteger(value)) {
67 return value as number;
68 }
69 if (typeof value === 'number') {
70 return Math.trunc(value);
71 }
72 if (isString(value)) {
73 changedValue = parseInt(value as string);
74 }
75 if (isNaN(changedValue)) {
76 // eslint-disable-next-line @typescript-eslint/no-base-to-string
77 throw new Error(`Cannot convert to integer: ${value.toString()}`);
78 }
79 return changedValue;
80 };
81
82 export const convertToFloat = (value: unknown): number => {
83 if (!value) {
84 return 0;
85 }
86 let changedValue: number = value as number;
87 if (isString(value)) {
88 changedValue = parseFloat(value as string);
89 }
90 if (isNaN(changedValue)) {
91 // eslint-disable-next-line @typescript-eslint/no-base-to-string
92 throw new Error(`Cannot convert to float: ${value.toString()}`);
93 }
94 return changedValue;
95 };
96
97 export const convertToBoolean = (value: unknown): boolean => {
98 let result = false;
99 if (value) {
100 // Check the type
101 if (typeof value === 'boolean') {
102 return value;
103 } else if (isString(value) && ((value as string).toLowerCase() === 'true' || value === '1')) {
104 result = true;
105 } else if (typeof value === 'number' && value === 1) {
106 result = true;
107 }
108 }
109 return result;
110 };
111
112 export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => {
113 if (max < min) {
114 throw new RangeError('Invalid interval');
115 }
116 if (max - min === Infinity) {
117 throw new RangeError('Invalid interval');
118 }
119 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min;
120 };
121
122 export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => {
123 max = Math.floor(max);
124 if (!isNullOrUndefined(min) && min !== 0) {
125 min = Math.ceil(min);
126 return Math.floor(randomInt(min, max + 1));
127 }
128 return Math.floor(randomInt(max + 1));
129 };
130
131 /**
132 * Rounds the given number to the given scale.
133 * The rounding is done using the "round half away from zero" method.
134 *
135 * @param numberValue - The number to round.
136 * @param scale - The scale to round to.
137 * @returns The rounded number.
138 */
139 export const roundTo = (numberValue: number, scale: number): number => {
140 const roundPower = Math.pow(10, scale);
141 return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower;
142 };
143
144 export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => {
145 if (min) {
146 return roundTo(getRandomFloat(max, min), scale);
147 }
148 return roundTo(getRandomFloat(max), scale);
149 };
150
151 export const getRandomFloatFluctuatedRounded = (
152 staticValue: number,
153 fluctuationPercent: number,
154 scale = 2,
155 ): number => {
156 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
157 throw new RangeError(
158 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
159 );
160 }
161 if (fluctuationPercent === 0) {
162 return roundTo(staticValue, scale);
163 }
164 const fluctuationRatio = fluctuationPercent / 100;
165 return getRandomFloatRounded(
166 staticValue * (1 + fluctuationRatio),
167 staticValue * (1 - fluctuationRatio),
168 scale,
169 );
170 };
171
172 export const extractTimeSeriesValues = (timeSeries: Array<TimestampedData>): number[] => {
173 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
174 };
175
176 export const isObject = (item: unknown): boolean => {
177 return (
178 isNullOrUndefined(item) === false && typeof item === 'object' && Array.isArray(item) === false
179 );
180 };
181
182 export const cloneObject = <T extends object>(object: T): T => {
183 return clone<T>(object);
184 };
185
186 export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => {
187 return isObject(object) && Object.hasOwn(object as object, property);
188 };
189
190 export const isCFEnvironment = (): boolean => {
191 return !isNullOrUndefined(process.env.VCAP_APPLICATION);
192 };
193
194 export const isIterable = <T>(obj: T): boolean => {
195 return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false;
196 };
197
198 const isString = (value: unknown): boolean => {
199 return typeof value === 'string';
200 };
201
202 export const isEmptyString = (value: unknown): boolean => {
203 return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0);
204 };
205
206 export const isNotEmptyString = (value: unknown): boolean => {
207 return isString(value) && (value as string).trim().length > 0;
208 };
209
210 export const isUndefined = (value: unknown): boolean => {
211 return value === undefined;
212 };
213
214 export const isNullOrUndefined = (value: unknown): boolean => {
215 // eslint-disable-next-line eqeqeq, no-eq-null
216 return value == null;
217 };
218
219 export const isEmptyArray = (object: unknown): boolean => {
220 return Array.isArray(object) && object.length === 0;
221 };
222
223 export const isNotEmptyArray = (object: unknown): boolean => {
224 return Array.isArray(object) && object.length > 0;
225 };
226
227 export const isEmptyObject = (obj: object): boolean => {
228 if (obj?.constructor !== Object) {
229 return false;
230 }
231 // Iterates over the keys of an object, if
232 // any exist, return false.
233 for (const _ in obj) {
234 return false;
235 }
236 return true;
237 };
238
239 export const insertAt = (str: string, subStr: string, pos: number): string =>
240 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
241
242 /**
243 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
244 *
245 * @param retryNumber - the number of retries that have already been attempted
246 * @returns delay in milliseconds
247 */
248 export const exponentialDelay = (retryNumber = 0, maxDelayRatio = 0.2): number => {
249 const delay = Math.pow(2, retryNumber) * 100;
250 const randomSum = delay * maxDelayRatio * secureRandom(); // 0-20% of the delay
251 return delay + randomSum;
252 };
253
254 const isPromisePending = (promise: Promise<unknown>): boolean => {
255 return inspect(promise).includes('pending');
256 };
257
258 export const promiseWithTimeout = async <T>(
259 promise: Promise<T>,
260 timeoutMs: number,
261 timeoutError: Error,
262 timeoutCallback: () => void = () => {
263 /* This is intentional */
264 },
265 ): Promise<T> => {
266 // Create a timeout promise that rejects in timeout milliseconds
267 const timeoutPromise = new Promise<never>((_, reject) => {
268 setTimeout(() => {
269 if (isPromisePending(promise)) {
270 timeoutCallback();
271 // FIXME: The original promise shall be canceled
272 }
273 reject(timeoutError);
274 }, timeoutMs);
275 });
276
277 // Returns a race between timeout promise and the passed promise
278 return Promise.race<T>([promise, timeoutPromise]);
279 };
280
281 /**
282 * Generates a cryptographically secure random number in the [0,1[ range
283 *
284 * @returns
285 */
286 export const secureRandom = (): number => {
287 return randomBytes(4).readUInt32LE() / 0x100000000;
288 };
289
290 export const JSONStringifyWithMapSupport = (
291 obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
292 space?: number,
293 ): string => {
294 return JSON.stringify(
295 obj,
296 (_, value: Record<string, unknown>) => {
297 if (value instanceof Map) {
298 return {
299 dataType: 'Map',
300 value: [...value],
301 };
302 }
303 return value;
304 },
305 space,
306 );
307 };
308
309 /**
310 * Converts websocket error code to human readable string message
311 *
312 * @param code - websocket error code
313 * @returns human readable string message
314 */
315 export const getWebSocketCloseEventStatusString = (code: number): string => {
316 if (code >= 0 && code <= 999) {
317 return '(Unused)';
318 } else if (code >= 1016) {
319 if (code <= 1999) {
320 return '(For WebSocket standard)';
321 } else if (code <= 2999) {
322 return '(For WebSocket extensions)';
323 } else if (code <= 3999) {
324 return '(For libraries and frameworks)';
325 } else if (code <= 4999) {
326 return '(For applications)';
327 }
328 }
329 if (
330 !isUndefined(
331 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString],
332 )
333 ) {
334 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString];
335 }
336 return '(Unknown)';
337 };