Add per phase support to MeterValues in template.
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
1 import Configuration from './Configuration';
2 import { WebSocketCloseEventStatusString } from '../types/WebSocket';
3 import { WorkerProcessType } from '../types/Worker';
4 import { v4 as uuid } from 'uuid';
5
6 export default class Utils {
7 static logPrefix(prefixString = ''): string {
8 return new Date().toLocaleString() + prefixString;
9 }
10
11 static generateUUID(): string {
12 return uuid();
13 }
14
15 static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
16 return new Promise((resolve) => setTimeout(resolve, milliSeconds));
17 }
18
19 static secondsToHHMMSS(seconds: number): string {
20 return Utils.milliSecondsToHHMMSS(seconds * 1000);
21 }
22
23 static milliSecondsToHHMMSS(milliSeconds: number): string {
24 return new Date(milliSeconds).toISOString().substr(11, 8);
25 }
26
27 static removeExtraEmptyLines(tab: string[]): void {
28 // Start from the end
29 for (let i = tab.length - 1; i > 0; i--) {
30 // Two consecutive empty lines?
31 if (tab[i].length === 0 && tab[i - 1].length === 0) {
32 // Remove the last one
33 tab.splice(i, 1);
34 }
35 // Check last line
36 if (i === 1 && tab[i - 1].length === 0) {
37 // Remove the first one
38 tab.splice(i - 1, 1);
39 }
40 }
41 }
42
43 static convertToDate(value: any): Date {
44 // Check
45 if (!value) {
46 return value;
47 }
48 // Check Type
49 if (!(value instanceof Date)) {
50 return new Date(value);
51 }
52 return value;
53 }
54
55 static convertToInt(value: any): number {
56 let changedValue = value;
57 if (!value) {
58 return 0;
59 }
60 if (Number.isSafeInteger(value)) {
61 return value;
62 }
63 // Check
64 if (typeof value === 'string') {
65 // Create Object
66 changedValue = parseInt(value);
67 }
68 return changedValue;
69 }
70
71 static convertToFloat(value: any): number {
72 let changedValue = value;
73 if (!value) {
74 return 0;
75 }
76 // Check
77 if (typeof value === 'string') {
78 // Create Object
79 changedValue = parseFloat(value);
80 }
81 return changedValue;
82 }
83
84 static convertToBoolean(value: any): boolean {
85 let result = false;
86 // Check boolean
87 if (value) {
88 // Check the type
89 if (typeof value === 'boolean') {
90 // Already a boolean
91 result = value;
92 } else {
93 // Convert
94 result = (value === 'true');
95 }
96 }
97 return result;
98 }
99
100 static getRandomFloat(max: number, min = 0): number {
101 return Math.random() < 0.5 ? (1 - Math.random()) * (max - min) + min : Math.random() * (max - min) + min;
102 }
103
104 static getRandomInt(max: number, min = 0): number {
105 if (min) {
106 return Math.floor(Math.random() * (max - min + 1) + min);
107 }
108 return Math.floor(Math.random() * max + 1);
109 }
110
111 static roundTo(numberValue: number, scale: number): number {
112 const roundPower = Math.pow(10, scale);
113 return Math.round(numberValue * roundPower) / roundPower;
114 }
115
116 static truncTo(numberValue: number, scale: number): number {
117 const truncPower = Math.pow(10, scale);
118 return Math.trunc(numberValue * truncPower) / truncPower;
119 }
120
121 static getRandomFloatRounded(max: number, min = 0, scale = 2): number {
122 if (min) {
123 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
124 }
125 return Utils.roundTo(Utils.getRandomFloat(max), scale);
126 }
127
128 static getRandomFloatFluctuatedRounded(staticValue: number, fluctuationPercent: number, scale = 2): number {
129 if (fluctuationPercent === 0) {
130 return Utils.roundTo(staticValue, scale);
131 }
132 return Utils.getRandomFloatRounded(staticValue + staticValue * (fluctuationPercent / 100), staticValue - staticValue * (fluctuationPercent / 100), scale);
133 }
134
135 static cloneObject<T>(object: T): T {
136 return JSON.parse(JSON.stringify(object)) as T;
137 }
138
139 static isIterable<T>(obj: T): boolean {
140 if (obj) {
141 return typeof obj[Symbol.iterator] === 'function';
142 }
143 return false;
144 }
145
146 static isEmptyJSon(document: any): boolean {
147 // Empty?
148 if (!document) {
149 return true;
150 }
151 // Check type
152 if (typeof document !== 'object') {
153 return true;
154 }
155 // Check
156 return Object.keys(document).length === 0;
157 }
158
159 static isString(value: any): boolean {
160 return typeof value === 'string';
161 }
162
163 static isUndefined(value: any): boolean {
164 return typeof value === 'undefined';
165 }
166
167 static isNullOrUndefined(value: any): boolean {
168 // eslint-disable-next-line no-eq-null, eqeqeq
169 if (value == null) {
170 return true;
171 }
172 return false;
173 }
174
175 static isEmptyArray(object: any): boolean {
176 if (!object) {
177 return true;
178 }
179 if (Array.isArray(object) && object.length > 0) {
180 return false;
181 }
182 return true;
183 }
184
185 static isEmptyObject(obj: any): boolean {
186 return !Object.keys(obj).length;
187 }
188
189 static insertAt = (str: string, subStr: string, pos: number): string => `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
190
191 /**
192 * @param {number} [retryNumber=0]
193 * @returns {number} delay in milliseconds
194 */
195 static exponentialDelay(retryNumber = 0): number {
196 const delay = Math.pow(2, retryNumber) * 100;
197 const randomSum = delay * 0.2 * Math.random(); // 0-20% of the delay
198 return delay + randomSum;
199 }
200
201 /**
202 * Convert websocket error code to human readable string message
203 *
204 * @param {number} code websocket error code
205 * @returns {string} human readable string message
206 */
207 static getWebSocketCloseEventStatusString(code: number): string {
208 if (code >= 0 && code <= 999) {
209 return '(Unused)';
210 } else if (code >= 1016) {
211 if (code <= 1999) {
212 return '(For WebSocket standard)';
213 } else if (code <= 2999) {
214 return '(For WebSocket extensions)';
215 } else if (code <= 3999) {
216 return '(For libraries and frameworks)';
217 } else if (code <= 4999) {
218 return '(For applications)';
219 }
220 }
221 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
222 return WebSocketCloseEventStatusString[code] as string;
223 }
224 return '(Unknown)';
225 }
226
227 static workerPoolInUse(): boolean {
228 return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(Configuration.getWorkerProcess());
229 }
230
231 static workerDynamicPoolInUse(): boolean {
232 return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL;
233 }
234 }