refactor: rename cloneObject() -> clone()
[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 { type TimestampedData, WebSocketCloseEventStatusString } from '../types/index.js'
18
19 export const logPrefix = (prefixString = ''): string => {
20 return `${new Date().toLocaleString()}${prefixString}`
21 }
22
23 export const generateUUID = (): string => {
24 return randomUUID()
25 }
26
27 export const validateUUID = (uuid: string): boolean => {
28 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)
29 }
30
31 export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
32 return await new Promise<NodeJS.Timeout>(resolve =>
33 setTimeout(resolve as () => void, milliSeconds)
34 )
35 }
36
37 export const formatDurationMilliSeconds = (duration: number): string => {
38 duration = convertToInt(duration)
39 if (duration < 0) {
40 throw new RangeError('Duration cannot be negative')
41 }
42 const days = Math.floor(duration / (24 * 3600 * 1000))
43 const hours = Math.floor(millisecondsToHours(duration) - days * 24)
44 const minutes = Math.floor(
45 millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours)
46 )
47 const seconds = Math.floor(
48 millisecondsToSeconds(duration) -
49 days * 24 * 3600 -
50 hoursToSeconds(hours) -
51 minutesToSeconds(minutes)
52 )
53 if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) {
54 return formatDuration({ seconds }, { zero: true })
55 }
56 return formatDuration({
57 days,
58 hours,
59 minutes,
60 seconds
61 })
62 }
63
64 export const formatDurationSeconds = (duration: number): string => {
65 return formatDurationMilliSeconds(secondsToMilliseconds(duration))
66 }
67
68 // More efficient time validation function than the one provided by date-fns
69 export const isValidDate = (date: Date | number | undefined): date is Date | number => {
70 if (typeof date === 'number') {
71 return !isNaN(date)
72 } else if (isDate(date)) {
73 return !isNaN(date.getTime())
74 }
75 return false
76 }
77
78 export const convertToDate = (
79 value: Date | string | number | undefined | null
80 ): Date | undefined | null => {
81 if (value == null) {
82 return value
83 }
84 if (isDate(value)) {
85 return value
86 }
87 if (isString(value) || typeof value === 'number') {
88 const valueToDate = new Date(value)
89 if (isNaN(valueToDate.getTime())) {
90 throw new Error(`Cannot convert to date: '${value}'`)
91 }
92 return valueToDate
93 }
94 }
95
96 export const convertToInt = (value: unknown): number => {
97 if (value == null) {
98 return 0
99 }
100 let changedValue: number = value as number
101 if (Number.isSafeInteger(value)) {
102 return value as number
103 }
104 if (typeof value === 'number') {
105 return Math.trunc(value)
106 }
107 if (isString(value)) {
108 changedValue = parseInt(value)
109 }
110 if (isNaN(changedValue)) {
111 throw new Error(`Cannot convert to integer: '${String(value)}'`)
112 }
113 return changedValue
114 }
115
116 export const convertToFloat = (value: unknown): number => {
117 if (value == null) {
118 return 0
119 }
120 let changedValue: number = value as number
121 if (isString(value)) {
122 changedValue = parseFloat(value)
123 }
124 if (isNaN(changedValue)) {
125 throw new Error(`Cannot convert to float: '${String(value)}'`)
126 }
127 return changedValue
128 }
129
130 export const convertToBoolean = (value: unknown): boolean => {
131 let result = false
132 if (value != null) {
133 // Check the type
134 if (typeof value === 'boolean') {
135 return value
136 } else if (isString(value) && (value.toLowerCase() === 'true' || value === '1')) {
137 result = true
138 } else if (typeof value === 'number' && value === 1) {
139 result = true
140 }
141 }
142 return result
143 }
144
145 export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => {
146 if (max < min) {
147 throw new RangeError('Invalid interval')
148 }
149 if (max - min === Infinity) {
150 throw new RangeError('Invalid interval')
151 }
152 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min
153 }
154
155 export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => {
156 max = Math.floor(max)
157 if (min !== 0) {
158 min = Math.ceil(min)
159 return Math.floor(randomInt(min, max + 1))
160 }
161 return Math.floor(randomInt(max + 1))
162 }
163
164 /**
165 * Rounds the given number to the given scale.
166 * The rounding is done using the "round half away from zero" method.
167 *
168 * @param numberValue - The number to round.
169 * @param scale - The scale to round to.
170 * @returns The rounded number.
171 */
172 export const roundTo = (numberValue: number, scale: number): number => {
173 const roundPower = Math.pow(10, scale)
174 return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower
175 }
176
177 export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => {
178 if (min !== 0) {
179 return roundTo(getRandomFloat(max, min), scale)
180 }
181 return roundTo(getRandomFloat(max), scale)
182 }
183
184 export const getRandomFloatFluctuatedRounded = (
185 staticValue: number,
186 fluctuationPercent: number,
187 scale = 2
188 ): number => {
189 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
190 throw new RangeError(
191 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
192 )
193 }
194 if (fluctuationPercent === 0) {
195 return roundTo(staticValue, scale)
196 }
197 const fluctuationRatio = fluctuationPercent / 100
198 return getRandomFloatRounded(
199 staticValue * (1 + fluctuationRatio),
200 staticValue * (1 - fluctuationRatio),
201 scale
202 )
203 }
204
205 export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => {
206 return timeSeries.map(timeSeriesItem => timeSeriesItem.value)
207 }
208
209 export const isObject = (item: unknown): item is object => {
210 return item != null && typeof item === 'object' && !Array.isArray(item)
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 hasOwnProp = (object: unknown, property: PropertyKey): boolean => {
265 return isObject(object) && Object.hasOwn(object, property)
266 }
267
268 export const isCFEnvironment = (): boolean => {
269 return env.VCAP_APPLICATION != null
270 }
271
272 const isString = (value: unknown): value is string => {
273 return typeof value === 'string'
274 }
275
276 export const isEmptyString = (value: unknown): value is string | undefined | null => {
277 return value == null || (isString(value) && value.trim().length === 0)
278 }
279
280 export const isNotEmptyString = (value: unknown): value is string => {
281 return isString(value) && value.trim().length > 0
282 }
283
284 export const isEmptyArray = (object: unknown): object is unknown[] => {
285 return Array.isArray(object) && object.length === 0
286 }
287
288 export const isNotEmptyArray = (object: unknown): object is unknown[] => {
289 return Array.isArray(object) && object.length > 0
290 }
291
292 export const isEmptyObject = (obj: object): boolean => {
293 if (obj.constructor !== Object) {
294 return false
295 }
296 // Iterates over the keys of an object, if
297 // any exist, return false.
298 // eslint-disable-next-line no-unreachable-loop
299 for (const _ in obj) {
300 return false
301 }
302 return true
303 }
304
305 export const insertAt = (str: string, subStr: string, pos: number): string =>
306 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
307
308 /**
309 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
310 *
311 * @param retryNumber - the number of retries that have already been attempted
312 * @param delayFactor - the base delay factor in milliseconds
313 * @returns delay in milliseconds
314 */
315 export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
316 const delay = Math.pow(2, retryNumber) * delayFactor
317 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
318 return delay + randomSum
319 }
320
321 /**
322 * Generates a cryptographically secure random number in the [0,1[ range
323 *
324 * @returns A number in the [0,1[ range
325 */
326 export const secureRandom = (): number => {
327 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
328 }
329
330 export const JSONStringifyWithMapSupport = (
331 obj: Record<string, unknown> | Array<Record<string, unknown>> | Map<unknown, unknown>,
332 space?: number
333 ): string => {
334 return JSON.stringify(
335 obj,
336 (_, value: Record<string, unknown>) => {
337 if (value instanceof Map) {
338 return {
339 dataType: 'Map',
340 value: [...value]
341 }
342 }
343 return value
344 },
345 space
346 )
347 }
348
349 /**
350 * Converts websocket error code to human readable string message
351 *
352 * @param code - websocket error code
353 * @returns human readable string message
354 */
355 export const getWebSocketCloseEventStatusString = (code: number): string => {
356 if (code >= 0 && code <= 999) {
357 return '(Unused)'
358 } else if (code >= 1016) {
359 if (code <= 1999) {
360 return '(For WebSocket standard)'
361 } else if (code <= 2999) {
362 return '(For WebSocket extensions)'
363 } else if (code <= 3999) {
364 return '(For libraries and frameworks)'
365 } else if (code <= 4999) {
366 return '(For applications)'
367 }
368 }
369 if (
370 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
371 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null
372 ) {
373 return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]
374 }
375 return '(Unknown)'
376 }
377
378 export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => {
379 for (let index = 0; index < array.length - 1; ++index) {
380 if (compareFn(array[index], array[index + 1]) > 0) {
381 return false
382 }
383 }
384 return true
385 }
386
387 // eslint-disable-next-line @typescript-eslint/no-explicit-any
388 export const once = <T, A extends any[], R>(
389 fn: (...args: A) => R,
390 context: T
391 ): ((...args: A) => R) => {
392 let result: R
393 return (...args: A) => {
394 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
395 if (fn != null) {
396 result = fn.apply<T, A, R>(context, args)
397 ;(fn as unknown as undefined) = (context as unknown as undefined) = undefined
398 }
399 return result
400 }
401 }
402
403 export const min = (...args: number[]): number =>
404 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
405
406 export const max = (...args: number[]): number =>
407 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
408
409 export const throwErrorInNextTick = (error: Error): void => {
410 nextTick(() => {
411 throw error
412 })
413 }