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