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