Fixes to performance:
[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(value: unknown): Date | null | undefined {
56 if (Utils.isNullOrUndefined(value)) {
57 return value as null | undefined;
58 }
59 if (value instanceof Date) {
60 return value;
61 }
62 if (Utils.isString(value) || typeof value === 'number') {
63 return new Date(value as string | number);
64 }
65 return null;
66 }
67
68 public static convertToInt(value: unknown): number {
69 if (!value) {
70 return 0;
71 }
72 let changedValue: number = value as number;
73 if (Number.isSafeInteger(value)) {
74 return value as number;
75 }
76 if (typeof value === 'number') {
77 changedValue = Math.trunc(value);
78 }
79 if (Utils.isString(value)) {
80 changedValue = parseInt(value as string);
81 }
82 return changedValue;
83 }
84
85 public static convertToFloat(value: unknown): number {
86 if (!value) {
87 return 0;
88 }
89 let changedValue: number = value as number;
90 if (Utils.isString(value)) {
91 changedValue = parseFloat(value as string);
92 }
93 return changedValue;
94 }
95
96 public static convertToBoolean(value: unknown): boolean {
97 let result = false;
98 if (value) {
99 // Check the type
100 if (typeof value === 'boolean') {
101 result = value;
102 } else if (
103 Utils.isString(value) &&
104 ((value as string).toLowerCase() === 'true' || value === '1')
105 ) {
106 result = true;
107 } else if (typeof value === 'number' && value === 1) {
108 result = true;
109 }
110 }
111 return result;
112 }
113
114 public static getRandomFloat(max = Number.MAX_VALUE, min = 0, negative = false): number {
115 if (max < min || max < 0 || min < 0) {
116 throw new RangeError('Invalid interval');
117 }
118 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
119 const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
120 return sign * (randomPositiveFloat * (max - min) + min);
121 }
122
123 public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number {
124 if (max < min || max < 0 || min < 0) {
125 throw new RangeError('Invalid interval');
126 }
127 max = Math.floor(max);
128 if (!Utils.isNullOrUndefined(min) && min !== 0) {
129 min = Math.ceil(min);
130 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
131 }
132 return Math.floor(Utils.secureRandom() * (max + 1));
133 }
134
135 public static roundTo(numberValue: number, scale: number): number {
136 const roundPower = Math.pow(10, scale);
137 return Math.round(numberValue * roundPower) / roundPower;
138 }
139
140 public static truncTo(numberValue: number, scale: number): number {
141 const truncPower = Math.pow(10, scale);
142 return Math.trunc(numberValue * truncPower) / truncPower;
143 }
144
145 public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number {
146 if (min) {
147 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
148 }
149 return Utils.roundTo(Utils.getRandomFloat(max), scale);
150 }
151
152 public static getRandomFloatFluctuatedRounded(
153 staticValue: number,
154 fluctuationPercent: number,
155 scale = 2
156 ): number {
157 if (fluctuationPercent === 0) {
158 return Utils.roundTo(staticValue, scale);
159 }
160 const fluctuationRatio = fluctuationPercent / 100;
161 return Utils.getRandomFloatRounded(
162 staticValue * (1 + fluctuationRatio),
163 staticValue * (1 - fluctuationRatio),
164 scale
165 );
166 }
167
168 public static isObject(item: unknown): boolean {
169 return item && typeof item === 'object' && Array.isArray(item) === false;
170 }
171
172 public static cloneObject<T extends object>(object: T): T {
173 return clone<T>(object);
174 }
175
176 public static isIterable<T>(obj: T): boolean {
177 return obj ? typeof obj[Symbol.iterator] === 'function' : false;
178 }
179
180 public static isString(value: unknown): boolean {
181 return typeof value === 'string';
182 }
183
184 public static isEmptyString(value: unknown): boolean {
185 return Utils.isString(value) && (value as string).trim().length === 0;
186 }
187
188 public static isUndefined(value: unknown): boolean {
189 return typeof value === 'undefined';
190 }
191
192 public static isNullOrUndefined(value: unknown): boolean {
193 // eslint-disable-next-line eqeqeq, no-eq-null
194 return value == null ? true : false;
195 }
196
197 public static isEmptyArray(object: unknown | unknown[]): boolean {
198 if (!Array.isArray(object)) {
199 return true;
200 }
201 if (object.length > 0) {
202 return false;
203 }
204 return true;
205 }
206
207 public static isEmptyObject(obj: object): boolean {
208 if (obj?.constructor !== Object) {
209 return false;
210 }
211 // Iterates over the keys of an object, if
212 // any exist, return false.
213 for (const _ in obj) {
214 return false;
215 }
216 return true;
217 }
218
219 public static insertAt = (str: string, subStr: string, pos: number): string =>
220 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
221
222 /**
223 * @param [retryNumber=0]
224 * @returns delay in milliseconds
225 */
226 public static exponentialDelay(retryNumber = 0): number {
227 const delay = Math.pow(2, retryNumber) * 100;
228 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
229 return delay + randomSum;
230 }
231
232 public static async promiseWithTimeout<T>(
233 promise: Promise<T>,
234 timeoutMs: number,
235 timeoutError: Error,
236 timeoutCallback: () => void = () => {
237 /* This is intentional */
238 }
239 ): Promise<T> {
240 // Create a timeout promise that rejects in timeout milliseconds
241 const timeoutPromise = new Promise<never>((_, reject) => {
242 setTimeout(() => {
243 timeoutCallback();
244 reject(timeoutError);
245 }, timeoutMs);
246 });
247
248 // Returns a race between timeout promise and the passed promise
249 return Promise.race<T>([promise, timeoutPromise]);
250 }
251
252 /**
253 * Generate a cryptographically secure random number in the [0,1[ range
254 *
255 * @returns
256 */
257 public static secureRandom(): number {
258 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
259 }
260
261 public static JSONStringifyWithMapSupport(
262 obj: Record<string, unknown> | Record<string, unknown>[] | Map<string, unknown>,
263 space?: number
264 ): string {
265 return JSON.stringify(
266 obj,
267 (key, value: Record<string, unknown>) => {
268 if (value instanceof Map) {
269 return {
270 dataType: 'Map',
271 value: [...value],
272 };
273 }
274 return value;
275 },
276 space
277 );
278 }
279
280 /**
281 * Convert websocket error code to human readable string message
282 *
283 * @param code websocket error code
284 * @returns human readable string message
285 */
286 public static getWebSocketCloseEventStatusString(code: number): string {
287 if (code >= 0 && code <= 999) {
288 return '(Unused)';
289 } else if (code >= 1016) {
290 if (code <= 1999) {
291 return '(For WebSocket standard)';
292 } else if (code <= 2999) {
293 return '(For WebSocket extensions)';
294 } else if (code <= 3999) {
295 return '(For libraries and frameworks)';
296 } else if (code <= 4999) {
297 return '(For applications)';
298 }
299 }
300 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
301 return WebSocketCloseEventStatusString[code] as string;
302 }
303 return '(Unknown)';
304 }
305 }