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