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