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