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