Add sanity checks to random number generation code
[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) {
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
96 result = (value === 'true');
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
JB
106 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
107 const sign = (negative && randomPositiveFloat < 0.5) ? 1 : -1;
108 return sign * (randomPositiveFloat * (max - min) + min);
560bcf5b
JB
109 }
110
0f16a662 111 public static getRandomInt(max: number, min = 0): number {
fd00fa2e 112 max = Math.floor(max);
7dde0b73 113 if (min) {
fd00fa2e 114 min = Math.ceil(min);
c37528f1 115 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
7dde0b73 116 }
c37528f1 117 return Math.floor(Utils.secureRandom() * (max + 1));
560bcf5b
JB
118 }
119
0f16a662 120 public static roundTo(numberValue: number, scale: number): number {
ad3de6c4 121 const roundPower = Math.pow(10, scale);
035742f7 122 return Math.round(numberValue * roundPower) / roundPower;
560bcf5b
JB
123 }
124
0f16a662 125 public static truncTo(numberValue: number, scale: number): number {
6d3a11a0 126 const truncPower = Math.pow(10, scale);
035742f7 127 return Math.trunc(numberValue * truncPower) / truncPower;
6d3a11a0
JB
128 }
129
0f16a662 130 public static getRandomFloatRounded(max: number, min = 0, scale = 2): number {
560bcf5b
JB
131 if (min) {
132 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
133 }
134 return Utils.roundTo(Utils.getRandomFloat(max), scale);
7dde0b73
JB
135 }
136
0f16a662 137 public static getRandomFloatFluctuatedRounded(staticValue: number, fluctuationPercent: number, scale = 2): number {
9ccca265
JB
138 if (fluctuationPercent === 0) {
139 return Utils.roundTo(staticValue, scale);
140 }
97ef739c
JB
141 const fluctuationRatio = fluctuationPercent / 100;
142 return Utils.getRandomFloatRounded(staticValue * (1 + fluctuationRatio), staticValue * (1 - fluctuationRatio), scale);
9ccca265
JB
143 }
144
0f16a662 145 public static cloneObject<T>(object: T): T {
e56aa9a4 146 return JSON.parse(JSON.stringify(object)) as T;
2e6f5966 147 }
facd8ebd 148
0f16a662 149 public static isIterable<T>(obj: T): boolean {
67e9cccf
JB
150 if (obj) {
151 return typeof obj[Symbol.iterator] === 'function';
152 }
153 return false;
154 }
155
0f16a662 156 public static isString(value: unknown): boolean {
560bcf5b
JB
157 return typeof value === 'string';
158 }
159
0f16a662 160 public static isUndefined(value: unknown): boolean {
ead548f2
JB
161 return typeof value === 'undefined';
162 }
163
0f16a662 164 public static isNullOrUndefined(value: unknown): boolean {
32a1eb7a 165 // eslint-disable-next-line no-eq-null, eqeqeq
ead548f2 166 if (value == null) {
facd8ebd
JB
167 return true;
168 }
169 return false;
170 }
4a56deef 171
0f16a662 172 public static isEmptyArray(object: unknown): boolean {
fd1ee77c
JB
173 if (!object) {
174 return true;
175 }
4a56deef
JB
176 if (Array.isArray(object) && object.length > 0) {
177 return false;
178 }
179 return true;
180 }
7abfea5f 181
0f16a662 182 public static isEmptyObject(obj: Record<string, unknown>): boolean {
7abfea5f
JB
183 return !Object.keys(obj).length;
184 }
7ec46a9a 185
0f16a662 186 public static insertAt = (str: string, subStr: string, pos: number): string => `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
032d6efc
JB
187
188 /**
81797102
JB
189 * @param [retryNumber=0]
190 * @returns delay in milliseconds
032d6efc 191 */
0f16a662 192 public static exponentialDelay(retryNumber = 0): number {
032d6efc 193 const delay = Math.pow(2, retryNumber) * 100;
c37528f1 194 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
032d6efc
JB
195 return delay + randomSum;
196 }
32a1eb7a 197
e71cccf3
JB
198 /**
199 * Convert websocket error code to human readable string message
200 *
81797102
JB
201 * @param code websocket error code
202 * @returns human readable string message
e71cccf3 203 */
0f16a662 204 public static getWebSocketCloseEventStatusString(code: number): string {
32a1eb7a
JB
205 if (code >= 0 && code <= 999) {
206 return '(Unused)';
207 } else if (code >= 1016) {
208 if (code <= 1999) {
209 return '(For WebSocket standard)';
210 } else if (code <= 2999) {
211 return '(For WebSocket extensions)';
212 } else if (code <= 3999) {
213 return '(For libraries and frameworks)';
214 } else if (code <= 4999) {
215 return '(For applications)';
216 }
217 }
218 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
17991e8c 219 return WebSocketCloseEventStatusString[code] as string;
32a1eb7a
JB
220 }
221 return '(Unknown)';
222 }
a4624c96 223
0f16a662 224 public static workerPoolInUse(): boolean {
9ab7950c 225 return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(Configuration.getWorkerProcess());
a4624c96 226 }
059f35a5 227
0f16a662 228 public static workerDynamicPoolInUse(): boolean {
059f35a5
JB
229 return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL;
230 }
c37528f1
JB
231
232 /**
0f16a662 233 * Generate a cryptographically secure random number in the [0,1[ range
c37528f1
JB
234 *
235 * @returns
236 */
0f16a662 237 public static secureRandom(): number {
c37528f1
JB
238 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
239 }
7dde0b73 240}