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