Merge dependabot/npm_and_yarn/prettier-3.2.4 into combined-prs-branch
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
1 import { getRandomValues, randomBytes, randomInt, randomUUID } from 'node:crypto'
2 import { env, nextTick } from 'node:process'
3
4 import {
5 formatDuration,
6 hoursToMinutes,
7 hoursToSeconds,
8 isDate,
9 millisecondsToHours,
10 millisecondsToMinutes,
11 millisecondsToSeconds,
12 minutesToSeconds,
13 secondsToMilliseconds
14 } from 'date-fns'
15
16 import { Constants } from './Constants.js'
17 import {
18 type EmptyObject,
19 type TimestampedData,
20 WebSocketCloseEventStatusString
21 } from '../types/index.js'
22
23 export const logPrefix = (prefixString = ''): string => {
24 return `${new Date().toLocaleString()}${prefixString}`
25 }
26
27 export const generateUUID = (): string => {
28 return randomUUID()
29 }
30
31 export const validateUUID = (uuid: string): boolean => {
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 }
34
35 export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
36 return await new Promise<NodeJS.Timeout>(resolve =>
37 setTimeout(resolve as () => void, milliSeconds)
38 )
39 }
40
41 export const formatDurationMilliSeconds = (duration: number): string => {
42 duration = convertToInt(duration)
43 if (duration < 0) {
44 throw new RangeError('Duration cannot be negative')
45 }
46 const days = Math.floor(duration / (24 * 3600 * 1000))
47 const hours = Math.floor(millisecondsToHours(duration) - days * 24)
48 const minutes = Math.floor(
49 millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours)
50 )
51 const seconds = Math.floor(
52 millisecondsToSeconds(duration) -
53 days * 24 * 3600 -
54 hoursToSeconds(hours) -
55 minutesToSeconds(minutes)
56 )
57 if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) {
58 return formatDuration({ seconds }, { zero: true })
59 }
60 return formatDuration({
61 days,
62 hours,
63 minutes,
64 seconds
65 })
66 }
67
68 export const formatDurationSeconds = (duration: number): string => {
69 return formatDurationMilliSeconds(secondsToMilliseconds(duration))
70 }
71
72 // More efficient time validation function than the one provided by date-fns
73 export const isValidDate = (date: Date | number | undefined): date is Date | number => {
74 if (typeof date === 'number') {
75 return !isNaN(date)
76 } else if (isDate(date)) {
77 return !isNaN(date.getTime())
78 }
79 return false
80 }
81
82 export const convertToDate = (
83 value: Date | string | number | undefined | null
84 ): Date | undefined => {
85 if (value == null) {
86 return undefined
87 }
88 if (isDate(value)) {
89 return value
90 }
91 if (isString(value) || typeof value === 'number') {
92 const valueToDate = new Date(value)
93 if (isNaN(valueToDate.getTime())) {
94 throw new Error(`Cannot convert to date: '${value}'`)
95 }
96 return valueToDate
97 }
98 }
99
100 export const convertToInt = (value: unknown): number => {
101 if (value == null) {
102 return 0
103 }
104 let changedValue: number = value as number
105 if (Number.isSafeInteger(value)) {
106 return value as number
107 }
108 if (typeof value === 'number') {
109 return Math.trunc(value)
110 }
111 if (isString(value)) {
112 changedValue = parseInt(value)
113 }
114 if (isNaN(changedValue)) {
115 throw new Error(`Cannot convert to integer: '${String(value)}'`)
116 }
117 return changedValue
118 }
119
120 export const convertToFloat = (value: unknown): number => {
121 if (value == null) {
122 return 0
123 }
124 let changedValue: number = value as number
125 if (isString(value)) {
126 changedValue = parseFloat(value)
127 }
128 if (isNaN(changedValue)) {
129 throw new Error(`Cannot convert to float: '${String(value)}'`)
130 }
131 return changedValue
132 }
133
134 export const convertToBoolean = (value: unknown): boolean => {
135 let result = false
136 if (value != null) {
137 // Check the type
138 if (typeof value === 'boolean') {
139 return value
140 } else if (isString(value) && (value.toLowerCase() === 'true' || value === '1')) {
141 result = true
142 } else if (typeof value === 'number' && value === 1) {
143 result = true
144 }
145 }
146 return result
147 }
148
149 export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => {
150 if (max < min) {
151 throw new RangeError('Invalid interval')
152 }
153 if (max - min === Infinity) {
154 throw new RangeError('Invalid interval')
155 }
156 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min
157 }
158
159 export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => {
160 max = Math.floor(max)
161 if (min !== 0) {
162 min = Math.ceil(min)
163 return Math.floor(randomInt(min, max + 1))
164 }
165 return Math.floor(randomInt(max + 1))
166 }
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 */
176 export const roundTo = (numberValue: number, scale: number): number => {
177 const roundPower = Math.pow(10, scale)
178 return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower
179 }
180
181 export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => {
182 if (min !== 0) {
183 return roundTo(getRandomFloat(max, min), scale)
184 }
185 return roundTo(getRandomFloat(max), scale)
186 }
187
188 export const getRandomFloatFluctuatedRounded = (
189 staticValue: number,
190 fluctuationPercent: number,
191 scale = 2
192 ): number => {
193 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
194 throw new RangeError(
195 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
196 )
197 }
198 if (fluctuationPercent === 0) {
199 return roundTo(staticValue, scale)
200 }
201 const fluctuationRatio = fluctuationPercent / 100
202 return getRandomFloatRounded(
203 staticValue * (1 + fluctuationRatio),
204 staticValue * (1 - fluctuationRatio),
205 scale
206 )
207 }
208
209 export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => {
210 return timeSeries.map(timeSeriesItem => timeSeriesItem.value)
211 }
212
213 type CloneableData =
214 | number
215 | string
216 | boolean
217 | null
218 | undefined
219 | Date
220 | CloneableData[]
221 | { [key: string]: CloneableData }
222
223 type FormatKey = (key: string) => string
224
225 const deepClone = <I extends CloneableData, O extends CloneableData = I>(
226 value: I,
227 formatKey?: FormatKey,
228 refs: Map<I, O> = new Map<I, O>()
229 ): O => {
230 const ref = refs.get(value)
231 if (ref !== undefined) {
232 return ref
233 }
234 if (Array.isArray(value)) {
235 const clone: CloneableData[] = []
236 refs.set(value, clone as O)
237 for (let i = 0; i < value.length; i++) {
238 clone[i] = deepClone(value[i], formatKey, refs)
239 }
240 return clone as O
241 }
242 if (value instanceof Date) {
243 return new Date(value.getTime()) as O
244 }
245 if (typeof value !== 'object' || value === null) {
246 return value as unknown as O
247 }
248 const clone: Record<string, CloneableData> = {}
249 refs.set(value, clone as O)
250 for (const key of Object.keys(value)) {
251 clone[typeof formatKey === 'function' ? formatKey(key) : key] = deepClone(
252 value[key],
253 formatKey,
254 refs
255 )
256 }
257 return clone as O
258 }
259
260 export const clone = <T>(object: T): T => {
261 return deepClone(object as CloneableData) as T
262 }
263
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 */
271 export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise<unknown> => {
272 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
273 }
274
275 export const isObject = (value: unknown): value is object => {
276 return value != null && typeof value === 'object' && !Array.isArray(value)
277 }
278
279 export const isEmptyObject = (object: object): object is EmptyObject => {
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
292 export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => {
293 return isObject(value) && Object.hasOwn(value, property)
294 }
295
296 export const isCFEnvironment = (): boolean => {
297 return env.VCAP_APPLICATION != null
298 }
299
300 const isString = (value: unknown): value is string => {
301 return typeof value === 'string'
302 }
303
304 export const isEmptyString = (value: unknown): value is '' | undefined | null => {
305 return value == null || (isString(value) && value.trim().length === 0)
306 }
307
308 export const isNotEmptyString = (value: unknown): value is string => {
309 return isString(value) && value.trim().length > 0
310 }
311
312 export const isEmptyArray = (value: unknown): value is never[] => {
313 return Array.isArray(value) && value.length === 0
314 }
315
316 export const isNotEmptyArray = (value: unknown): value is unknown[] => {
317 return Array.isArray(value) && value.length > 0
318 }
319
320 export const insertAt = (str: string, subStr: string, pos: number): string =>
321 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
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
327 * @param delayFactor - the base delay factor in milliseconds
328 * @returns delay in milliseconds
329 */
330 export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
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 }
335
336 /**
337 * Generates a cryptographically secure random number in the [0,1[ range
338 *
339 * @returns A number in the [0,1[ range
340 */
341 export const secureRandom = (): number => {
342 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
343 }
344
345 export const JSONStringifyWithMapSupport = (
346 object: Record<string, unknown> | Array<Record<string, unknown>> | Map<unknown, unknown>,
347 space?: number
348 ): string => {
349 return JSON.stringify(
350 object,
351 (_, value: Record<string, unknown>) => {
352 if (value instanceof Map) {
353 return {
354 dataType: 'Map',
355 value: [...value]
356 }
357 }
358 return value
359 },
360 space
361 )
362 }
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 */
370 export const getWebSocketCloseEventStatusString = (code: number): string => {
371 if (code >= 0 && code <= 999) {
372 return '(Unused)'
373 } else if (code >= 1016) {
374 if (code <= 1999) {
375 return '(For WebSocket standard)'
376 } else if (code <= 2999) {
377 return '(For WebSocket extensions)'
378 } else if (code <= 3999) {
379 return '(For libraries and frameworks)'
380 } else if (code <= 4999) {
381 return '(For applications)'
382 }
383 }
384 if (
385 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
386 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null
387 ) {
388 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]
389 }
390 return '(Unknown)'
391 }
392
393 export 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) {
396 return false
397 }
398 }
399 return true
400 }
401
402 // eslint-disable-next-line @typescript-eslint/no-explicit-any
403 export const once = <T, A extends any[], R>(
404 fn: (...args: A) => R,
405 context: T
406 ): ((...args: A) => R) => {
407 let result: R
408 return (...args: A) => {
409 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
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
413 }
414 return result
415 }
416 }
417
418 export const min = (...args: number[]): number =>
419 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
420
421 export const max = (...args: number[]): number =>
422 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
423
424 export const throwErrorInNextTick = (error: Error): void => {
425 nextTick(() => {
426 throw error
427 })
428 }