X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FUtils.ts;h=abfac5e4873c98af8a4afa225ed1568fa4c9cec8;hb=0b1828224edf798044ef54672ddfc69598cd99a5;hp=b8083596b2618a3b5c2360d15a4fc6542a00c9dd;hpb=68220b423c52da387fdf41967dd8c738da0ff52e;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index b8083596..abfac5e4 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -14,7 +14,12 @@ import { } from 'date-fns' import { Constants } from './Constants.js' -import { type TimestampedData, WebSocketCloseEventStatusString } from '../types/index.js' +import { + type EmptyObject, + type ProtocolResponse, + type TimestampedData, + WebSocketCloseEventStatusString +} from '../types/index.js' export const logPrefix = (prefixString = ''): string => { return `${new Date().toLocaleString()}${prefixString}` @@ -29,7 +34,7 @@ export const validateUUID = (uuid: string): boolean => { } export const sleep = async (milliSeconds: number): Promise => { - return await new Promise((resolve) => + return await new Promise(resolve => setTimeout(resolve as () => void, milliSeconds) ) } @@ -66,7 +71,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,10 +81,10 @@ 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 @@ -97,15 +102,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) } + let changedValue: number = value as number if (isString(value)) { - changedValue = parseInt(value as string) + changedValue = parseInt(value) } if (isNaN(changedValue)) { throw new Error(`Cannot convert to integer: '${String(value)}'`) @@ -119,7 +124,7 @@ export const convertToFloat = (value: unknown): number => { } let changedValue: number = value as number if (isString(value)) { - changedValue = parseFloat(value as string) + changedValue = parseFloat(value) } if (isNaN(changedValue)) { throw new Error(`Cannot convert to float: '${String(value)}'`) @@ -133,7 +138,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 (isString(value) && (value.toLowerCase() === 'true' || value === '1')) { result = true } else if (typeof value === 'number' && value === 1) { result = true @@ -203,107 +208,67 @@ 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 item != null && 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 } +/** + * 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 typeof fn === 'function' && fn.constructor.name === 'AsyncFunction' +} -type FormatKey = (key: string) => string +export const isObject = (value: unknown): value is object => { + return value != null && typeof value === 'object' && !Array.isArray(value) +} -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 +export const isEmptyObject = (object: object): object is EmptyObject => { + if (object.constructor !== Object) { + return false } - 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 - ) + // Iterates over the keys of an object, if + // any exist, return false. + // eslint-disable-next-line no-unreachable-loop + for (const _ in object) { + return false } - return clone as O -} - -export const cloneObject = (object: T): T => { - return deepClone(object as CloneableData) as T + return true } -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 env.VCAP_APPLICATION != null } -export const isIterable = (obj: T): boolean => { - return obj != null ? typeof obj[Symbol.iterator as keyof T] === 'function' : false -} - -const isString = (value: unknown): boolean => { +const isString = (value: unknown): value is string => { return typeof value === 'string' } -export const isEmptyString = (value: unknown): boolean => { - return value == null || (isString(value) && (value as string).trim().length === 0) -} - -export const isNotEmptyString = (value: unknown): boolean => { - return isString(value) && (value as string).trim().length > 0 +export const isEmptyString = (value: unknown): value is '' | undefined | null => { + return value == null || (isString(value) && value.trim().length === 0) } -export const isEmptyArray = (object: unknown): boolean => { - return Array.isArray(object) && object.length === 0 +export const isNotEmptyString = (value: unknown): value is string => { + return isString(value) && value.trim().length > 0 } -export const isNotEmptyArray = (object: unknown): boolean => { - return Array.isArray(object) && object.length > 0 +export const isEmptyArray = (value: unknown): value is never[] => { + return Array.isArray(value) && value.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 => @@ -332,11 +297,15 @@ export const secureRandom = (): number => { } export const JSONStringifyWithMapSupport = ( - obj: Record | Array> | Map, - space?: number + object: + | Record + | Array> + | Map + | ProtocolResponse, + space?: string | number ): string => { return JSON.stringify( - obj, + object, (_, value: Record) => { if (value instanceof Map) { return {