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