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