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