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