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