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