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