Apply prettier formating
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
CommitLineData
a4624c96 1import Configuration from './Configuration';
32a1eb7a 2import { WebSocketCloseEventStatusString } from '../types/WebSocket';
a4624c96 3import { WorkerProcessType } from '../types/Worker';
c37528f1 4import crypto from 'crypto';
6af9012e 5import { v4 as uuid } from 'uuid';
7dde0b73 6
3f40bc9c 7export default class Utils {
0f16a662 8 public static logPrefix(prefixString = ''): string {
147d0e0f
JB
9 return new Date().toLocaleString() + prefixString;
10 }
11
0f16a662 12 public static generateUUID(): string {
2e3ac96d 13 return uuid();
7dde0b73
JB
14 }
15
0f16a662 16 public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
5f8a4fd6 17 return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
7dde0b73
JB
18 }
19
d7d1db72
JB
20 public static formatDurationMilliSeconds(duration: number): string {
21 duration = Utils.convertToInt(duration);
22 const hours = Math.floor(duration / (3600 * 1000));
e7aeea18
JB
23 const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
24 const seconds = duration / 1000 - hours * 3600 - minutes * 60;
a3868ec4
JB
25 let hoursStr = hours.toString();
26 let minutesStr = minutes.toString();
27 let secondsStr = seconds.toString();
d7d1db72
JB
28
29 if (hours < 10) {
30 hoursStr = '0' + hours.toString();
31 }
32 if (minutes < 10) {
33 minutesStr = '0' + minutes.toString();
34 }
35 if (seconds < 10) {
b322b8b4 36 secondsStr = '0' + seconds.toString();
d7d1db72 37 }
b322b8b4 38 return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6);
9ac86a7e
JB
39 }
40
d7d1db72
JB
41 public static formatDurationSeconds(duration: number): string {
42 return Utils.formatDurationMilliSeconds(duration * 1000);
7dde0b73
JB
43 }
44
0f16a662 45 public static convertToDate(value: unknown): Date {
560bcf5b 46 // Check
6af9012e 47 if (!value) {
73d09045 48 return value as Date;
560bcf5b
JB
49 }
50 // Check Type
6af9012e 51 if (!(value instanceof Date)) {
73d09045 52 return new Date(value as string);
7dde0b73 53 }
6af9012e 54 return value;
7dde0b73
JB
55 }
56
0f16a662 57 public static convertToInt(value: unknown): number {
73d09045 58 let changedValue: number = value as number;
72766a82 59 if (!value) {
7dde0b73
JB
60 return 0;
61 }
72766a82 62 if (Number.isSafeInteger(value)) {
95926c9b 63 return value as number;
72766a82 64 }
7dde0b73 65 // Check
087a502d 66 if (Utils.isString(value)) {
7dde0b73 67 // Create Object
73d09045 68 changedValue = parseInt(value as string);
7dde0b73 69 }
72766a82 70 return changedValue;
7dde0b73
JB
71 }
72
0f16a662 73 public static convertToFloat(value: unknown): number {
73d09045 74 let changedValue: number = value as number;
72766a82 75 if (!value) {
7dde0b73
JB
76 return 0;
77 }
78 // Check
087a502d 79 if (Utils.isString(value)) {
7dde0b73 80 // Create Object
73d09045 81 changedValue = parseFloat(value as string);
7dde0b73 82 }
72766a82 83 return changedValue;
7dde0b73
JB
84 }
85
0f16a662 86 public static convertToBoolean(value: unknown): boolean {
a6e68f34
JB
87 let result = false;
88 // Check boolean
89 if (value) {
90 // Check the type
91 if (typeof value === 'boolean') {
92 // Already a boolean
93 result = value;
94 } else {
95 // Convert
e7aeea18 96 result = value === 'true';
a6e68f34
JB
97 }
98 }
99 return result;
100 }
101
fd00fa2e 102 public static getRandomFloat(max: number, min = 0, negative = false): number {
b322b8b4
JB
103 if (max < min || min < 0 || max < 0) {
104 throw new RangeError('Invalid interval');
105 }
fd00fa2e 106 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
e7aeea18 107 const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
fd00fa2e 108 return sign * (randomPositiveFloat * (max - min) + min);
560bcf5b
JB
109 }
110
72740232 111 public static getRandomInteger(max: number, min = 0): number {
a3868ec4
JB
112 if (max < 0) {
113 throw new RangeError('Invalid interval');
114 }
fd00fa2e 115 max = Math.floor(max);
7dde0b73 116 if (min) {
a3868ec4
JB
117 if (max < min || min < 0) {
118 throw new RangeError('Invalid interval');
119 }
fd00fa2e 120 min = Math.ceil(min);
c37528f1 121 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
7dde0b73 122 }
c37528f1 123 return Math.floor(Utils.secureRandom() * (max + 1));
560bcf5b
JB
124 }
125
0f16a662 126 public static roundTo(numberValue: number, scale: number): number {
ad3de6c4 127 const roundPower = Math.pow(10, scale);
035742f7 128 return Math.round(numberValue * roundPower) / roundPower;
560bcf5b
JB
129 }
130
0f16a662 131 public static truncTo(numberValue: number, scale: number): number {
6d3a11a0 132 const truncPower = Math.pow(10, scale);
035742f7 133 return Math.trunc(numberValue * truncPower) / truncPower;
6d3a11a0
JB
134 }
135
0f16a662 136 public static getRandomFloatRounded(max: number, min = 0, scale = 2): number {
560bcf5b
JB
137 if (min) {
138 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
139 }
140 return Utils.roundTo(Utils.getRandomFloat(max), scale);
7dde0b73
JB
141 }
142
e7aeea18
JB
143 public static getRandomFloatFluctuatedRounded(
144 staticValue: number,
145 fluctuationPercent: number,
146 scale = 2
147 ): number {
9ccca265
JB
148 if (fluctuationPercent === 0) {
149 return Utils.roundTo(staticValue, scale);
150 }
97ef739c 151 const fluctuationRatio = fluctuationPercent / 100;
e7aeea18
JB
152 return Utils.getRandomFloatRounded(
153 staticValue * (1 + fluctuationRatio),
154 staticValue * (1 - fluctuationRatio),
155 scale
156 );
9ccca265
JB
157 }
158
0f16a662 159 public static cloneObject<T>(object: T): T {
e56aa9a4 160 return JSON.parse(JSON.stringify(object)) as T;
2e6f5966 161 }
facd8ebd 162
0f16a662 163 public static isIterable<T>(obj: T): boolean {
67e9cccf
JB
164 if (obj) {
165 return typeof obj[Symbol.iterator] === 'function';
166 }
167 return false;
168 }
169
0f16a662 170 public static isString(value: unknown): boolean {
560bcf5b
JB
171 return typeof value === 'string';
172 }
173
0f16a662 174 public static isUndefined(value: unknown): boolean {
ead548f2
JB
175 return typeof value === 'undefined';
176 }
177
0f16a662 178 public static isNullOrUndefined(value: unknown): boolean {
32a1eb7a 179 // eslint-disable-next-line no-eq-null, eqeqeq
ead548f2 180 if (value == null) {
facd8ebd
JB
181 return true;
182 }
183 return false;
184 }
4a56deef 185
0f16a662 186 public static isEmptyArray(object: unknown): boolean {
fd1ee77c
JB
187 if (!object) {
188 return true;
189 }
4a56deef
JB
190 if (Array.isArray(object) && object.length > 0) {
191 return false;
192 }
193 return true;
194 }
7abfea5f 195
0f16a662 196 public static isEmptyObject(obj: Record<string, unknown>): boolean {
7abfea5f
JB
197 return !Object.keys(obj).length;
198 }
7ec46a9a 199
e7aeea18
JB
200 public static insertAt = (str: string, subStr: string, pos: number): string =>
201 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
032d6efc
JB
202
203 /**
81797102
JB
204 * @param [retryNumber=0]
205 * @returns delay in milliseconds
032d6efc 206 */
0f16a662 207 public static exponentialDelay(retryNumber = 0): number {
032d6efc 208 const delay = Math.pow(2, retryNumber) * 100;
c37528f1 209 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
032d6efc
JB
210 return delay + randomSum;
211 }
32a1eb7a 212
e71cccf3
JB
213 /**
214 * Convert websocket error code to human readable string message
215 *
81797102
JB
216 * @param code websocket error code
217 * @returns human readable string message
e71cccf3 218 */
0f16a662 219 public static getWebSocketCloseEventStatusString(code: number): string {
32a1eb7a
JB
220 if (code >= 0 && code <= 999) {
221 return '(Unused)';
222 } else if (code >= 1016) {
223 if (code <= 1999) {
224 return '(For WebSocket standard)';
225 } else if (code <= 2999) {
226 return '(For WebSocket extensions)';
227 } else if (code <= 3999) {
228 return '(For libraries and frameworks)';
229 } else if (code <= 4999) {
230 return '(For applications)';
231 }
232 }
233 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
17991e8c 234 return WebSocketCloseEventStatusString[code] as string;
32a1eb7a
JB
235 }
236 return '(Unknown)';
237 }
a4624c96 238
0f16a662 239 public static workerPoolInUse(): boolean {
e7aeea18
JB
240 return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(
241 Configuration.getWorkerProcess()
242 );
a4624c96 243 }
059f35a5 244
0f16a662 245 public static workerDynamicPoolInUse(): boolean {
059f35a5
JB
246 return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL;
247 }
c37528f1 248
6d9abcc2 249 public static async promiseWithTimeout<T>(
e7aeea18
JB
250 promise: Promise<T>,
251 timeoutMs: number,
252 timeoutError: Error,
253 timeoutCallback: () => void = () => {
254 /* This is intentional */
255 }
6d9abcc2
JB
256 ): Promise<T> {
257 // Create a timeout promise that rejects in timeout milliseconds
258 const timeoutPromise = new Promise<never>((_, reject) => {
259 setTimeout(() => {
ed0f8380 260 timeoutCallback();
6d9abcc2
JB
261 reject(timeoutError);
262 }, timeoutMs);
263 });
264
265 // Returns a race between timeout promise and the passed promise
266 return Promise.race<T>([promise, timeoutPromise]);
267 }
268
c37528f1 269 /**
0f16a662 270 * Generate a cryptographically secure random number in the [0,1[ range
c37528f1
JB
271 *
272 * @returns
273 */
0f16a662 274 public static secureRandom(): number {
c37528f1
JB
275 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
276 }
7dde0b73 277}