Use eslint extension for import sorting instead of unmaintained external ones
[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 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 uuid();
16 }
17
18 public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
19 return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
20 }
21
22 public static formatDurationMilliSeconds(duration: number): string {
23 duration = Utils.convertToInt(duration);
24 const hours = Math.floor(duration / (3600 * 1000));
25 const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
26 const seconds = duration / 1000 - hours * 3600 - minutes * 60;
27 let hoursStr = hours.toString();
28 let minutesStr = minutes.toString();
29 let secondsStr = seconds.toString();
30
31 if (hours < 10) {
32 hoursStr = '0' + hours.toString();
33 }
34 if (minutes < 10) {
35 minutesStr = '0' + minutes.toString();
36 }
37 if (seconds < 10) {
38 secondsStr = '0' + seconds.toString();
39 }
40 return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6);
41 }
42
43 public static formatDurationSeconds(duration: number): string {
44 return Utils.formatDurationMilliSeconds(duration * 1000);
45 }
46
47 public static convertToDate(value: unknown): Date {
48 // Check
49 if (!value) {
50 return value as Date;
51 }
52 // Check Type
53 if (!(value instanceof Date)) {
54 return new Date(value as string);
55 }
56 return value;
57 }
58
59 public static convertToInt(value: unknown): number {
60 let changedValue: number = value as number;
61 if (!value) {
62 return 0;
63 }
64 if (Number.isSafeInteger(value)) {
65 return value as number;
66 }
67 // Check
68 if (Utils.isString(value)) {
69 // Create Object
70 changedValue = parseInt(value as string);
71 }
72 return changedValue;
73 }
74
75 public static convertToFloat(value: unknown): number {
76 let changedValue: number = value as number;
77 if (!value) {
78 return 0;
79 }
80 // Check
81 if (Utils.isString(value)) {
82 // Create Object
83 changedValue = parseFloat(value as string);
84 }
85 return changedValue;
86 }
87
88 public static convertToBoolean(value: unknown): boolean {
89 let result = false;
90 // Check boolean
91 if (value) {
92 // Check the type
93 if (typeof value === 'boolean') {
94 // Already a boolean
95 result = value;
96 } else {
97 // Convert
98 result = value === 'true';
99 }
100 }
101 return result;
102 }
103
104 public static getRandomFloat(max: number, min = 0, negative = false): number {
105 if (max < min || min < 0 || max < 0) {
106 throw new RangeError('Invalid interval');
107 }
108 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
109 const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
110 return sign * (randomPositiveFloat * (max - min) + min);
111 }
112
113 public static getRandomInteger(max: number, min = 0): number {
114 if (max < 0) {
115 throw new RangeError('Invalid interval');
116 }
117 max = Math.floor(max);
118 if (min) {
119 if (max < min || min < 0) {
120 throw new RangeError('Invalid interval');
121 }
122 min = Math.ceil(min);
123 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
124 }
125 return Math.floor(Utils.secureRandom() * (max + 1));
126 }
127
128 public static roundTo(numberValue: number, scale: number): number {
129 const roundPower = Math.pow(10, scale);
130 return Math.round(numberValue * roundPower) / roundPower;
131 }
132
133 public static truncTo(numberValue: number, scale: number): number {
134 const truncPower = Math.pow(10, scale);
135 return Math.trunc(numberValue * truncPower) / truncPower;
136 }
137
138 public static getRandomFloatRounded(max: number, min = 0, scale = 2): number {
139 if (min) {
140 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
141 }
142 return Utils.roundTo(Utils.getRandomFloat(max), scale);
143 }
144
145 public static getRandomFloatFluctuatedRounded(
146 staticValue: number,
147 fluctuationPercent: number,
148 scale = 2
149 ): number {
150 if (fluctuationPercent === 0) {
151 return Utils.roundTo(staticValue, scale);
152 }
153 const fluctuationRatio = fluctuationPercent / 100;
154 return Utils.getRandomFloatRounded(
155 staticValue * (1 + fluctuationRatio),
156 staticValue * (1 - fluctuationRatio),
157 scale
158 );
159 }
160
161 public static cloneObject<T>(object: T): T {
162 return JSON.parse(JSON.stringify(object)) as T;
163 }
164
165 public static isIterable<T>(obj: T): boolean {
166 return obj ? typeof obj[Symbol.iterator] === 'function' : false;
167 }
168
169 public static isString(value: unknown): boolean {
170 return typeof value === 'string';
171 }
172
173 public static isEmptyString(value: unknown): boolean {
174 return Utils.isString(value) && (value as string).length === 0;
175 }
176
177 public static isUndefined(value: unknown): boolean {
178 return typeof value === 'undefined';
179 }
180
181 public static isNullOrUndefined(value: unknown): boolean {
182 // eslint-disable-next-line eqeqeq, no-eq-null
183 return value == null ? true : false;
184 }
185
186 public static isEmptyArray(object: unknown): boolean {
187 if (!object) {
188 return true;
189 }
190 if (Array.isArray(object) && object.length > 0) {
191 return false;
192 }
193 return true;
194 }
195
196 public static isEmptyObject(obj: object): boolean {
197 return !Object.keys(obj).length;
198 }
199
200 public static insertAt = (str: string, subStr: string, pos: number): string =>
201 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
202
203 /**
204 * @param [retryNumber=0]
205 * @returns delay in milliseconds
206 */
207 public static exponentialDelay(retryNumber = 0): number {
208 const delay = Math.pow(2, retryNumber) * 100;
209 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
210 return delay + randomSum;
211 }
212
213 public static async promiseWithTimeout<T>(
214 promise: Promise<T>,
215 timeoutMs: number,
216 timeoutError: Error,
217 timeoutCallback: () => void = () => {
218 /* This is intentional */
219 }
220 ): Promise<T> {
221 // Create a timeout promise that rejects in timeout milliseconds
222 const timeoutPromise = new Promise<never>((_, reject) => {
223 setTimeout(() => {
224 timeoutCallback();
225 reject(timeoutError);
226 }, timeoutMs);
227 });
228
229 // Returns a race between timeout promise and the passed promise
230 return Promise.race<T>([promise, timeoutPromise]);
231 }
232
233 /**
234 * Generate a cryptographically secure random number in the [0,1[ range
235 *
236 * @returns
237 */
238 public static secureRandom(): number {
239 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
240 }
241 }