refactor: cleanup isNullOrUndefined usage
[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 isValidTime = (date: unknown): boolean => {
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 | null | undefined
80 ): Date | null | undefined => {
81 if (value == null) {
82 return value
83 }
84 if (isDate(value)) {
85 return value
86 }
87 if (isString(value) || typeof value === 'number') {
88 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
89 const valueToDate = new Date(value)
90 if (isNaN(valueToDate.getTime())) {
91 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
92 throw new Error(`Cannot convert to date: '${value}'`)
93 }
94 return valueToDate
95 }
96 }
97
98 export const convertToInt = (value: unknown): number => {
99 if (value == null) {
100 return 0
101 }
102 let changedValue: number = value as number
103 if (Number.isSafeInteger(value)) {
104 return value as number
105 }
106 if (typeof value === 'number') {
107 return Math.trunc(value)
108 }
109 if (isString(value)) {
110 changedValue = parseInt(value as string)
111 }
112 if (isNaN(changedValue)) {
113 throw new Error(`Cannot convert to integer: '${String(value)}'`)
114 }
115 return changedValue
116 }
117
118 export const convertToFloat = (value: unknown): number => {
119 if (value == null) {
120 return 0
121 }
122 let changedValue: number = value as number
123 if (isString(value)) {
124 changedValue = parseFloat(value as string)
125 }
126 if (isNaN(changedValue)) {
127 throw new Error(`Cannot convert to float: '${String(value)}'`)
128 }
129 return changedValue
130 }
131
132 export const convertToBoolean = (value: unknown): boolean => {
133 let result = false
134 if (value != null) {
135 // Check the type
136 if (typeof value === 'boolean') {
137 return value
138 } else if (isString(value) && ((value as string).toLowerCase() === 'true' || value === '1')) {
139 result = true
140 } else if (typeof value === 'number' && value === 1) {
141 result = true
142 }
143 }
144 return result
145 }
146
147 export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => {
148 if (max < min) {
149 throw new RangeError('Invalid interval')
150 }
151 if (max - min === Infinity) {
152 throw new RangeError('Invalid interval')
153 }
154 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min
155 }
156
157 export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => {
158 max = Math.floor(max)
159 if (min != null && min !== 0) {
160 min = Math.ceil(min)
161 return Math.floor(randomInt(min, max + 1))
162 }
163 return Math.floor(randomInt(max + 1))
164 }
165
166 /**
167 * Rounds the given number to the given scale.
168 * The rounding is done using the "round half away from zero" method.
169 *
170 * @param numberValue - The number to round.
171 * @param scale - The scale to round to.
172 * @returns The rounded number.
173 */
174 export const roundTo = (numberValue: number, scale: number): number => {
175 const roundPower = Math.pow(10, scale)
176 return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower
177 }
178
179 export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => {
180 if (min != null && min !== 0) {
181 return roundTo(getRandomFloat(max, min), scale)
182 }
183 return roundTo(getRandomFloat(max), scale)
184 }
185
186 export const getRandomFloatFluctuatedRounded = (
187 staticValue: number,
188 fluctuationPercent: number,
189 scale = 2
190 ): number => {
191 if (fluctuationPercent < 0 || fluctuationPercent > 100) {
192 throw new RangeError(
193 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
194 )
195 }
196 if (fluctuationPercent === 0) {
197 return roundTo(staticValue, scale)
198 }
199 const fluctuationRatio = fluctuationPercent / 100
200 return getRandomFloatRounded(
201 staticValue * (1 + fluctuationRatio),
202 staticValue * (1 - fluctuationRatio),
203 scale
204 )
205 }
206
207 export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => {
208 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value)
209 }
210
211 export const isObject = (item: unknown): boolean => {
212 return item != null && typeof item === 'object' && !Array.isArray(item)
213 }
214
215 type CloneableData =
216 | number
217 | string
218 | boolean
219 | null
220 | undefined
221 | Date
222 | CloneableData[]
223 | { [key: string]: CloneableData }
224
225 type FormatKey = (key: string) => string
226
227 const deepClone = <I extends CloneableData, O extends CloneableData = I>(
228 value: I,
229 formatKey?: FormatKey,
230 refs: Map<I, O> = new Map<I, O>()
231 ): O => {
232 const ref = refs.get(value)
233 if (ref !== undefined) {
234 return ref
235 }
236 if (Array.isArray(value)) {
237 const clone: CloneableData[] = []
238 refs.set(value, clone as O)
239 for (let i = 0; i < value.length; i++) {
240 clone[i] = deepClone(value[i], formatKey, refs)
241 }
242 return clone as O
243 }
244 if (value instanceof Date) {
245 return new Date(value.valueOf()) as O
246 }
247 if (typeof value !== 'object' || value === null) {
248 return value as unknown as O
249 }
250 const clone: Record<string, CloneableData> = {}
251 refs.set(value, clone as O)
252 for (const key of Object.keys(value)) {
253 clone[typeof formatKey === 'function' ? formatKey(key) : key] = deepClone(
254 value[key],
255 formatKey,
256 refs
257 )
258 }
259 return clone as O
260 }
261
262 export const cloneObject = <T>(object: T): T => {
263 return deepClone(object as CloneableData) as T
264 }
265
266 export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => {
267 return isObject(object) && Object.hasOwn(object as object, property)
268 }
269
270 export const isCFEnvironment = (): boolean => {
271 return env.VCAP_APPLICATION != null
272 }
273
274 export const isIterable = <T>(obj: T): boolean => {
275 return obj != null ? typeof obj[Symbol.iterator as keyof T] === 'function' : false
276 }
277
278 const isString = (value: unknown): boolean => {
279 return typeof value === 'string'
280 }
281
282 export const isEmptyString = (value: unknown): boolean => {
283 return value == null || (isString(value) && (value as string).trim().length === 0)
284 }
285
286 export const isNotEmptyString = (value: unknown): boolean => {
287 return isString(value) && (value as string).trim().length > 0
288 }
289
290 export const isUndefined = (value: unknown): boolean => {
291 return value === undefined
292 }
293
294 export const isNullOrUndefined = (value: unknown): boolean => {
295 return value == null
296 }
297
298 export const isEmptyArray = (object: unknown): boolean => {
299 return Array.isArray(object) && object.length === 0
300 }
301
302 export const isNotEmptyArray = (object: unknown): boolean => {
303 return Array.isArray(object) && object.length > 0
304 }
305
306 export const isEmptyObject = (obj: object): boolean => {
307 if (obj?.constructor !== Object) {
308 return false
309 }
310 // Iterates over the keys of an object, if
311 // any exist, return false.
312 // eslint-disable-next-line no-unreachable-loop
313 for (const _ in obj) {
314 return false
315 }
316 return true
317 }
318
319 export const insertAt = (str: string, subStr: string, pos: number): string =>
320 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
321
322 /**
323 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
324 *
325 * @param retryNumber - the number of retries that have already been attempted
326 * @param delayFactor - the base delay factor in milliseconds
327 * @returns delay in milliseconds
328 */
329 export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => {
330 const delay = Math.pow(2, retryNumber) * delayFactor
331 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
332 return delay + randomSum
333 }
334
335 /**
336 * Generates a cryptographically secure random number in the [0,1[ range
337 *
338 * @returns A number in the [0,1[ range
339 */
340 export const secureRandom = (): number => {
341 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
342 }
343
344 export const JSONStringifyWithMapSupport = (
345 obj: Record<string, unknown> | Array<Record<string, unknown>> | Map<unknown, unknown>,
346 space?: number
347 ): string => {
348 return JSON.stringify(
349 obj,
350 (_, value: Record<string, unknown>) => {
351 if (value instanceof Map) {
352 return {
353 dataType: 'Map',
354 value: [...value]
355 }
356 }
357 return value
358 },
359 space
360 )
361 }
362
363 /**
364 * Converts websocket error code to human readable string message
365 *
366 * @param code - websocket error code
367 * @returns human readable string message
368 */
369 export const getWebSocketCloseEventStatusString = (code: number): string => {
370 if (code >= 0 && code <= 999) {
371 return '(Unused)'
372 } else if (code >= 1016) {
373 if (code <= 1999) {
374 return '(For WebSocket standard)'
375 } else if (code <= 2999) {
376 return '(For WebSocket extensions)'
377 } else if (code <= 3999) {
378 return '(For libraries and frameworks)'
379 } else if (code <= 4999) {
380 return '(For applications)'
381 }
382 }
383 if (
384 !isUndefined(
385 WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]
386 )
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 if (fn != null) {
410 result = fn.apply<T, A, R>(context, args)
411 ;(fn as unknown as undefined) = (context as unknown as undefined) = undefined
412 }
413 return result
414 }
415 }
416
417 export const min = (...args: number[]): number =>
418 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
419
420 export const max = (...args: number[]): number =>
421 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
422
423 export const throwErrorInNextTick = (error: Error): void => {
424 nextTick(() => {
425 throw error
426 })
427 }