Use ternary operator in helpers methods
[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 {
7558b3a6 164 return obj ? typeof obj[Symbol.iterator] === 'function' : false;
67e9cccf
JB
165 }
166
0f16a662 167 public static isString(value: unknown): boolean {
560bcf5b
JB
168 return typeof value === 'string';
169 }
170
e8191622
JB
171 public static isEmptyString(value: unknown): boolean {
172 return Utils.isString(value) && (value as string).length === 0;
173 }
174
0f16a662 175 public static isUndefined(value: unknown): boolean {
ead548f2
JB
176 return typeof value === 'undefined';
177 }
178
0f16a662 179 public static isNullOrUndefined(value: unknown): boolean {
7558b3a6
JB
180 // eslint-disable-next-line eqeqeq, no-eq-null
181 return value == null ? true : false;
facd8ebd 182 }
4a56deef 183
0f16a662 184 public static isEmptyArray(object: unknown): boolean {
fd1ee77c
JB
185 if (!object) {
186 return true;
187 }
4a56deef
JB
188 if (Array.isArray(object) && object.length > 0) {
189 return false;
190 }
191 return true;
192 }
7abfea5f 193
94ec7e96 194 public static isEmptyObject(obj: object): boolean {
7abfea5f
JB
195 return !Object.keys(obj).length;
196 }
7ec46a9a 197
e7aeea18
JB
198 public static insertAt = (str: string, subStr: string, pos: number): string =>
199 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
032d6efc
JB
200
201 /**
81797102
JB
202 * @param [retryNumber=0]
203 * @returns delay in milliseconds
032d6efc 204 */
0f16a662 205 public static exponentialDelay(retryNumber = 0): number {
032d6efc 206 const delay = Math.pow(2, retryNumber) * 100;
c37528f1 207 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
032d6efc
JB
208 return delay + randomSum;
209 }
32a1eb7a 210
e71cccf3
JB
211 /**
212 * Convert websocket error code to human readable string message
213 *
81797102
JB
214 * @param code websocket error code
215 * @returns human readable string message
e71cccf3 216 */
0f16a662 217 public static getWebSocketCloseEventStatusString(code: number): string {
32a1eb7a
JB
218 if (code >= 0 && code <= 999) {
219 return '(Unused)';
220 } else if (code >= 1016) {
221 if (code <= 1999) {
222 return '(For WebSocket standard)';
223 } else if (code <= 2999) {
224 return '(For WebSocket extensions)';
225 } else if (code <= 3999) {
226 return '(For libraries and frameworks)';
227 } else if (code <= 4999) {
228 return '(For applications)';
229 }
230 }
231 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
17991e8c 232 return WebSocketCloseEventStatusString[code] as string;
32a1eb7a
JB
233 }
234 return '(Unknown)';
235 }
a4624c96 236
0f16a662 237 public static workerPoolInUse(): boolean {
e7aeea18
JB
238 return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(
239 Configuration.getWorkerProcess()
240 );
a4624c96 241 }
059f35a5 242
0f16a662 243 public static workerDynamicPoolInUse(): boolean {
059f35a5
JB
244 return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL;
245 }
c37528f1 246
6d9abcc2 247 public static async promiseWithTimeout<T>(
e7aeea18
JB
248 promise: Promise<T>,
249 timeoutMs: number,
250 timeoutError: Error,
251 timeoutCallback: () => void = () => {
252 /* This is intentional */
253 }
6d9abcc2
JB
254 ): Promise<T> {
255 // Create a timeout promise that rejects in timeout milliseconds
256 const timeoutPromise = new Promise<never>((_, reject) => {
257 setTimeout(() => {
ed0f8380 258 timeoutCallback();
6d9abcc2
JB
259 reject(timeoutError);
260 }, timeoutMs);
261 });
262
263 // Returns a race between timeout promise and the passed promise
264 return Promise.race<T>([promise, timeoutPromise]);
265 }
266
c37528f1 267 /**
0f16a662 268 * Generate a cryptographically secure random number in the [0,1[ range
c37528f1
JB
269 *
270 * @returns
271 */
0f16a662 272 public static secureRandom(): number {
c37528f1
JB
273 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
274 }
7dde0b73 275}