Implement an optimized (20x) version of isEmptyObject()
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
1 import crypto from 'crypto';
2
3 import { WebSocketCloseEventStatusString } from '../types/WebSocket';
4
5 export default class Utils {
6 private constructor() {
7 // This is intentional
8 }
9
10 public static logPrefix(prefixString = ''): string {
11 return new Date().toLocaleString() + prefixString;
12 }
13
14 public static generateUUID(): string {
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);
20 }
21
22 public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
23 return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
24 }
25
26 public static formatDurationMilliSeconds(duration: number): string {
27 duration = Utils.convertToInt(duration);
28 const hours = Math.floor(duration / (3600 * 1000));
29 const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
30 const seconds = duration / 1000 - hours * 3600 - minutes * 60;
31 let hoursStr = hours.toString();
32 let minutesStr = minutes.toString();
33 let secondsStr = seconds.toString();
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) {
42 secondsStr = '0' + seconds.toString();
43 }
44 return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6);
45 }
46
47 public static formatDurationSeconds(duration: number): string {
48 return Utils.formatDurationMilliSeconds(duration * 1000);
49 }
50
51 public static convertToDate(value: unknown): Date {
52 // Check
53 if (!value) {
54 return value as Date;
55 }
56 // Check Type
57 if (!(value instanceof Date)) {
58 return new Date(value as string);
59 }
60 return value;
61 }
62
63 public static convertToInt(value: unknown): number {
64 let changedValue: number = value as number;
65 if (!value) {
66 return 0;
67 }
68 if (Number.isSafeInteger(value)) {
69 return value as number;
70 }
71 // Check
72 if (Utils.isString(value)) {
73 // Create Object
74 changedValue = parseInt(value as string);
75 }
76 return changedValue;
77 }
78
79 public static convertToFloat(value: unknown): number {
80 let changedValue: number = value as number;
81 if (!value) {
82 return 0;
83 }
84 // Check
85 if (Utils.isString(value)) {
86 // Create Object
87 changedValue = parseFloat(value as string);
88 }
89 return changedValue;
90 }
91
92 public static convertToBoolean(value: unknown): boolean {
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
102 result = value === 'true';
103 }
104 }
105 return result;
106 }
107
108 public static getRandomFloat(max = Number.MAX_VALUE, min = 0, negative = false): number {
109 if (max < min || max < 0 || min < 0) {
110 throw new RangeError('Invalid interval');
111 }
112 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
113 const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
114 return sign * (randomPositiveFloat * (max - min) + min);
115 }
116
117 public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number {
118 if (max < min || max < 0 || min < 0) {
119 throw new RangeError('Invalid interval');
120 }
121 max = Math.floor(max);
122 if (!Utils.isNullOrUndefined(min) && min !== 0) {
123 min = Math.ceil(min);
124 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
125 }
126 return Math.floor(Utils.secureRandom() * (max + 1));
127 }
128
129 public static roundTo(numberValue: number, scale: number): number {
130 const roundPower = Math.pow(10, scale);
131 return Math.round(numberValue * roundPower) / roundPower;
132 }
133
134 public static truncTo(numberValue: number, scale: number): number {
135 const truncPower = Math.pow(10, scale);
136 return Math.trunc(numberValue * truncPower) / truncPower;
137 }
138
139 public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number {
140 if (min) {
141 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
142 }
143 return Utils.roundTo(Utils.getRandomFloat(max), scale);
144 }
145
146 public static getRandomFloatFluctuatedRounded(
147 staticValue: number,
148 fluctuationPercent: number,
149 scale = 2
150 ): number {
151 if (fluctuationPercent === 0) {
152 return Utils.roundTo(staticValue, scale);
153 }
154 const fluctuationRatio = fluctuationPercent / 100;
155 return Utils.getRandomFloatRounded(
156 staticValue * (1 + fluctuationRatio),
157 staticValue * (1 - fluctuationRatio),
158 scale
159 );
160 }
161
162 public static cloneObject<T>(object: T): T {
163 return JSON.parse(JSON.stringify(object)) as T;
164 }
165
166 public static isIterable<T>(obj: T): boolean {
167 return obj ? typeof obj[Symbol.iterator] === 'function' : false;
168 }
169
170 public static isString(value: unknown): boolean {
171 return typeof value === 'string';
172 }
173
174 public static isEmptyString(value: unknown): boolean {
175 return Utils.isString(value) && (value as string).trim().length === 0;
176 }
177
178 public static isUndefined(value: unknown): boolean {
179 return typeof value === 'undefined';
180 }
181
182 public static isNullOrUndefined(value: unknown): boolean {
183 // eslint-disable-next-line eqeqeq, no-eq-null
184 return value == null ? true : false;
185 }
186
187 public static isEmptyArray(object: unknown): boolean {
188 if (!object) {
189 return true;
190 }
191 if (Array.isArray(object) === true && (object as unknown[]).length > 0) {
192 return false;
193 }
194 return true;
195 }
196
197 public static isEmptyObject(obj: object): boolean {
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;
207 }
208
209 public static insertAt = (str: string, subStr: string, pos: number): string =>
210 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
211
212 /**
213 * @param [retryNumber=0]
214 * @returns delay in milliseconds
215 */
216 public static exponentialDelay(retryNumber = 0): number {
217 const delay = Math.pow(2, retryNumber) * 100;
218 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
219 return delay + randomSum;
220 }
221
222 public static async promiseWithTimeout<T>(
223 promise: Promise<T>,
224 timeoutMs: number,
225 timeoutError: Error,
226 timeoutCallback: () => void = () => {
227 /* This is intentional */
228 }
229 ): Promise<T> {
230 // Create a timeout promise that rejects in timeout milliseconds
231 const timeoutPromise = new Promise<never>((_, reject) => {
232 setTimeout(() => {
233 timeoutCallback();
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
242 /**
243 * Generate a cryptographically secure random number in the [0,1[ range
244 *
245 * @returns
246 */
247 public static secureRandom(): number {
248 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
249 }
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 }
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 }
295 }