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