X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FUtils.ts;h=aeed9b0fa44b4a073bff682583c95695cbb954ac;hb=452a4864d4a8d0286ddd351958d8cc02574b4ba9;hp=291787d9013f91d10162eb60f01cd8dc3039896c;hpb=66a7748ddeda8c94d7562a1ce58d440319654a4c;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 291787d9..aeed9b0f 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -1,4 +1,4 @@ -import { getRandomValues, randomBytes, randomInt, randomUUID } from 'node:crypto' +import { getRandomValues, randomBytes, randomUUID } from 'node:crypto' import { env, nextTick } from 'node:process' import { @@ -12,24 +12,31 @@ import { minutesToSeconds, secondsToMilliseconds } from 'date-fns' +import { is } from 'rambda' -import { Constants } from './Constants.js' -import { type TimestampedData, WebSocketCloseEventStatusString } from '../types/index.js' +import { + type JsonType, + MapStringifyFormat, + type TimestampedData, + WebSocketCloseEventStatusString +} from '../types/index.js' export const logPrefix = (prefixString = ''): string => { return `${new Date().toLocaleString()}${prefixString}` } -export const generateUUID = (): string => { +export const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => { return randomUUID() } -export const validateUUID = (uuid: string): boolean => { +export const validateUUID = ( + uuid: `${string}-${string}-${string}-${string}-${string}` +): uuid is `${string}-${string}-${string}-${string}-${string}` => { 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) } export const sleep = async (milliSeconds: number): Promise => { - return await new Promise((resolve) => + return await new Promise(resolve => setTimeout(resolve as () => void, milliSeconds) ) } @@ -66,7 +73,7 @@ export const formatDurationSeconds = (duration: number): string => { } // More efficient time validation function than the one provided by date-fns -export const isValidTime = (date: unknown): boolean => { +export const isValidDate = (date: Date | number | undefined): date is Date | number => { if (typeof date === 'number') { return !isNaN(date) } else if (isDate(date)) { @@ -76,19 +83,17 @@ export const isValidTime = (date: unknown): boolean => { } export const convertToDate = ( - value: Date | string | number | null | undefined -): Date | null | undefined => { + value: Date | string | number | undefined | null +): Date | undefined => { if (value == null) { - return value + return undefined } if (isDate(value)) { return value } - if (isString(value) || typeof value === 'number') { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + if (typeof value === 'string' || typeof value === 'number') { const valueToDate = new Date(value) if (isNaN(valueToDate.getTime())) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion throw new Error(`Cannot convert to date: '${value}'`) } return valueToDate @@ -99,15 +104,15 @@ export const convertToInt = (value: unknown): number => { if (value == null) { return 0 } - let changedValue: number = value as number if (Number.isSafeInteger(value)) { return value as number } if (typeof value === 'number') { return Math.trunc(value) } - if (isString(value)) { - changedValue = parseInt(value as string) + let changedValue: number = value as number + if (typeof value === 'string') { + changedValue = parseInt(value) } if (isNaN(changedValue)) { throw new Error(`Cannot convert to integer: '${String(value)}'`) @@ -120,8 +125,8 @@ export const convertToFloat = (value: unknown): number => { return 0 } let changedValue: number = value as number - if (isString(value)) { - changedValue = parseFloat(value as string) + if (typeof value === 'string') { + changedValue = parseFloat(value) } if (isNaN(changedValue)) { throw new Error(`Cannot convert to float: '${String(value)}'`) @@ -135,7 +140,7 @@ export const convertToBoolean = (value: unknown): boolean => { // Check the type if (typeof value === 'boolean') { return value - } else if (isString(value) && ((value as string).toLowerCase() === 'true' || value === '1')) { + } else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value === '1')) { result = true } else if (typeof value === 'number' && value === 1) { result = true @@ -154,15 +159,6 @@ export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => { return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min } -export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => { - max = Math.floor(max) - if (min != null && min !== 0) { - min = Math.ceil(min) - return Math.floor(randomInt(min, max + 1)) - } - return Math.floor(randomInt(max + 1)) -} - /** * Rounds the given number to the given scale. * The rounding is done using the "round half away from zero" method. @@ -177,7 +173,7 @@ export const roundTo = (numberValue: number, scale: number): number => { } export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => { - if (min != null && min !== 0) { + if (min !== 0) { return roundTo(getRandomFloat(max, min), scale) } return roundTo(getRandomFloat(max), scale) @@ -205,115 +201,42 @@ export const getRandomFloatFluctuatedRounded = ( } export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => { - return timeSeries.map((timeSeriesItem) => timeSeriesItem.value) + return timeSeries.map(timeSeriesItem => timeSeriesItem.value) } -export const isObject = (item: unknown): boolean => { - return !isNullOrUndefined(item) && typeof item === 'object' && !Array.isArray(item) +export const clone = (object: T): T => { + return structuredClone(object) } -type CloneableData = - | number - | string - | boolean - | null - | undefined - | Date - | CloneableData[] - | { [key: string]: CloneableData } - -type FormatKey = (key: string) => string - -const deepClone = ( - value: I, - formatKey?: FormatKey, - refs: Map = new Map() -): O => { - const ref = refs.get(value) - if (ref !== undefined) { - return ref - } - if (Array.isArray(value)) { - const clone: CloneableData[] = [] - refs.set(value, clone as O) - for (let i = 0; i < value.length; i++) { - clone[i] = deepClone(value[i], formatKey, refs) - } - return clone as O - } - if (value instanceof Date) { - return new Date(value.valueOf()) as O - } - if (typeof value !== 'object' || value === null) { - return value as unknown as O - } - const clone: Record = {} - refs.set(value, clone as O) - for (const key of Object.keys(value)) { - clone[typeof formatKey === 'function' ? formatKey(key) : key] = deepClone( - value[key], - formatKey, - refs - ) - } - return clone as O +/** + * Detects whether the given value is an asynchronous function or not. + * + * @param fn - Unknown value. + * @returns `true` if `fn` was an asynchronous function, otherwise `false`. + * @internal + */ +export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise => { + return is(Function, fn) && fn.constructor.name === 'AsyncFunction' } -export const cloneObject = (object: T): T => { - return deepClone(object as CloneableData) as T +export const isObject = (value: unknown): value is object => { + return value != null && !Array.isArray(value) && is(Object, value) } -export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => { - return isObject(object) && Object.hasOwn(object as object, property) +export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => { + return isObject(value) && Object.hasOwn(value, property) } export const isCFEnvironment = (): boolean => { - return !isNullOrUndefined(env.VCAP_APPLICATION) -} - -export const isIterable = (obj: T): boolean => { - return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false -} - -const isString = (value: unknown): boolean => { - return typeof value === 'string' + return env.VCAP_APPLICATION != null } -export const isEmptyString = (value: unknown): boolean => { - return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0) +export const isNotEmptyString = (value: unknown): value is string => { + return typeof value === 'string' && value.trim().length > 0 } -export const isNotEmptyString = (value: unknown): boolean => { - return isString(value) && (value as string).trim().length > 0 -} - -export const isUndefined = (value: unknown): boolean => { - return value === undefined -} - -export const isNullOrUndefined = (value: unknown): boolean => { - return value == null -} - -export const isEmptyArray = (object: unknown): boolean => { - return Array.isArray(object) && object.length === 0 -} - -export const isNotEmptyArray = (object: unknown): boolean => { - return Array.isArray(object) && object.length > 0 -} - -export const isEmptyObject = (obj: object): boolean => { - if (obj?.constructor !== Object) { - return false - } - // Iterates over the keys of an object, if - // any exist, return false. - // eslint-disable-next-line no-unreachable-loop - for (const _ in obj) { - return false - } - return true +export const isNotEmptyArray = (value: unknown): value is unknown[] => { + return Array.isArray(value) && value.length > 0 } export const insertAt = (str: string, subStr: string, pos: number): string => @@ -341,18 +264,30 @@ export const secureRandom = (): number => { return getRandomValues(new Uint32Array(1))[0] / 0x100000000 } -export const JSONStringifyWithMapSupport = ( - obj: Record | Array> | Map, - space?: number -): string => { +export const JSONStringify = < + T extends + | JsonType + | Array> + | Set> + | Map> +>( + object: T, + space?: string | number, + mapFormat?: MapStringifyFormat + ): string => { return JSON.stringify( - obj, + object, (_, value: Record) => { - if (value instanceof Map) { - return { - dataType: 'Map', - value: [...value] + if (is(Map, value)) { + switch (mapFormat) { + case MapStringifyFormat.object: + return { ...Object.fromEntries>>(value.entries()) } + case MapStringifyFormat.array: + default: + return [...value] } + } else if (is(Set, value)) { + return [...value] as JsonType[] } return value }, @@ -381,9 +316,8 @@ export const getWebSocketCloseEventStatusString = (code: number): string => { } } if ( - !isUndefined( - WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] - ) + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null ) { return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] } @@ -399,27 +333,6 @@ export const isArraySorted = (array: T[], compareFn: (a: T, b: T) => number): return true } -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export const once = ( - fn: (...args: A) => R, - context: T -): ((...args: A) => R) => { - let result: R - return (...args: A) => { - if (fn != null) { - result = fn.apply(context, args) - ;(fn as unknown as undefined) = (context as unknown as undefined) = undefined - } - return result - } -} - -export const min = (...args: number[]): number => - args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity) - -export const max = (...args: number[]): number => - args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity) - export const throwErrorInNextTick = (error: Error): void => { nextTick(() => { throw error