docs: refine README.md
[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,
a66bbcfe 18 type ProtocolResponse,
4ccf551d
JB
19 type TimestampedData,
20 WebSocketCloseEventStatusString
21} from '../types/index.js'
4c3f6c20 22import { Constants } from './Constants.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 }
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 }
f5ee1403 111 let changedValue: number = value as number
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
40615072 214export const clone = <T>(object: T): T => {
3fad0dec 215 return structuredClone<T>(object)
66a7748d 216}
9bf0ef23 217
be0a4d4d
JB
218/**
219 * Detects whether the given value is an asynchronous function or not.
220 *
221 * @param fn - Unknown value.
222 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
223 * @internal
224 */
225export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise<unknown> => {
226 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
227}
228
bfcd3a87
JB
229export const isObject = (value: unknown): value is object => {
230 return value != null && typeof value === 'object' && !Array.isArray(value)
231}
232
4ccf551d 233export const isEmptyObject = (object: object): object is EmptyObject => {
bfcd3a87
JB
234 if (object.constructor !== Object) {
235 return false
236 }
237 // Iterates over the keys of an object, if
238 // any exist, return false.
239 // eslint-disable-next-line no-unreachable-loop
240 for (const _ in object) {
241 return false
242 }
243 return true
244}
245
246export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => {
247 return isObject(value) && Object.hasOwn(value, property)
66a7748d 248}
9bf0ef23
JB
249
250export const isCFEnvironment = (): boolean => {
aa63c9b7 251 return env.VCAP_APPLICATION != null
66a7748d 252}
9bf0ef23 253
5dc7c990 254const isString = (value: unknown): value is string => {
66a7748d
JB
255 return typeof value === 'string'
256}
9bf0ef23 257
bfcd3a87 258export const isEmptyString = (value: unknown): value is '' | undefined | null => {
5dc7c990 259 return value == null || (isString(value) && value.trim().length === 0)
66a7748d 260}
9bf0ef23 261
5dc7c990
JB
262export const isNotEmptyString = (value: unknown): value is string => {
263 return isString(value) && value.trim().length > 0
66a7748d 264}
9bf0ef23 265
bfcd3a87
JB
266export const isEmptyArray = (value: unknown): value is never[] => {
267 return Array.isArray(value) && value.length === 0
66a7748d 268}
9bf0ef23 269
bfcd3a87
JB
270export const isNotEmptyArray = (value: unknown): value is unknown[] => {
271 return Array.isArray(value) && value.length > 0
66a7748d 272}
9bf0ef23
JB
273
274export const insertAt = (str: string, subStr: string, pos: number): string =>
66a7748d 275 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
9bf0ef23
JB
276
277/**
278 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
279 *
280 * @param retryNumber - the number of retries that have already been attempted
45abd3c6 281 * @param delayFactor - the base delay factor in milliseconds
9bf0ef23
JB
282 * @returns delay in milliseconds
283 */
45abd3c6 284export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
66a7748d
JB
285 const delay = Math.pow(2, retryNumber) * delayFactor
286 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
287 return delay + randomSum
288}
9bf0ef23 289
9bf0ef23
JB
290/**
291 * Generates a cryptographically secure random number in the [0,1[ range
292 *
ab93b184 293 * @returns A number in the [0,1[ range
9bf0ef23
JB
294 */
295export const secureRandom = (): number => {
66a7748d
JB
296 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
297}
9bf0ef23
JB
298
299export const JSONStringifyWithMapSupport = (
a66bbcfe
JB
300 object:
301 | Record<string, unknown>
302 | Array<Record<string, unknown>>
303 | Map<unknown, unknown>
304 | ProtocolResponse,
305 space?: string | number
9bf0ef23
JB
306): string => {
307 return JSON.stringify(
bfcd3a87 308 object,
58ddf341 309 (_, value: Record<string, unknown>) => {
9bf0ef23
JB
310 if (value instanceof Map) {
311 return {
312 dataType: 'Map',
66a7748d
JB
313 value: [...value]
314 }
9bf0ef23 315 }
66a7748d 316 return value
9bf0ef23 317 },
66a7748d
JB
318 space
319 )
320}
9bf0ef23
JB
321
322/**
323 * Converts websocket error code to human readable string message
324 *
325 * @param code - websocket error code
326 * @returns human readable string message
327 */
328export const getWebSocketCloseEventStatusString = (code: number): string => {
329 if (code >= 0 && code <= 999) {
66a7748d 330 return '(Unused)'
9bf0ef23
JB
331 } else if (code >= 1016) {
332 if (code <= 1999) {
66a7748d 333 return '(For WebSocket standard)'
9bf0ef23 334 } else if (code <= 2999) {
66a7748d 335 return '(For WebSocket extensions)'
9bf0ef23 336 } else if (code <= 3999) {
66a7748d 337 return '(For libraries and frameworks)'
9bf0ef23 338 } else if (code <= 4999) {
66a7748d 339 return '(For applications)'
5e3cb728 340 }
5e3cb728 341 }
a37fc6dc 342 if (
5199f9fd
JB
343 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
344 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null
a37fc6dc 345 ) {
66a7748d 346 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]
9bf0ef23 347 }
66a7748d
JB
348 return '(Unknown)'
349}
80c58041 350
991fb26b
JB
351export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => {
352 for (let index = 0; index < array.length - 1; ++index) {
353 if (compareFn(array[index], array[index + 1]) > 0) {
66a7748d 354 return false
80c58041
JB
355 }
356 }
66a7748d
JB
357 return true
358}
5f742aac
JB
359
360// eslint-disable-next-line @typescript-eslint/no-explicit-any
361export const once = <T, A extends any[], R>(
362 fn: (...args: A) => R,
66a7748d 363 context: T
5f742aac 364): ((...args: A) => R) => {
66a7748d 365 let result: R
5f742aac 366 return (...args: A) => {
5199f9fd 367 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
66a7748d
JB
368 if (fn != null) {
369 result = fn.apply<T, A, R>(context, args)
370 ;(fn as unknown as undefined) = (context as unknown as undefined) = undefined
5f742aac 371 }
66a7748d
JB
372 return result
373 }
374}
5adf6ca4
JB
375
376export const min = (...args: number[]): number =>
66a7748d 377 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
5adf6ca4
JB
378
379export const max = (...args: number[]): number =>
66a7748d 380 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
29dff95e
JB
381
382export const throwErrorInNextTick = (error: Error): void => {
383 nextTick(() => {
66a7748d
JB
384 throw error
385 })
386}