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