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