Optimize worker handlers calls by binding them to the current instance
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
1 import crypto from 'crypto';
2
3 import clone from 'just-clone';
4
5 import { WebSocketCloseEventStatusString } from '../types/WebSocket';
6
7 export default class Utils {
8 private constructor() {
9 // This is intentional
10 }
11
12 public static logPrefix(prefixString = ''): string {
13 return new Date().toLocaleString() + prefixString;
14 }
15
16 public static generateUUID(): string {
17 return crypto.randomUUID();
18 }
19
20 public static validateUUID(uuid: string): boolean {
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 );
24 }
25
26 public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
27 return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
28 }
29
30 public static formatDurationMilliSeconds(duration: number): string {
31 duration = Utils.convertToInt(duration);
32 const hours = Math.floor(duration / (3600 * 1000));
33 const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
34 const seconds = duration / 1000 - hours * 3600 - minutes * 60;
35 let hoursStr = hours.toString();
36 let minutesStr = minutes.toString();
37 let secondsStr = seconds.toString();
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) {
46 secondsStr = '0' + seconds.toString();
47 }
48 return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6);
49 }
50
51 public static formatDurationSeconds(duration: number): string {
52 return Utils.formatDurationMilliSeconds(duration * 1000);
53 }
54
55 public static convertToDate(
56 value: Date | string | number | null | undefined
57 ): Date | null | undefined {
58 if (Utils.isNullOrUndefined(value)) {
59 return value as null | undefined;
60 }
61 if (value instanceof Date) {
62 return value;
63 }
64 if (Utils.isString(value) || typeof value === 'number') {
65 return new Date(value);
66 }
67 return null;
68 }
69
70 public static convertToInt(value: unknown): number {
71 if (!value) {
72 return 0;
73 }
74 let changedValue: number = value as number;
75 if (Number.isSafeInteger(value)) {
76 return value as number;
77 }
78 if (typeof value === 'number') {
79 return Math.trunc(value);
80 }
81 if (Utils.isString(value)) {
82 changedValue = parseInt(value as string);
83 }
84 if (isNaN(changedValue)) {
85 throw new Error(`Cannot convert to integer: ${value.toString()}`);
86 }
87 return changedValue;
88 }
89
90 public static convertToFloat(value: unknown): number {
91 if (!value) {
92 return 0;
93 }
94 let changedValue: number = value as number;
95 if (Utils.isString(value)) {
96 changedValue = parseFloat(value as string);
97 }
98 if (isNaN(changedValue)) {
99 throw new Error(`Cannot convert to float: ${value.toString()}`);
100 }
101 return changedValue;
102 }
103
104 public static convertToBoolean(value: unknown): boolean {
105 let result = false;
106 if (value) {
107 // Check the type
108 if (typeof value === 'boolean') {
109 return value;
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;
117 }
118 }
119 return result;
120 }
121
122 public static getRandomFloat(max = Number.MAX_VALUE, min = 0, negative = false): number {
123 if (max < min || max < 0 || min < 0) {
124 throw new RangeError('Invalid interval');
125 }
126 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
127 const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
128 return sign * (randomPositiveFloat * (max - min) + min);
129 }
130
131 public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number {
132 if (max < min || max < 0 || min < 0) {
133 throw new RangeError('Invalid interval');
134 }
135 max = Math.floor(max);
136 if (!Utils.isNullOrUndefined(min) && min !== 0) {
137 min = Math.ceil(min);
138 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
139 }
140 return Math.floor(Utils.secureRandom() * (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 item && typeof item === 'object' && Array.isArray(item) === false;
178 }
179
180 public static cloneObject<T extends object>(object: T): T {
181 return clone<T>(object);
182 }
183
184 public static isIterable<T>(obj: T): boolean {
185 return obj ? typeof obj[Symbol.iterator] === 'function' : false;
186 }
187
188 public static isString(value: unknown): boolean {
189 return typeof value === 'string';
190 }
191
192 public static isEmptyString(value: unknown): boolean {
193 return Utils.isString(value) && (value as string).trim().length === 0;
194 }
195
196 public static isUndefined(value: unknown): boolean {
197 return typeof value === 'undefined';
198 }
199
200 public static isNullOrUndefined(value: unknown): boolean {
201 // eslint-disable-next-line eqeqeq, no-eq-null
202 return value == null ? true : false;
203 }
204
205 public static isEmptyArray(object: unknown | unknown[]): boolean {
206 if (!Array.isArray(object)) {
207 return true;
208 }
209 if (object.length > 0) {
210 return false;
211 }
212 return true;
213 }
214
215 public static isEmptyObject(obj: object): boolean {
216 if (obj?.constructor !== Object) {
217 return false;
218 }
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;
225 }
226
227 public static insertAt = (str: string, subStr: string, pos: number): string =>
228 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
229
230 /**
231 * @param retryNumber - the number of retries that have already been attempted
232 * @returns delay in milliseconds
233 */
234 public static exponentialDelay(retryNumber = 0): number {
235 const delay = Math.pow(2, retryNumber) * 100;
236 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
237 return delay + randomSum;
238 }
239
240 public static async promiseWithTimeout<T>(
241 promise: Promise<T>,
242 timeoutMs: number,
243 timeoutError: Error,
244 timeoutCallback: () => void = () => {
245 /* This is intentional */
246 }
247 ): Promise<T> {
248 // Create a timeout promise that rejects in timeout milliseconds
249 const timeoutPromise = new Promise<never>((_, reject) => {
250 setTimeout(() => {
251 timeoutCallback();
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
260 /**
261 * Generate a cryptographically secure random number in the [0,1[ range
262 *
263 * @returns
264 */
265 public static secureRandom(): number {
266 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
267 }
268
269 public static JSONStringifyWithMapSupport(
270 obj: Record<string, unknown> | Record<string, unknown>[] | Map<string, unknown>,
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 }
287
288 /**
289 * Convert websocket error code to human readable string message
290 *
291 * @param code - websocket error code
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 }
313 }