Optimize worker handlers calls by binding them to the current instance
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
CommitLineData
c37528f1 1import crypto from 'crypto';
8114d10e 2
088ee3c1
JB
3import clone from 'just-clone';
4
5e3cb728
JB
5import { WebSocketCloseEventStatusString } from '../types/WebSocket';
6
3f40bc9c 7export default class Utils {
d5bd1c00
JB
8 private constructor() {
9 // This is intentional
10 }
11
0f16a662 12 public static logPrefix(prefixString = ''): string {
147d0e0f
JB
13 return new Date().toLocaleString() + prefixString;
14 }
15
0f16a662 16 public static generateUUID(): string {
03eacbe5
JB
17 return crypto.randomUUID();
18 }
19
20 public static validateUUID(uuid: string): boolean {
8bd02502
JB
21 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(
22 uuid
23 );
7dde0b73
JB
24 }
25
0f16a662 26 public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
5f8a4fd6 27 return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
7dde0b73
JB
28 }
29
d7d1db72
JB
30 public static formatDurationMilliSeconds(duration: number): string {
31 duration = Utils.convertToInt(duration);
32 const hours = Math.floor(duration / (3600 * 1000));
e7aeea18
JB
33 const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
34 const seconds = duration / 1000 - hours * 3600 - minutes * 60;
a3868ec4
JB
35 let hoursStr = hours.toString();
36 let minutesStr = minutes.toString();
37 let secondsStr = seconds.toString();
d7d1db72
JB
38
39 if (hours < 10) {
40 hoursStr = '0' + hours.toString();
41 }
42 if (minutes < 10) {
43 minutesStr = '0' + minutes.toString();
44 }
45 if (seconds < 10) {
b322b8b4 46 secondsStr = '0' + seconds.toString();
d7d1db72 47 }
b322b8b4 48 return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6);
9ac86a7e
JB
49 }
50
d7d1db72
JB
51 public static formatDurationSeconds(duration: number): string {
52 return Utils.formatDurationMilliSeconds(duration * 1000);
7dde0b73
JB
53 }
54
b1340ec1
JB
55 public static convertToDate(
56 value: Date | string | number | null | undefined
57 ): Date | null | undefined {
d439da5c
JB
58 if (Utils.isNullOrUndefined(value)) {
59 return value as null | undefined;
60 }
61 if (value instanceof Date) {
62 return value;
560bcf5b 63 }
d439da5c 64 if (Utils.isString(value) || typeof value === 'number') {
b1340ec1 65 return new Date(value);
7dde0b73 66 }
d439da5c 67 return null;
7dde0b73
JB
68 }
69
0f16a662 70 public static convertToInt(value: unknown): number {
72766a82 71 if (!value) {
7dde0b73
JB
72 return 0;
73 }
69bafbed 74 let changedValue: number = value as number;
72766a82 75 if (Number.isSafeInteger(value)) {
95926c9b 76 return value as number;
72766a82 77 }
df645d8f 78 if (typeof value === 'number') {
b1340ec1 79 return Math.trunc(value);
df645d8f 80 }
3df786f9
JB
81 if (Utils.isString(value)) {
82 changedValue = parseInt(value as string);
83 }
b1340ec1
JB
84 if (isNaN(changedValue)) {
85 throw new Error(`Cannot convert to integer: ${value.toString()}`);
86 }
72766a82 87 return changedValue;
7dde0b73
JB
88 }
89
0f16a662 90 public static convertToFloat(value: unknown): number {
72766a82 91 if (!value) {
7dde0b73
JB
92 return 0;
93 }
69bafbed 94 let changedValue: number = value as number;
087a502d 95 if (Utils.isString(value)) {
73d09045 96 changedValue = parseFloat(value as string);
7dde0b73 97 }
b1340ec1
JB
98 if (isNaN(changedValue)) {
99 throw new Error(`Cannot convert to float: ${value.toString()}`);
100 }
72766a82 101 return changedValue;
7dde0b73
JB
102 }
103
0f16a662 104 public static convertToBoolean(value: unknown): boolean {
a6e68f34 105 let result = false;
a6e68f34
JB
106 if (value) {
107 // Check the type
108 if (typeof value === 'boolean') {
b1340ec1 109 return value;
df645d8f
JB
110 } else if (
111 Utils.isString(value) &&
112 ((value as string).toLowerCase() === 'true' || value === '1')
113 ) {
114 result = true;
115 } else if (typeof value === 'number' && value === 1) {
116 result = true;
a6e68f34
JB
117 }
118 }
119 return result;
120 }
121
b5e5892d 122 public static getRandomFloat(max = Number.MAX_VALUE, min = 0, negative = false): number {
b3aa9f53 123 if (max < min || max < 0 || min < 0) {
b322b8b4
JB
124 throw new RangeError('Invalid interval');
125 }
fd00fa2e 126 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
e7aeea18 127 const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
fd00fa2e 128 return sign * (randomPositiveFloat * (max - min) + min);
560bcf5b
JB
129 }
130
b5e5892d 131 public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number {
b3aa9f53 132 if (max < min || max < 0 || min < 0) {
a3868ec4
JB
133 throw new RangeError('Invalid interval');
134 }
fd00fa2e 135 max = Math.floor(max);
1f86b121 136 if (!Utils.isNullOrUndefined(min) && min !== 0) {
fd00fa2e 137 min = Math.ceil(min);
c37528f1 138 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
7dde0b73 139 }
c37528f1 140 return Math.floor(Utils.secureRandom() * (max + 1));
560bcf5b
JB
141 }
142
0f16a662 143 public static roundTo(numberValue: number, scale: number): number {
ad3de6c4 144 const roundPower = Math.pow(10, scale);
035742f7 145 return Math.round(numberValue * roundPower) / roundPower;
560bcf5b
JB
146 }
147
0f16a662 148 public static truncTo(numberValue: number, scale: number): number {
6d3a11a0 149 const truncPower = Math.pow(10, scale);
035742f7 150 return Math.trunc(numberValue * truncPower) / truncPower;
6d3a11a0
JB
151 }
152
b5e5892d 153 public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number {
560bcf5b
JB
154 if (min) {
155 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
156 }
157 return Utils.roundTo(Utils.getRandomFloat(max), scale);
7dde0b73
JB
158 }
159
e7aeea18
JB
160 public static getRandomFloatFluctuatedRounded(
161 staticValue: number,
162 fluctuationPercent: number,
163 scale = 2
164 ): number {
9ccca265
JB
165 if (fluctuationPercent === 0) {
166 return Utils.roundTo(staticValue, scale);
167 }
97ef739c 168 const fluctuationRatio = fluctuationPercent / 100;
e7aeea18
JB
169 return Utils.getRandomFloatRounded(
170 staticValue * (1 + fluctuationRatio),
171 staticValue * (1 - fluctuationRatio),
172 scale
173 );
9ccca265
JB
174 }
175
91ecff2d
JB
176 public static isObject(item: unknown): boolean {
177 return item && typeof item === 'object' && Array.isArray(item) === false;
178 }
179
088ee3c1
JB
180 public static cloneObject<T extends object>(object: T): T {
181 return clone<T>(object);
2e6f5966 182 }
facd8ebd 183
0f16a662 184 public static isIterable<T>(obj: T): boolean {
7558b3a6 185 return obj ? typeof obj[Symbol.iterator] === 'function' : false;
67e9cccf
JB
186 }
187
0f16a662 188 public static isString(value: unknown): boolean {
560bcf5b
JB
189 return typeof value === 'string';
190 }
191
e8191622 192 public static isEmptyString(value: unknown): boolean {
87f82a94 193 return Utils.isString(value) && (value as string).trim().length === 0;
e8191622
JB
194 }
195
0f16a662 196 public static isUndefined(value: unknown): boolean {
ead548f2
JB
197 return typeof value === 'undefined';
198 }
199
0f16a662 200 public static isNullOrUndefined(value: unknown): boolean {
7558b3a6
JB
201 // eslint-disable-next-line eqeqeq, no-eq-null
202 return value == null ? true : false;
facd8ebd 203 }
4a56deef 204
45999aab 205 public static isEmptyArray(object: unknown | unknown[]): boolean {
a2111e8d 206 if (!Array.isArray(object)) {
30e27491 207 return true;
fd1ee77c 208 }
45999aab 209 if (object.length > 0) {
4a56deef
JB
210 return false;
211 }
212 return true;
213 }
7abfea5f 214
94ec7e96 215 public static isEmptyObject(obj: object): boolean {
5e5ba121 216 if (obj?.constructor !== Object) {
d20581ee
JB
217 return false;
218 }
87f82a94
JB
219 // Iterates over the keys of an object, if
220 // any exist, return false.
221 for (const _ in obj) {
222 return false;
223 }
224 return true;
7abfea5f 225 }
7ec46a9a 226
e7aeea18
JB
227 public static insertAt = (str: string, subStr: string, pos: number): string =>
228 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
032d6efc
JB
229
230 /**
0e4fa348 231 * @param retryNumber - the number of retries that have already been attempted
81797102 232 * @returns delay in milliseconds
032d6efc 233 */
0f16a662 234 public static exponentialDelay(retryNumber = 0): number {
032d6efc 235 const delay = Math.pow(2, retryNumber) * 100;
c37528f1 236 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
032d6efc
JB
237 return delay + randomSum;
238 }
32a1eb7a 239
6d9abcc2 240 public static async promiseWithTimeout<T>(
e7aeea18
JB
241 promise: Promise<T>,
242 timeoutMs: number,
243 timeoutError: Error,
244 timeoutCallback: () => void = () => {
245 /* This is intentional */
246 }
6d9abcc2
JB
247 ): Promise<T> {
248 // Create a timeout promise that rejects in timeout milliseconds
249 const timeoutPromise = new Promise<never>((_, reject) => {
250 setTimeout(() => {
ed0f8380 251 timeoutCallback();
6d9abcc2
JB
252 reject(timeoutError);
253 }, timeoutMs);
254 });
255
256 // Returns a race between timeout promise and the passed promise
257 return Promise.race<T>([promise, timeoutPromise]);
258 }
259
c37528f1 260 /**
0f16a662 261 * Generate a cryptographically secure random number in the [0,1[ range
c37528f1
JB
262 *
263 * @returns
264 */
0f16a662 265 public static secureRandom(): number {
c37528f1
JB
266 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
267 }
fe791818
JB
268
269 public static JSONStringifyWithMapSupport(
c60af6ca 270 obj: Record<string, unknown> | Record<string, unknown>[] | Map<string, unknown>,
fe791818
JB
271 space?: number
272 ): string {
273 return JSON.stringify(
274 obj,
275 (key, value: Record<string, unknown>) => {
276 if (value instanceof Map) {
277 return {
278 dataType: 'Map',
279 value: [...value],
280 };
281 }
282 return value;
283 },
284 space
285 );
286 }
5e3cb728
JB
287
288 /**
289 * Convert websocket error code to human readable string message
290 *
0e4fa348 291 * @param code - websocket error code
5e3cb728
JB
292 * @returns human readable string message
293 */
294 public static getWebSocketCloseEventStatusString(code: number): string {
295 if (code >= 0 && code <= 999) {
296 return '(Unused)';
297 } else if (code >= 1016) {
298 if (code <= 1999) {
299 return '(For WebSocket standard)';
300 } else if (code <= 2999) {
301 return '(For WebSocket extensions)';
302 } else if (code <= 3999) {
303 return '(For libraries and frameworks)';
304 } else if (code <= 4999) {
305 return '(For applications)';
306 }
307 }
308 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
309 return WebSocketCloseEventStatusString[code] as string;
310 }
311 return '(Unknown)';
312 }
7dde0b73 313}