Add UI protocol Insomnia project export instead of just the collection
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
CommitLineData
c37528f1 1import crypto from 'crypto';
8114d10e 2
6af9012e 3import { v4 as uuid } from 'uuid';
7dde0b73 4
3f40bc9c 5export default class Utils {
d5bd1c00
JB
6 private constructor() {
7 // This is intentional
8 }
9
0f16a662 10 public static logPrefix(prefixString = ''): string {
147d0e0f
JB
11 return new Date().toLocaleString() + prefixString;
12 }
13
0f16a662 14 public static generateUUID(): string {
2e3ac96d 15 return uuid();
7dde0b73
JB
16 }
17
0f16a662 18 public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
5f8a4fd6 19 return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
7dde0b73
JB
20 }
21
d7d1db72
JB
22 public static formatDurationMilliSeconds(duration: number): string {
23 duration = Utils.convertToInt(duration);
24 const hours = Math.floor(duration / (3600 * 1000));
e7aeea18
JB
25 const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
26 const seconds = duration / 1000 - hours * 3600 - minutes * 60;
a3868ec4
JB
27 let hoursStr = hours.toString();
28 let minutesStr = minutes.toString();
29 let secondsStr = seconds.toString();
d7d1db72
JB
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) {
b322b8b4 38 secondsStr = '0' + seconds.toString();
d7d1db72 39 }
b322b8b4 40 return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6);
9ac86a7e
JB
41 }
42
d7d1db72
JB
43 public static formatDurationSeconds(duration: number): string {
44 return Utils.formatDurationMilliSeconds(duration * 1000);
7dde0b73
JB
45 }
46
0f16a662 47 public static convertToDate(value: unknown): Date {
560bcf5b 48 // Check
6af9012e 49 if (!value) {
73d09045 50 return value as Date;
560bcf5b
JB
51 }
52 // Check Type
6af9012e 53 if (!(value instanceof Date)) {
73d09045 54 return new Date(value as string);
7dde0b73 55 }
6af9012e 56 return value;
7dde0b73
JB
57 }
58
0f16a662 59 public static convertToInt(value: unknown): number {
73d09045 60 let changedValue: number = value as number;
72766a82 61 if (!value) {
7dde0b73
JB
62 return 0;
63 }
72766a82 64 if (Number.isSafeInteger(value)) {
95926c9b 65 return value as number;
72766a82 66 }
7dde0b73 67 // Check
087a502d 68 if (Utils.isString(value)) {
7dde0b73 69 // Create Object
73d09045 70 changedValue = parseInt(value as string);
7dde0b73 71 }
72766a82 72 return changedValue;
7dde0b73
JB
73 }
74
0f16a662 75 public static convertToFloat(value: unknown): number {
73d09045 76 let changedValue: number = value as number;
72766a82 77 if (!value) {
7dde0b73
JB
78 return 0;
79 }
80 // Check
087a502d 81 if (Utils.isString(value)) {
7dde0b73 82 // Create Object
73d09045 83 changedValue = parseFloat(value as string);
7dde0b73 84 }
72766a82 85 return changedValue;
7dde0b73
JB
86 }
87
0f16a662 88 public static convertToBoolean(value: unknown): boolean {
a6e68f34
JB
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
e7aeea18 98 result = value === 'true';
a6e68f34
JB
99 }
100 }
101 return result;
102 }
103
fd00fa2e 104 public static getRandomFloat(max: number, min = 0, negative = false): number {
b322b8b4
JB
105 if (max < min || min < 0 || max < 0) {
106 throw new RangeError('Invalid interval');
107 }
fd00fa2e 108 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
e7aeea18 109 const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
fd00fa2e 110 return sign * (randomPositiveFloat * (max - min) + min);
560bcf5b
JB
111 }
112
72740232 113 public static getRandomInteger(max: number, min = 0): number {
a3868ec4
JB
114 if (max < 0) {
115 throw new RangeError('Invalid interval');
116 }
fd00fa2e 117 max = Math.floor(max);
7dde0b73 118 if (min) {
a3868ec4
JB
119 if (max < min || min < 0) {
120 throw new RangeError('Invalid interval');
121 }
fd00fa2e 122 min = Math.ceil(min);
c37528f1 123 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
7dde0b73 124 }
c37528f1 125 return Math.floor(Utils.secureRandom() * (max + 1));
560bcf5b
JB
126 }
127
0f16a662 128 public static roundTo(numberValue: number, scale: number): number {
ad3de6c4 129 const roundPower = Math.pow(10, scale);
035742f7 130 return Math.round(numberValue * roundPower) / roundPower;
560bcf5b
JB
131 }
132
0f16a662 133 public static truncTo(numberValue: number, scale: number): number {
6d3a11a0 134 const truncPower = Math.pow(10, scale);
035742f7 135 return Math.trunc(numberValue * truncPower) / truncPower;
6d3a11a0
JB
136 }
137
0f16a662 138 public static getRandomFloatRounded(max: number, min = 0, scale = 2): number {
560bcf5b
JB
139 if (min) {
140 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
141 }
142 return Utils.roundTo(Utils.getRandomFloat(max), scale);
7dde0b73
JB
143 }
144
e7aeea18
JB
145 public static getRandomFloatFluctuatedRounded(
146 staticValue: number,
147 fluctuationPercent: number,
148 scale = 2
149 ): number {
9ccca265
JB
150 if (fluctuationPercent === 0) {
151 return Utils.roundTo(staticValue, scale);
152 }
97ef739c 153 const fluctuationRatio = fluctuationPercent / 100;
e7aeea18
JB
154 return Utils.getRandomFloatRounded(
155 staticValue * (1 + fluctuationRatio),
156 staticValue * (1 - fluctuationRatio),
157 scale
158 );
9ccca265
JB
159 }
160
0f16a662 161 public static cloneObject<T>(object: T): T {
e56aa9a4 162 return JSON.parse(JSON.stringify(object)) as T;
2e6f5966 163 }
facd8ebd 164
0f16a662 165 public static isIterable<T>(obj: T): boolean {
7558b3a6 166 return obj ? typeof obj[Symbol.iterator] === 'function' : false;
67e9cccf
JB
167 }
168
0f16a662 169 public static isString(value: unknown): boolean {
560bcf5b
JB
170 return typeof value === 'string';
171 }
172
e8191622
JB
173 public static isEmptyString(value: unknown): boolean {
174 return Utils.isString(value) && (value as string).length === 0;
175 }
176
0f16a662 177 public static isUndefined(value: unknown): boolean {
ead548f2
JB
178 return typeof value === 'undefined';
179 }
180
0f16a662 181 public static isNullOrUndefined(value: unknown): boolean {
7558b3a6
JB
182 // eslint-disable-next-line eqeqeq, no-eq-null
183 return value == null ? true : false;
facd8ebd 184 }
4a56deef 185
0f16a662 186 public static isEmptyArray(object: unknown): boolean {
fd1ee77c
JB
187 if (!object) {
188 return true;
189 }
4a56deef
JB
190 if (Array.isArray(object) && object.length > 0) {
191 return false;
192 }
193 return true;
194 }
7abfea5f 195
94ec7e96 196 public static isEmptyObject(obj: object): boolean {
7abfea5f
JB
197 return !Object.keys(obj).length;
198 }
7ec46a9a 199
e7aeea18
JB
200 public static insertAt = (str: string, subStr: string, pos: number): string =>
201 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
032d6efc
JB
202
203 /**
81797102
JB
204 * @param [retryNumber=0]
205 * @returns delay in milliseconds
032d6efc 206 */
0f16a662 207 public static exponentialDelay(retryNumber = 0): number {
032d6efc 208 const delay = Math.pow(2, retryNumber) * 100;
c37528f1 209 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
032d6efc
JB
210 return delay + randomSum;
211 }
32a1eb7a 212
6d9abcc2 213 public static async promiseWithTimeout<T>(
e7aeea18
JB
214 promise: Promise<T>,
215 timeoutMs: number,
216 timeoutError: Error,
217 timeoutCallback: () => void = () => {
218 /* This is intentional */
219 }
6d9abcc2
JB
220 ): Promise<T> {
221 // Create a timeout promise that rejects in timeout milliseconds
222 const timeoutPromise = new Promise<never>((_, reject) => {
223 setTimeout(() => {
ed0f8380 224 timeoutCallback();
6d9abcc2
JB
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
c37528f1 233 /**
0f16a662 234 * Generate a cryptographically secure random number in the [0,1[ range
c37528f1
JB
235 *
236 * @returns
237 */
0f16a662 238 public static secureRandom(): number {
c37528f1
JB
239 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
240 }
7dde0b73 241}