refactor: make storage init compliant with MikroORM 6
[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.valueOf()) 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 export const isObject = (value: unknown): value is object => {
265 return value != null && typeof value === 'object' && !Array.isArray(value)
266 }
267
268 export const isEmptyObject = (object: object): object is EmptyObject => {
269 if (object.constructor !== Object) {
270 return false
271 }
272 // Iterates over the keys of an object, if
273 // any exist, return false.
274 // eslint-disable-next-line no-unreachable-loop
275 for (const _ in object) {
276 return false
277 }
278 return true
279 }
280
281 export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => {
282 return isObject(value) && Object.hasOwn(value, property)
283 }
284
285 export const isCFEnvironment = (): boolean => {
286 return env.VCAP_APPLICATION != null
287 }
288
289 const isString = (value: unknown): value is string => {
290 return typeof value === 'string'
291 }
292
293 export const isEmptyString = (value: unknown): value is '' | undefined | null => {
294 return value == null || (isString(value) && value.trim().length === 0)
295 }
296
297 export const isNotEmptyString = (value: unknown): value is string => {
298 return isString(value) && value.trim().length > 0
299 }
300
301 export const isEmptyArray = (value: unknown): value is never[] => {
302 return Array.isArray(value) && value.length === 0
303 }
304
305 export const isNotEmptyArray = (value: unknown): value is unknown[] => {
306 return Array.isArray(value) && value.length > 0
307 }
308
309 export const insertAt = (str: string, subStr: string, pos: number): string =>
310 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
311
312 /**
313 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
314 *
315 * @param retryNumber - the number of retries that have already been attempted
316 * @param delayFactor - the base delay factor in milliseconds
317 * @returns delay in milliseconds
318 */
319 export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
320 const delay = Math.pow(2, retryNumber) * delayFactor
321 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
322 return delay + randomSum
323 }
324
325 /**
326 * Generates a cryptographically secure random number in the [0,1[ range
327 *
328 * @returns A number in the [0,1[ range
329 */
330 export const secureRandom = (): number => {
331 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
332 }
333
334 export const JSONStringifyWithMapSupport = (
335 object: Record<string, unknown> | Array<Record<string, unknown>> | Map<unknown, unknown>,
336 space?: number
337 ): string => {
338 return JSON.stringify(
339 object,
340 (_, value: Record<string, unknown>) => {
341 if (value instanceof Map) {
342 return {
343 dataType: 'Map',
344 value: [...value]
345 }
346 }
347 return value
348 },
349 space
350 )
351 }
352
353 /**
354 * Converts websocket error code to human readable string message
355 *
356 * @param code - websocket error code
357 * @returns human readable string message
358 */
359 export const getWebSocketCloseEventStatusString = (code: number): string => {
360 if (code >= 0 && code <= 999) {
361 return '(Unused)'
362 } else if (code >= 1016) {
363 if (code <= 1999) {
364 return '(For WebSocket standard)'
365 } else if (code <= 2999) {
366 return '(For WebSocket extensions)'
367 } else if (code <= 3999) {
368 return '(For libraries and frameworks)'
369 } else if (code <= 4999) {
370 return '(For applications)'
371 }
372 }
373 if (
374 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
375 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null
376 ) {
377 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]
378 }
379 return '(Unknown)'
380 }
381
382 export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => {
383 for (let index = 0; index < array.length - 1; ++index) {
384 if (compareFn(array[index], array[index + 1]) > 0) {
385 return false
386 }
387 }
388 return true
389 }
390
391 // eslint-disable-next-line @typescript-eslint/no-explicit-any
392 export const once = <T, A extends any[], R>(
393 fn: (...args: A) => R,
394 context: T
395 ): ((...args: A) => R) => {
396 let result: R
397 return (...args: A) => {
398 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
399 if (fn != null) {
400 result = fn.apply<T, A, R>(context, args)
401 ;(fn as unknown as undefined) = (context as unknown as undefined) = undefined
402 }
403 return result
404 }
405 }
406
407 export const min = (...args: number[]): number =>
408 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
409
410 export const max = (...args: number[]): number =>
411 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
412
413 export const throwErrorInNextTick = (error: Error): void => {
414 nextTick(() => {
415 throw error
416 })
417 }