build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
1 import { getRandomValues, randomBytes, 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 import type { CircularBuffer } from 'mnemonist'
16 import { is } from 'rambda'
17
18 import {
19 type JsonType,
20 MapStringifyFormat,
21 type TimestampedData,
22 WebSocketCloseEventStatusString
23 } from '../types/index.js'
24
25 export const logPrefix = (prefixString = ''): string => {
26 return `${new Date().toLocaleString()}${prefixString}`
27 }
28
29 export const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => {
30 return randomUUID()
31 }
32
33 export const validateUUID = (
34 uuid: `${string}-${string}-${string}-${string}-${string}`
35 ): uuid is `${string}-${string}-${string}-${string}-${string}` => {
36 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)
37 }
38
39 export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
40 return await new Promise<NodeJS.Timeout>(resolve =>
41 setTimeout(resolve as () => void, milliSeconds)
42 )
43 }
44
45 export const formatDurationMilliSeconds = (duration: number): string => {
46 duration = convertToInt(duration)
47 if (duration < 0) {
48 throw new RangeError('Duration cannot be negative')
49 }
50 const days = Math.floor(duration / (24 * 3600 * 1000))
51 const hours = Math.floor(millisecondsToHours(duration) - days * 24)
52 const minutes = Math.floor(
53 millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours)
54 )
55 const seconds = Math.floor(
56 millisecondsToSeconds(duration) -
57 days * 24 * 3600 -
58 hoursToSeconds(hours) -
59 minutesToSeconds(minutes)
60 )
61 if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) {
62 return formatDuration({ seconds }, { zero: true })
63 }
64 return formatDuration({
65 days,
66 hours,
67 minutes,
68 seconds
69 })
70 }
71
72 export const formatDurationSeconds = (duration: number): string => {
73 return formatDurationMilliSeconds(secondsToMilliseconds(duration))
74 }
75
76 // More efficient time validation function than the one provided by date-fns
77 export const isValidDate = (date: Date | number | undefined): date is Date | number => {
78 if (typeof date === 'number') {
79 return !isNaN(date)
80 } else if (isDate(date)) {
81 return !isNaN(date.getTime())
82 }
83 return false
84 }
85
86 export const convertToDate = (
87 value: Date | string | number | undefined | null
88 ): Date | undefined => {
89 if (value == null) {
90 return undefined
91 }
92 if (isDate(value)) {
93 return value
94 }
95 if (typeof value === 'string' || typeof value === 'number') {
96 const valueToDate = new Date(value)
97 if (isNaN(valueToDate.getTime())) {
98 throw new Error(`Cannot convert to date: '${value}'`)
99 }
100 return valueToDate
101 }
102 }
103
104 export const convertToInt = (value: unknown): number => {
105 if (value == null) {
106 return 0
107 }
108 if (Number.isSafeInteger(value)) {
109 return value as number
110 }
111 if (typeof value === 'number') {
112 return Math.trunc(value)
113 }
114 let changedValue: number = value as number
115 if (typeof value === 'string') {
116 changedValue = Number.parseInt(value)
117 }
118 if (isNaN(changedValue)) {
119 throw new Error(`Cannot convert to integer: '${String(value)}'`)
120 }
121 return changedValue
122 }
123
124 export const convertToFloat = (value: unknown): number => {
125 if (value == null) {
126 return 0
127 }
128 let changedValue: number = value as number
129 if (typeof value === 'string') {
130 changedValue = Number.parseFloat(value)
131 }
132 if (isNaN(changedValue)) {
133 throw new Error(`Cannot convert to float: '${String(value)}'`)
134 }
135 return changedValue
136 }
137
138 export const convertToBoolean = (value: unknown): boolean => {
139 let result = false
140 if (value != null) {
141 // Check the type
142 if (typeof value === 'boolean') {
143 return value
144 } else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value === '1')) {
145 result = true
146 } else if (typeof value === 'number' && value === 1) {
147 result = true
148 }
149 }
150 return result
151 }
152
153 export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => {
154 if (max < min) {
155 throw new RangeError('Invalid interval')
156 }
157 if (max - min === Number.POSITIVE_INFINITY) {
158 throw new RangeError('Invalid interval')
159 }
160 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min
161 }
162
163 /**
164 * Rounds the given number to the given scale.
165 * The rounding is done using the "round half away from zero" method.
166 *
167 * @param numberValue - The number to round.
168 * @param scale - The scale to round to.
169 * @returns The rounded number.
170 */
171 export const roundTo = (numberValue: number, scale: number): number => {
172 const roundPower = Math.pow(10, scale)
173 return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower
174 }
175
176 export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => {
177 if (min !== 0) {
178 return roundTo(getRandomFloat(max, min), scale)
179 }
180 return roundTo(getRandomFloat(max), scale)
181 }
182
183 export const getRandomFloatFluctuatedRounded = (
184 staticValue: number,
185 fluctuationPercent: number,
186 scale = 2
187 ): number => {
188 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
189 throw new RangeError(
190 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
191 )
192 }
193 if (fluctuationPercent === 0) {
194 return roundTo(staticValue, scale)
195 }
196 const fluctuationRatio = fluctuationPercent / 100
197 return getRandomFloatRounded(
198 staticValue * (1 + fluctuationRatio),
199 staticValue * (1 - fluctuationRatio),
200 scale
201 )
202 }
203
204 export const extractTimeSeriesValues = (timeSeries: CircularBuffer<TimestampedData>): number[] => {
205 return (timeSeries.toArray() as TimestampedData[]).map(timeSeriesItem => timeSeriesItem.value)
206 }
207
208 export const clone = <T>(object: T): T => {
209 return structuredClone<T>(object)
210 }
211
212 /**
213 * Detects whether the given value is an asynchronous function or not.
214 *
215 * @param fn - Unknown value.
216 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
217 * @internal
218 */
219 export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise<unknown> => {
220 return is(Function, fn) && fn.constructor.name === 'AsyncFunction'
221 }
222
223 export const isObject = (value: unknown): value is object => {
224 return value != null && !Array.isArray(value) && is(Object, value)
225 }
226
227 export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => {
228 return isObject(value) && Object.hasOwn(value, property)
229 }
230
231 export const isCFEnvironment = (): boolean => {
232 return env.VCAP_APPLICATION != null
233 }
234
235 export const isNotEmptyString = (value: unknown): value is string => {
236 return typeof value === 'string' && value.trim().length > 0
237 }
238
239 export const isNotEmptyArray = (value: unknown): value is unknown[] => {
240 return Array.isArray(value) && value.length > 0
241 }
242
243 export const insertAt = (str: string, subStr: string, pos: number): string =>
244 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
245
246 /**
247 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
248 *
249 * @param retryNumber - the number of retries that have already been attempted
250 * @param delayFactor - the base delay factor in milliseconds
251 * @returns delay in milliseconds
252 */
253 export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
254 const delay = Math.pow(2, retryNumber) * delayFactor
255 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
256 return delay + randomSum
257 }
258
259 /**
260 * Generates a cryptographically secure random number in the [0,1[ range
261 *
262 * @returns A number in the [0,1[ range
263 */
264 export const secureRandom = (): number => {
265 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
266 }
267
268 export const JSONStringify = <
269 T extends
270 | JsonType
271 | Array<Record<string, unknown>>
272 | Set<Record<string, unknown>>
273 | Map<string, Record<string, unknown>>
274 >(
275 object: T,
276 space?: string | number,
277 mapFormat?: MapStringifyFormat
278 ): string => {
279 return JSON.stringify(
280 object,
281 (_, value: Record<string, unknown>) => {
282 if (is(Map, value)) {
283 switch (mapFormat) {
284 case MapStringifyFormat.object:
285 return {
286 ...Object.fromEntries<Map<string, Record<string, unknown>>>(value.entries())
287 }
288 case MapStringifyFormat.array:
289 default:
290 return [...value]
291 }
292 } else if (is(Set, value)) {
293 return [...value] as JsonType[]
294 }
295 return value
296 },
297 space
298 )
299 }
300
301 /**
302 * Converts websocket error code to human readable string message
303 *
304 * @param code - websocket error code
305 * @returns human readable string message
306 */
307 export const getWebSocketCloseEventStatusString = (code: number): string => {
308 if (code >= 0 && code <= 999) {
309 return '(Unused)'
310 } else if (code >= 1016) {
311 if (code <= 1999) {
312 return '(For WebSocket standard)'
313 } else if (code <= 2999) {
314 return '(For WebSocket extensions)'
315 } else if (code <= 3999) {
316 return '(For libraries and frameworks)'
317 } else if (code <= 4999) {
318 return '(For applications)'
319 }
320 }
321 if (
322 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
323 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null
324 ) {
325 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]
326 }
327 return '(Unknown)'
328 }
329
330 export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => {
331 for (let index = 0; index < array.length - 1; ++index) {
332 if (compareFn(array[index], array[index + 1]) > 0) {
333 return false
334 }
335 }
336 return true
337 }
338
339 export const throwErrorInNextTick = (error: Error): void => {
340 nextTick(() => {
341 throw error
342 })
343 }