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