Optimize ATG run duration handling
[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> {
9ac86a7e 17 return new Promise((resolve) => setTimeout(resolve, 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));
d10397af
JB
23 const minutes = Math.floor((duration / 1000 - (hours * 3600)) / 60);
24 const seconds = duration / 1000 - (hours * 3600) - (minutes * 60);
d7d1db72
JB
25 let hoursStr: string = hours.toString();
26 let minutesStr: string = minutes.toString();
27 let secondsStr: string = seconds.toString();
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) {
765a0a4f 36 secondsStr = ('0' + seconds.toString()).substring(0, 6);
d7d1db72
JB
37 }
38 return hoursStr + ':' + minutesStr + ':' + secondsStr;
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 removeExtraEmptyLines(tab: string[]): void {
7dde0b73
JB
46 // Start from the end
47 for (let i = tab.length - 1; i > 0; i--) {
48 // Two consecutive empty lines?
49 if (tab[i].length === 0 && tab[i - 1].length === 0) {
50 // Remove the last one
51 tab.splice(i, 1);
52 }
53 // Check last line
54 if (i === 1 && tab[i - 1].length === 0) {
55 // Remove the first one
56 tab.splice(i - 1, 1);
57 }
58 }
59 }
60
0f16a662 61 public static convertToDate(value: unknown): Date {
560bcf5b 62 // Check
6af9012e 63 if (!value) {
73d09045 64 return value as Date;
560bcf5b
JB
65 }
66 // Check Type
6af9012e 67 if (!(value instanceof Date)) {
73d09045 68 return new Date(value as string);
7dde0b73 69 }
6af9012e 70 return value;
7dde0b73
JB
71 }
72
0f16a662 73 public static convertToInt(value: unknown): number {
73d09045 74 let changedValue: number = value as number;
72766a82 75 if (!value) {
7dde0b73
JB
76 return 0;
77 }
72766a82 78 if (Number.isSafeInteger(value)) {
95926c9b 79 return value as number;
72766a82 80 }
7dde0b73 81 // Check
087a502d 82 if (Utils.isString(value)) {
7dde0b73 83 // Create Object
73d09045 84 changedValue = parseInt(value as string);
7dde0b73 85 }
72766a82 86 return changedValue;
7dde0b73
JB
87 }
88
0f16a662 89 public static convertToFloat(value: unknown): number {
73d09045 90 let changedValue: number = value as number;
72766a82 91 if (!value) {
7dde0b73
JB
92 return 0;
93 }
94 // Check
087a502d 95 if (Utils.isString(value)) {
7dde0b73 96 // Create Object
73d09045 97 changedValue = parseFloat(value as string);
7dde0b73 98 }
72766a82 99 return changedValue;
7dde0b73
JB
100 }
101
0f16a662 102 public static convertToBoolean(value: unknown): boolean {
a6e68f34
JB
103 let result = false;
104 // Check boolean
105 if (value) {
106 // Check the type
107 if (typeof value === 'boolean') {
108 // Already a boolean
109 result = value;
110 } else {
111 // Convert
112 result = (value === 'true');
113 }
114 }
115 return result;
116 }
117
fd00fa2e
JB
118 public static getRandomFloat(max: number, min = 0, negative = false): number {
119 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
120 const sign = (negative && randomPositiveFloat < 0.5) ? 1 : -1;
121 return sign * (randomPositiveFloat * (max - min) + min);
560bcf5b
JB
122 }
123
0f16a662 124 public static getRandomInt(max: number, min = 0): number {
fd00fa2e 125 max = Math.floor(max);
7dde0b73 126 if (min) {
fd00fa2e 127 min = Math.ceil(min);
c37528f1 128 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
7dde0b73 129 }
c37528f1 130 return Math.floor(Utils.secureRandom() * (max + 1));
560bcf5b
JB
131 }
132
0f16a662 133 public static roundTo(numberValue: number, scale: number): number {
ad3de6c4 134 const roundPower = Math.pow(10, scale);
035742f7 135 return Math.round(numberValue * roundPower) / roundPower;
560bcf5b
JB
136 }
137
0f16a662 138 public static truncTo(numberValue: number, scale: number): number {
6d3a11a0 139 const truncPower = Math.pow(10, scale);
035742f7 140 return Math.trunc(numberValue * truncPower) / truncPower;
6d3a11a0
JB
141 }
142
0f16a662 143 public static getRandomFloatRounded(max: number, min = 0, scale = 2): number {
560bcf5b
JB
144 if (min) {
145 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
146 }
147 return Utils.roundTo(Utils.getRandomFloat(max), scale);
7dde0b73
JB
148 }
149
0f16a662 150 public static getRandomFloatFluctuatedRounded(staticValue: number, fluctuationPercent: number, scale = 2): number {
9ccca265
JB
151 if (fluctuationPercent === 0) {
152 return Utils.roundTo(staticValue, scale);
153 }
97ef739c
JB
154 const fluctuationRatio = fluctuationPercent / 100;
155 return Utils.getRandomFloatRounded(staticValue * (1 + fluctuationRatio), staticValue * (1 - fluctuationRatio), scale);
9ccca265
JB
156 }
157
0f16a662 158 public static cloneObject<T>(object: T): T {
e56aa9a4 159 return JSON.parse(JSON.stringify(object)) as T;
2e6f5966 160 }
facd8ebd 161
0f16a662 162 public static isIterable<T>(obj: T): boolean {
67e9cccf
JB
163 if (obj) {
164 return typeof obj[Symbol.iterator] === 'function';
165 }
166 return false;
167 }
168
0f16a662 169 public static isEmptyJSon(document: unknown): boolean {
67e9cccf
JB
170 // Empty?
171 if (!document) {
172 return true;
173 }
174 // Check type
175 if (typeof document !== 'object') {
176 return true;
177 }
178 // Check
179 return Object.keys(document).length === 0;
180 }
181
0f16a662 182 public static isString(value: unknown): boolean {
560bcf5b
JB
183 return typeof value === 'string';
184 }
185
0f16a662 186 public static isUndefined(value: unknown): boolean {
ead548f2
JB
187 return typeof value === 'undefined';
188 }
189
0f16a662 190 public static isNullOrUndefined(value: unknown): boolean {
32a1eb7a 191 // eslint-disable-next-line no-eq-null, eqeqeq
ead548f2 192 if (value == null) {
facd8ebd
JB
193 return true;
194 }
195 return false;
196 }
4a56deef 197
0f16a662 198 public static isEmptyArray(object: unknown): boolean {
fd1ee77c
JB
199 if (!object) {
200 return true;
201 }
4a56deef
JB
202 if (Array.isArray(object) && object.length > 0) {
203 return false;
204 }
205 return true;
206 }
7abfea5f 207
0f16a662 208 public static isEmptyObject(obj: Record<string, unknown>): boolean {
7abfea5f
JB
209 return !Object.keys(obj).length;
210 }
7ec46a9a 211
0f16a662 212 public static insertAt = (str: string, subStr: string, pos: number): string => `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
032d6efc
JB
213
214 /**
81797102
JB
215 * @param [retryNumber=0]
216 * @returns delay in milliseconds
032d6efc 217 */
0f16a662 218 public static exponentialDelay(retryNumber = 0): number {
032d6efc 219 const delay = Math.pow(2, retryNumber) * 100;
c37528f1 220 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
032d6efc
JB
221 return delay + randomSum;
222 }
32a1eb7a 223
e71cccf3
JB
224 /**
225 * Convert websocket error code to human readable string message
226 *
81797102
JB
227 * @param code websocket error code
228 * @returns human readable string message
e71cccf3 229 */
0f16a662 230 public static getWebSocketCloseEventStatusString(code: number): string {
32a1eb7a
JB
231 if (code >= 0 && code <= 999) {
232 return '(Unused)';
233 } else if (code >= 1016) {
234 if (code <= 1999) {
235 return '(For WebSocket standard)';
236 } else if (code <= 2999) {
237 return '(For WebSocket extensions)';
238 } else if (code <= 3999) {
239 return '(For libraries and frameworks)';
240 } else if (code <= 4999) {
241 return '(For applications)';
242 }
243 }
244 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
17991e8c 245 return WebSocketCloseEventStatusString[code] as string;
32a1eb7a
JB
246 }
247 return '(Unknown)';
248 }
a4624c96 249
0f16a662 250 public static workerPoolInUse(): boolean {
9ab7950c 251 return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(Configuration.getWorkerProcess());
a4624c96 252 }
059f35a5 253
0f16a662 254 public static workerDynamicPoolInUse(): boolean {
059f35a5
JB
255 return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL;
256 }
c37528f1
JB
257
258 /**
0f16a662 259 * Generate a cryptographically secure random number in the [0,1[ range
c37528f1
JB
260 *
261 * @returns
262 */
0f16a662 263 public static secureRandom(): number {
c37528f1
JB
264 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
265 }
7dde0b73 266}