7ff24ac8a423b7ece4ab779dd87c3972f9dcf2d4
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
1 import { getRandomValues, randomBytes, randomUUID } from 'node:crypto'
2 import { env, nextTick } from 'node:process'
3
4 import {
5 formatDuration,
6 hoursToMinutes,
7 hoursToSeconds,
8 isDate,
9 millisecondsToHours,
10 millisecondsToMinutes,
11 millisecondsToSeconds,
12 minutesToSeconds,
13 secondsToMilliseconds
14 } from 'date-fns'
15
16 import {
17 type JsonType,
18 MapStringifyFormat,
19 type TimestampedData,
20 WebSocketCloseEventStatusString
21 } from '../types/index.js'
22
23 export const logPrefix = (prefixString = ''): string => {
24 return `${new Date().toLocaleString()}${prefixString}`
25 }
26
27 export const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => {
28 return randomUUID()
29 }
30
31 export const validateUUID = (
32 uuid: `${string}-${string}-${string}-${string}-${string}`
33 ): uuid is `${string}-${string}-${string}-${string}-${string}` => {
34 return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(uuid)
35 }
36
37 export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
38 return await new Promise<NodeJS.Timeout>(resolve =>
39 setTimeout(resolve as () => void, milliSeconds)
40 )
41 }
42
43 export const formatDurationMilliSeconds = (duration: number): string => {
44 duration = convertToInt(duration)
45 if (duration < 0) {
46 throw new RangeError('Duration cannot be negative')
47 }
48 const days = Math.floor(duration / (24 * 3600 * 1000))
49 const hours = Math.floor(millisecondsToHours(duration) - days * 24)
50 const minutes = Math.floor(
51 millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours)
52 )
53 const seconds = Math.floor(
54 millisecondsToSeconds(duration) -
55 days * 24 * 3600 -
56 hoursToSeconds(hours) -
57 minutesToSeconds(minutes)
58 )
59 if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) {
60 return formatDuration({ seconds }, { zero: true })
61 }
62 return formatDuration({
63 days,
64 hours,
65 minutes,
66 seconds
67 })
68 }
69
70 export const formatDurationSeconds = (duration: number): string => {
71 return formatDurationMilliSeconds(secondsToMilliseconds(duration))
72 }
73
74 // More efficient time validation function than the one provided by date-fns
75 export const isValidDate = (date: Date | number | undefined): date is Date | number => {
76 if (typeof date === 'number') {
77 return !isNaN(date)
78 } else if (isDate(date)) {
79 return !isNaN(date.getTime())
80 }
81 return false
82 }
83
84 export const convertToDate = (
85 value: Date | string | number | undefined | null
86 ): Date | undefined => {
87 if (value == null) {
88 return undefined
89 }
90 if (isDate(value)) {
91 return value
92 }
93 if (typeof value === 'string' || typeof value === 'number') {
94 const valueToDate = new Date(value)
95 if (isNaN(valueToDate.getTime())) {
96 throw new Error(`Cannot convert to date: '${value}'`)
97 }
98 return valueToDate
99 }
100 }
101
102 export const convertToInt = (value: unknown): number => {
103 if (value == null) {
104 return 0
105 }
106 if (Number.isSafeInteger(value)) {
107 return value as number
108 }
109 if (typeof value === 'number') {
110 return Math.trunc(value)
111 }
112 let changedValue: number = value as number
113 if (typeof value === 'string') {
114 changedValue = parseInt(value)
115 }
116 if (isNaN(changedValue)) {
117 throw new Error(`Cannot convert to integer: '${String(value)}'`)
118 }
119 return changedValue
120 }
121
122 export const convertToFloat = (value: unknown): number => {
123 if (value == null) {
124 return 0
125 }
126 let changedValue: number = value as number
127 if (typeof value === 'string') {
128 changedValue = parseFloat(value)
129 }
130 if (isNaN(changedValue)) {
131 throw new Error(`Cannot convert to float: '${String(value)}'`)
132 }
133 return changedValue
134 }
135
136 export const convertToBoolean = (value: unknown): boolean => {
137 let result = false
138 if (value != null) {
139 // Check the type
140 if (typeof value === 'boolean') {
141 return value
142 } else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value === '1')) {
143 result = true
144 } else if (typeof value === 'number' && value === 1) {
145 result = true
146 }
147 }
148 return result
149 }
150
151 export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => {
152 if (max < min) {
153 throw new RangeError('Invalid interval')
154 }
155 if (max - min === Infinity) {
156 throw new RangeError('Invalid interval')
157 }
158 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min
159 }
160
161 /**
162 * Rounds the given number to the given scale.
163 * The rounding is done using the "round half away from zero" method.
164 *
165 * @param numberValue - The number to round.
166 * @param scale - The scale to round to.
167 * @returns The rounded number.
168 */
169 export const roundTo = (numberValue: number, scale: number): number => {
170 const roundPower = Math.pow(10, scale)
171 return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower
172 }
173
174 export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => {
175 if (min !== 0) {
176 return roundTo(getRandomFloat(max, min), scale)
177 }
178 return roundTo(getRandomFloat(max), scale)
179 }
180
181 export const getRandomFloatFluctuatedRounded = (
182 staticValue: number,
183 fluctuationPercent: number,
184 scale = 2
185 ): number => {
186 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
187 throw new RangeError(
188 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
189 )
190 }
191 if (fluctuationPercent === 0) {
192 return roundTo(staticValue, scale)
193 }
194 const fluctuationRatio = fluctuationPercent / 100
195 return getRandomFloatRounded(
196 staticValue * (1 + fluctuationRatio),
197 staticValue * (1 - fluctuationRatio),
198 scale
199 )
200 }
201
202 export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => {
203 return timeSeries.map(timeSeriesItem => timeSeriesItem.value)
204 }
205
206 export const clone = <T>(object: T): T => {
207 return structuredClone<T>(object)
208 }
209
210 /**
211 * Detects whether the given value is an asynchronous function or not.
212 *
213 * @param fn - Unknown value.
214 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
215 * @internal
216 */
217 export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise<unknown> => {
218 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
219 }
220
221 export const isObject = (value: unknown): value is object => {
222 return value != null && typeof value === 'object' && !Array.isArray(value)
223 }
224
225 export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => {
226 return isObject(value) && Object.hasOwn(value, property)
227 }
228
229 export const isCFEnvironment = (): boolean => {
230 return env.VCAP_APPLICATION != null
231 }
232
233 export const isNotEmptyString = (value: unknown): value is string => {
234 return typeof value === 'string' && value.trim().length > 0
235 }
236
237 export const isNotEmptyArray = (value: unknown): value is unknown[] => {
238 return Array.isArray(value) && value.length > 0
239 }
240
241 export const insertAt = (str: string, subStr: string, pos: number): string =>
242 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
243
244 /**
245 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
246 *
247 * @param retryNumber - the number of retries that have already been attempted
248 * @param delayFactor - the base delay factor in milliseconds
249 * @returns delay in milliseconds
250 */
251 export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
252 const delay = Math.pow(2, retryNumber) * delayFactor
253 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
254 return delay + randomSum
255 }
256
257 /**
258 * Generates a cryptographically secure random number in the [0,1[ range
259 *
260 * @returns A number in the [0,1[ range
261 */
262 export const secureRandom = (): number => {
263 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
264 }
265
266 export const JSONStringify = <
267 T extends
268 | JsonType
269 | Array<Record<string, unknown>>
270 | Set<Record<string, unknown>>
271 | Map<string, Record<string, unknown>>
272 >(
273 object: T,
274 space?: string | number,
275 mapFormat?: MapStringifyFormat
276 ): string => {
277 return JSON.stringify(
278 object,
279 (_, value: Record<string, unknown>) => {
280 if (value instanceof Map) {
281 switch (mapFormat) {
282 case MapStringifyFormat.object:
283 return { ...Object.fromEntries<Map<string, Record<string, unknown>>>(value.entries()) }
284 case MapStringifyFormat.array:
285 default:
286 return [...value]
287 }
288 } else if (value instanceof Set) {
289 return [...value] as JsonType[]
290 }
291 return value
292 },
293 space
294 )
295 }
296
297 /**
298 * Converts websocket error code to human readable string message
299 *
300 * @param code - websocket error code
301 * @returns human readable string message
302 */
303 export const getWebSocketCloseEventStatusString = (code: number): string => {
304 if (code >= 0 && code <= 999) {
305 return '(Unused)'
306 } else if (code >= 1016) {
307 if (code <= 1999) {
308 return '(For WebSocket standard)'
309 } else if (code <= 2999) {
310 return '(For WebSocket extensions)'
311 } else if (code <= 3999) {
312 return '(For libraries and frameworks)'
313 } else if (code <= 4999) {
314 return '(For applications)'
315 }
316 }
317 if (
318 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
319 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null
320 ) {
321 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]
322 }
323 return '(Unknown)'
324 }
325
326 export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => {
327 for (let index = 0; index < array.length - 1; ++index) {
328 if (compareFn(array[index], array[index + 1]) > 0) {
329 return false
330 }
331 }
332 return true
333 }
334
335 export const throwErrorInNextTick = (error: Error): void => {
336 nextTick(() => {
337 throw error
338 })
339 }