refactor: cleanup some type casting
[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
4ccf551d
JB
16import {
17 type EmptyObject,
276e05ae
JB
18 type JsonType,
19 MapStringifyFormat,
4ccf551d
JB
20 type TimestampedData,
21 WebSocketCloseEventStatusString
22} from '../types/index.js'
4c3f6c20 23import { Constants } from './Constants.js'
5e3cb728 24
9bf0ef23 25export const logPrefix = (prefixString = ''): string => {
66a7748d
JB
26 return `${new Date().toLocaleString()}${prefixString}`
27}
d5bd1c00 28
2c5c7443 29export const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => {
66a7748d
JB
30 return randomUUID()
31}
147d0e0f 32
2c5c7443
JB
33export const validateUUID = (
34 uuid: `${string}-${string}-${string}-${string}-${string}`
35): uuid is `${string}-${string}-${string}-${string}-${string}` => {
66a7748d
JB
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}
03eacbe5 38
9bf0ef23 39export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
a974c8e4 40 return await new Promise<NodeJS.Timeout>(resolve =>
66a7748d
JB
41 setTimeout(resolve as () => void, milliSeconds)
42 )
43}
7dde0b73 44
9bf0ef23 45export const formatDurationMilliSeconds = (duration: number): string => {
66a7748d 46 duration = convertToInt(duration)
17b07e47 47 if (duration < 0) {
66a7748d 48 throw new RangeError('Duration cannot be negative')
17b07e47 49 }
66a7748d
JB
50 const days = Math.floor(duration / (24 * 3600 * 1000))
51 const hours = Math.floor(millisecondsToHours(duration) - days * 24)
be4c6702 52 const minutes = Math.floor(
66a7748d
JB
53 millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours)
54 )
f0c6601c 55 const seconds = Math.floor(
be4c6702
JB
56 millisecondsToSeconds(duration) -
57 days * 24 * 3600 -
58 hoursToSeconds(hours) -
66a7748d
JB
59 minutesToSeconds(minutes)
60 )
d7ceb0f0 61 if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) {
66a7748d 62 return formatDuration({ seconds }, { zero: true })
d7ceb0f0
JB
63 }
64 return formatDuration({
65 days,
66 hours,
67 minutes,
66a7748d
JB
68 seconds
69 })
70}
7dde0b73 71
9bf0ef23 72export const formatDurationSeconds = (duration: number): string => {
66a7748d
JB
73 return formatDurationMilliSeconds(secondsToMilliseconds(duration))
74}
7dde0b73 75
0bd926c1 76// More efficient time validation function than the one provided by date-fns
5dc7c990 77export const isValidDate = (date: Date | number | undefined): date is Date | number => {
b5c19509 78 if (typeof date === 'number') {
66a7748d 79 return !isNaN(date)
b5c19509 80 } else if (isDate(date)) {
66a7748d 81 return !isNaN(date.getTime())
b5c19509 82 }
66a7748d
JB
83 return false
84}
b5c19509 85
a78c196b 86export const convertToDate = (
5dc7c990 87 value: Date | string | number | undefined | null
79fd697f 88): Date | undefined => {
66a7748d 89 if (value == null) {
79fd697f 90 return undefined
7dde0b73 91 }
0bd926c1 92 if (isDate(value)) {
66a7748d 93 return value
a6e68f34 94 }
9bf0ef23 95 if (isString(value) || typeof value === 'number') {
66a7748d 96 const valueToDate = new Date(value)
85cce27f 97 if (isNaN(valueToDate.getTime())) {
66a7748d 98 throw new Error(`Cannot convert to date: '${value}'`)
43ff25b8 99 }
66a7748d 100 return valueToDate
560bcf5b 101 }
66a7748d 102}
560bcf5b 103
9bf0ef23 104export const convertToInt = (value: unknown): number => {
66a7748d
JB
105 if (value == null) {
106 return 0
560bcf5b 107 }
9bf0ef23 108 if (Number.isSafeInteger(value)) {
66a7748d 109 return value as number
6d3a11a0 110 }
9bf0ef23 111 if (typeof value === 'number') {
66a7748d 112 return Math.trunc(value)
7dde0b73 113 }
f5ee1403 114 let changedValue: number = value as number
9bf0ef23 115 if (isString(value)) {
5dc7c990 116 changedValue = parseInt(value)
9ccca265 117 }
9bf0ef23 118 if (isNaN(changedValue)) {
66a7748d 119 throw new Error(`Cannot convert to integer: '${String(value)}'`)
dada83ec 120 }
66a7748d
JB
121 return changedValue
122}
dada83ec 123
9bf0ef23 124export const convertToFloat = (value: unknown): number => {
66a7748d
JB
125 if (value == null) {
126 return 0
dada83ec 127 }
66a7748d 128 let changedValue: number = value as number
9bf0ef23 129 if (isString(value)) {
5dc7c990 130 changedValue = parseFloat(value)
560bcf5b 131 }
9bf0ef23 132 if (isNaN(changedValue)) {
66a7748d 133 throw new Error(`Cannot convert to float: '${String(value)}'`)
5a2a53cf 134 }
66a7748d
JB
135 return changedValue
136}
5a2a53cf 137
9bf0ef23 138export const convertToBoolean = (value: unknown): boolean => {
66a7748d 139 let result = false
a78c196b 140 if (value != null) {
9bf0ef23
JB
141 // Check the type
142 if (typeof value === 'boolean') {
66a7748d 143 return value
5dc7c990 144 } else if (isString(value) && (value.toLowerCase() === 'true' || value === '1')) {
66a7748d 145 result = true
9bf0ef23 146 } else if (typeof value === 'number' && value === 1) {
66a7748d 147 result = true
e7aeea18 148 }
c37528f1 149 }
66a7748d
JB
150 return result
151}
9bf0ef23
JB
152
153export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => {
154 if (max < min) {
66a7748d 155 throw new RangeError('Invalid interval')
9bf0ef23
JB
156 }
157 if (max - min === Infinity) {
66a7748d 158 throw new RangeError('Invalid interval')
9bf0ef23 159 }
66a7748d
JB
160 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min
161}
9bf0ef23
JB
162
163export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => {
66a7748d 164 max = Math.floor(max)
5199f9fd 165 if (min !== 0) {
66a7748d
JB
166 min = Math.ceil(min)
167 return Math.floor(randomInt(min, max + 1))
9bf0ef23 168 }
66a7748d
JB
169 return Math.floor(randomInt(max + 1))
170}
9bf0ef23
JB
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 */
180export const roundTo = (numberValue: number, scale: number): number => {
66a7748d
JB
181 const roundPower = Math.pow(10, scale)
182 return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower
183}
9bf0ef23
JB
184
185export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => {
5199f9fd 186 if (min !== 0) {
66a7748d 187 return roundTo(getRandomFloat(max, min), scale)
9bf0ef23 188 }
66a7748d
JB
189 return roundTo(getRandomFloat(max), scale)
190}
9bf0ef23
JB
191
192export const getRandomFloatFluctuatedRounded = (
193 staticValue: number,
194 fluctuationPercent: number,
66a7748d 195 scale = 2
9bf0ef23
JB
196): number => {
197 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
198 throw new RangeError(
66a7748d
JB
199 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
200 )
fe791818 201 }
9bf0ef23 202 if (fluctuationPercent === 0) {
66a7748d 203 return roundTo(staticValue, scale)
9bf0ef23 204 }
66a7748d 205 const fluctuationRatio = fluctuationPercent / 100
9bf0ef23
JB
206 return getRandomFloatRounded(
207 staticValue * (1 + fluctuationRatio),
208 staticValue * (1 - fluctuationRatio),
66a7748d
JB
209 scale
210 )
211}
9bf0ef23 212
66a7748d 213export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => {
a974c8e4 214 return timeSeries.map(timeSeriesItem => timeSeriesItem.value)
66a7748d 215}
da55bd34 216
40615072 217export const clone = <T>(object: T): T => {
3fad0dec 218 return structuredClone<T>(object)
66a7748d 219}
9bf0ef23 220
be0a4d4d
JB
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 */
228export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise<unknown> => {
229 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
230}
231
bfcd3a87
JB
232export const isObject = (value: unknown): value is object => {
233 return value != null && typeof value === 'object' && !Array.isArray(value)
234}
235
4ccf551d 236export const isEmptyObject = (object: object): object is EmptyObject => {
bfcd3a87
JB
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
249export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => {
250 return isObject(value) && Object.hasOwn(value, property)
66a7748d 251}
9bf0ef23
JB
252
253export const isCFEnvironment = (): boolean => {
aa63c9b7 254 return env.VCAP_APPLICATION != null
66a7748d 255}
9bf0ef23 256
5dc7c990 257const isString = (value: unknown): value is string => {
66a7748d
JB
258 return typeof value === 'string'
259}
9bf0ef23 260
bfcd3a87 261export const isEmptyString = (value: unknown): value is '' | undefined | null => {
5dc7c990 262 return value == null || (isString(value) && value.trim().length === 0)
66a7748d 263}
9bf0ef23 264
5dc7c990
JB
265export const isNotEmptyString = (value: unknown): value is string => {
266 return isString(value) && value.trim().length > 0
66a7748d 267}
9bf0ef23 268
2c5c7443 269export const isEmptyArray = (value: unknown): value is [] => {
bfcd3a87 270 return Array.isArray(value) && value.length === 0
66a7748d 271}
9bf0ef23 272
bfcd3a87
JB
273export const isNotEmptyArray = (value: unknown): value is unknown[] => {
274 return Array.isArray(value) && value.length > 0
66a7748d 275}
9bf0ef23
JB
276
277export const insertAt = (str: string, subStr: string, pos: number): string =>
66a7748d 278 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
9bf0ef23
JB
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
45abd3c6 284 * @param delayFactor - the base delay factor in milliseconds
9bf0ef23
JB
285 * @returns delay in milliseconds
286 */
45abd3c6 287export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
66a7748d
JB
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}
9bf0ef23 292
9bf0ef23
JB
293/**
294 * Generates a cryptographically secure random number in the [0,1[ range
295 *
ab93b184 296 * @returns A number in the [0,1[ range
9bf0ef23
JB
297 */
298export const secureRandom = (): number => {
66a7748d
JB
299 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
300}
9bf0ef23 301
276e05ae 302export const JSONStringify = <
28f384aa
JB
303 T extends
304 | JsonType
305 | Array<Record<string, unknown>>
306 | Set<Record<string, unknown>>
307 | Map<string, Record<string, unknown>>
276e05ae
JB
308>(
309 object: T,
310 space?: string | number,
311 mapFormat?: MapStringifyFormat
312 ): string => {
9bf0ef23 313 return JSON.stringify(
bfcd3a87 314 object,
58ddf341 315 (_, value: Record<string, unknown>) => {
9bf0ef23 316 if (value instanceof Map) {
276e05ae
JB
317 switch (mapFormat) {
318 case MapStringifyFormat.object:
61877a2e 319 return { ...Object.fromEntries<Map<string, Record<string, unknown>>>(value.entries()) }
276e05ae
JB
320 case MapStringifyFormat.array:
321 default:
322 return [...value]
66a7748d 323 }
276e05ae 324 } else if (value instanceof Set) {
61877a2e 325 return [...value] as JsonType[]
9bf0ef23 326 }
66a7748d 327 return value
9bf0ef23 328 },
66a7748d
JB
329 space
330 )
331}
9bf0ef23
JB
332
333/**
334 * Converts websocket error code to human readable string message
335 *
336 * @param code - websocket error code
337 * @returns human readable string message
338 */
339export const getWebSocketCloseEventStatusString = (code: number): string => {
340 if (code >= 0 && code <= 999) {
66a7748d 341 return '(Unused)'
9bf0ef23
JB
342 } else if (code >= 1016) {
343 if (code <= 1999) {
66a7748d 344 return '(For WebSocket standard)'
9bf0ef23 345 } else if (code <= 2999) {
66a7748d 346 return '(For WebSocket extensions)'
9bf0ef23 347 } else if (code <= 3999) {
66a7748d 348 return '(For libraries and frameworks)'
9bf0ef23 349 } else if (code <= 4999) {
66a7748d 350 return '(For applications)'
5e3cb728 351 }
5e3cb728 352 }
a37fc6dc 353 if (
5199f9fd
JB
354 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
355 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null
a37fc6dc 356 ) {
66a7748d 357 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]
9bf0ef23 358 }
66a7748d
JB
359 return '(Unknown)'
360}
80c58041 361
991fb26b
JB
362export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => {
363 for (let index = 0; index < array.length - 1; ++index) {
364 if (compareFn(array[index], array[index + 1]) > 0) {
66a7748d 365 return false
80c58041
JB
366 }
367 }
66a7748d
JB
368 return true
369}
5f742aac
JB
370
371// eslint-disable-next-line @typescript-eslint/no-explicit-any
372export const once = <T, A extends any[], R>(
373 fn: (...args: A) => R,
66a7748d 374 context: T
5f742aac 375): ((...args: A) => R) => {
66a7748d 376 let result: R
5f742aac 377 return (...args: A) => {
5199f9fd 378 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
66a7748d
JB
379 if (fn != null) {
380 result = fn.apply<T, A, R>(context, args)
381 ;(fn as unknown as undefined) = (context as unknown as undefined) = undefined
5f742aac 382 }
66a7748d
JB
383 return result
384 }
385}
5adf6ca4
JB
386
387export const min = (...args: number[]): number =>
66a7748d 388 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
5adf6ca4
JB
389
390export const max = (...args: number[]): number =>
66a7748d 391 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
29dff95e
JB
392
393export const throwErrorInNextTick = (error: Error): void => {
394 nextTick(() => {
66a7748d
JB
395 throw error
396 })
397}