X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;ds=sidebyside;f=src%2Futils%2FUtils.ts;h=9d021ecb2d3773cfeb318f5bbf07e53d55f41a90;hb=b8e3363a179fcf79d8bb66f47724b377d4d38a75;hp=4c4c20f234ff02faf4f79974db7913858b0c0dd7;hpb=61877a2e1a2cf976a5e5f7f37828950d8aca9af5;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 4c4c20f2..9d021ecb 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,15 +12,15 @@ import { minutesToSeconds, secondsToMilliseconds } from 'date-fns' +import type { CircularBuffer } from 'mnemonist' +import { is } from 'rambda' import { - type EmptyObject, type JsonType, MapStringifyFormat, type TimestampedData, WebSocketCloseEventStatusString } from '../types/index.js' -import { Constants } from './Constants.js' export const logPrefix = (prefixString = ''): string => { return `${new Date().toLocaleString()}${prefixString}` @@ -92,7 +92,7 @@ export const convertToDate = ( if (isDate(value)) { return value } - if (isString(value) || typeof value === 'number') { + if (typeof value === 'string' || typeof value === 'number') { const valueToDate = new Date(value) if (isNaN(valueToDate.getTime())) { throw new Error(`Cannot convert to date: '${value}'`) @@ -112,8 +112,8 @@ export const convertToInt = (value: unknown): number => { return Math.trunc(value) } let changedValue: number = value as number - if (isString(value)) { - changedValue = parseInt(value) + if (typeof value === 'string') { + changedValue = Number.parseInt(value) } if (isNaN(changedValue)) { throw new Error(`Cannot convert to integer: '${String(value)}'`) @@ -126,8 +126,8 @@ export const convertToFloat = (value: unknown): number => { return 0 } let changedValue: number = value as number - if (isString(value)) { - changedValue = parseFloat(value) + if (typeof value === 'string') { + changedValue = Number.parseFloat(value) } if (isNaN(changedValue)) { throw new Error(`Cannot convert to float: '${String(value)}'`) @@ -141,7 +141,7 @@ export const convertToBoolean = (value: unknown): boolean => { // Check the type if (typeof value === 'boolean') { return value - } else if (isString(value) && (value.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,21 +154,12 @@ export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => { if (max < min) { throw new RangeError('Invalid interval') } - if (max - min === Infinity) { + if (max - min === Number.POSITIVE_INFINITY) { throw new RangeError('Invalid interval') } 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 !== 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. @@ -210,8 +201,8 @@ export const getRandomFloatFluctuatedRounded = ( ) } -export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => { - return timeSeries.map(timeSeriesItem => timeSeriesItem.value) +export const extractTimeSeriesValues = (timeSeries: CircularBuffer): number[] => { + return (timeSeries.toArray() as TimestampedData[]).map(timeSeriesItem => timeSeriesItem.value) } export const clone = (object: T): T => { @@ -226,24 +217,11 @@ export const clone = (object: T): T => { * @internal */ export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise => { - return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction' + return is(Function, fn) && fn.constructor.name === 'AsyncFunction' } export const isObject = (value: unknown): value is object => { - return value != null && typeof value === 'object' && !Array.isArray(value) -} - -export const isEmptyObject = (object: object): object is EmptyObject => { - if (object.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 object) { - return false - } - return true + return value != null && !Array.isArray(value) && is(Object, value) } export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => { @@ -254,20 +232,8 @@ export const isCFEnvironment = (): boolean => { return env.VCAP_APPLICATION != null } -const isString = (value: unknown): value is string => { - return typeof value === 'string' -} - -export const isEmptyString = (value: unknown): value is '' | undefined | null => { - return value == null || (isString(value) && value.trim().length === 0) -} - export const isNotEmptyString = (value: unknown): value is string => { - return isString(value) && value.trim().length > 0 -} - -export const isEmptyArray = (value: unknown): value is [] => { - return Array.isArray(value) && value.length === 0 + return typeof value === 'string' && value.trim().length > 0 } export const isNotEmptyArray = (value: unknown): value is unknown[] => { @@ -313,15 +279,17 @@ export const JSONStringify = < return JSON.stringify( object, (_, value: Record) => { - if (value instanceof Map) { + if (is(Map, value)) { switch (mapFormat) { case MapStringifyFormat.object: - return { ...Object.fromEntries>>(value.entries()) } + return { + ...Object.fromEntries>>(value.entries()) + } case MapStringifyFormat.array: default: return [...value] } - } else if (value instanceof Set) { + } else if (is(Set, value)) { return [...value] as JsonType[] } return value @@ -368,28 +336,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) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - 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