From 5dc7c990eff43659bd48589cfc5afe09f9ec6664 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sat, 13 Jan 2024 12:53:58 +0100 Subject: [PATCH] refactor: improve types testing types definition MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- .../AutomaticTransactionGenerator.ts | 4 +- src/charging-station/ChargingStation.ts | 75 +++++++------------ src/charging-station/Helpers.ts | 28 +++---- .../ocpp/1.6/OCPP16IncomingRequestService.ts | 3 +- .../ocpp/1.6/OCPP16ServiceUtils.ts | 2 +- src/charging-station/ocpp/OCPPServiceUtils.ts | 26 +++---- .../ui-services/AbstractUIService.ts | 2 +- src/utils/Utils.ts | 34 ++++----- src/utils/index.ts | 2 +- tests/utils/Utils.test.ts | 40 ++-------- ui/web/src/composables/Utils.ts | 11 --- 11 files changed, 81 insertions(+), 146 deletions(-) diff --git a/src/charging-station/AutomaticTransactionGenerator.ts b/src/charging-station/AutomaticTransactionGenerator.ts index e12fba94..6158d7b0 100644 --- a/src/charging-station/AutomaticTransactionGenerator.ts +++ b/src/charging-station/AutomaticTransactionGenerator.ts @@ -23,7 +23,7 @@ import { convertToDate, formatDurationMilliSeconds, getRandomInteger, - isValidTime, + isValidDate, logPrefix, logger, secureRandom, @@ -264,7 +264,7 @@ export class AutomaticTransactionGenerator { this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.stopAbsoluteDuration === false || // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - !isValidTime(this.connectorsStatus.get(connectorId)!.stopDate) + !isValidDate(this.connectorsStatus.get(connectorId)!.stopDate) ) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.connectorsStatus.get(connectorId)!.stopDate = new Date( diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 92fbb80c..78561276 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -229,10 +229,8 @@ export class ChargingStation extends EventEmitter { `${ this.stationInfo?.supervisionUrlOcppConfiguration === true && isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) && - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)?.value) - ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)!.value + isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value) + ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value : this.configuredSupervisionUrl.href }/${this.stationInfo?.chargingStationId}` ) @@ -504,8 +502,7 @@ export class ChargingStation extends EventEmitter { this.stationInfo?.supervisionUrlOcppConfiguration === true && isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) ) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - setConfigurationKeyValue(this, this.stationInfo.supervisionUrlOcppKey!, url) + setConfigurationKeyValue(this, this.stationInfo.supervisionUrlOcppKey, url) } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.stationInfo!.supervisionUrls = url @@ -834,8 +831,7 @@ export class ChargingStation extends EventEmitter { public startAutomaticTransactionGenerator (connectorIds?: number[]): void { this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this) if (isNotEmptyArray(connectorIds)) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - for (const connectorId of connectorIds!) { + for (const connectorId of connectorIds) { this.automaticTransactionGenerator?.startConnector(connectorId) } } else { @@ -847,8 +843,7 @@ export class ChargingStation extends EventEmitter { public stopAutomaticTransactionGenerator (connectorIds?: number[]): void { if (isNotEmptyArray(connectorIds)) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - for (const connectorId of connectorIds!) { + for (const connectorId of connectorIds) { this.automaticTransactionGenerator?.stopConnector(connectorId) } } else { @@ -1108,17 +1103,16 @@ export class ChargingStation extends EventEmitter { createSerialNumber(stationTemplate, stationInfo) stationInfo.voltageOut = this.getVoltageOut(stationInfo) if (isNotEmptyArray(stationTemplate.power)) { - stationTemplate.power = stationTemplate.power as number[] const powerArrayRandomIndex = Math.floor(secureRandom() * stationTemplate.power.length) stationInfo.maximumPower = stationTemplate.powerUnit === PowerUnits.KILO_WATT ? stationTemplate.power[powerArrayRandomIndex] * 1000 : stationTemplate.power[powerArrayRandomIndex] } else { - stationTemplate.power = stationTemplate.power as number stationInfo.maximumPower = stationTemplate.powerUnit === PowerUnits.KILO_WATT - ? stationTemplate.power * 1000 + ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + stationTemplate.power! * 1000 : stationTemplate.power } stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo) @@ -1126,8 +1120,7 @@ export class ChargingStation extends EventEmitter { stationTemplate.firmwareVersionPattern ?? Constants.SEMVER_PATTERN if ( isNotEmptyString(stationInfo.firmwareVersion) && - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - !new RegExp(stationInfo.firmwareVersionPattern).test(stationInfo.firmwareVersion!) + !new RegExp(stationInfo.firmwareVersionPattern).test(stationInfo.firmwareVersion) ) { logger.warn( `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${ @@ -1226,13 +1219,10 @@ export class ChargingStation extends EventEmitter { ) { const patternGroup = this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ?? - this.stationInfo.firmwareVersion?.split('.').length - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const match = new RegExp(this.stationInfo.firmwareVersionPattern!) - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - .exec(this.stationInfo.firmwareVersion!) - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - ?.slice(1, patternGroup! + 1) + this.stationInfo.firmwareVersion.split('.').length + const match = new RegExp(this.stationInfo.firmwareVersionPattern) + .exec(this.stationInfo.firmwareVersion) + ?.slice(1, patternGroup + 1) if (match != null) { const patchLevelIndex = match.length - 1 match[patchLevelIndex] = ( @@ -1312,37 +1302,31 @@ export class ChargingStation extends EventEmitter { if ( this.stationInfo?.supervisionUrlOcppConfiguration === true && isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) && - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!) == null + getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey) == null ) { addConfigurationKey( this, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - this.stationInfo.supervisionUrlOcppKey!, + this.stationInfo.supervisionUrlOcppKey, this.configuredSupervisionUrl.href, { reboot: true } ) } else if ( this.stationInfo?.supervisionUrlOcppConfiguration === false && isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) && - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!) != null + getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey) != null ) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - deleteConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!, { save: false }) + deleteConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey, { save: false }) } if ( isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) && - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!) == null + getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey) == null ) { addConfigurationKey( this, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - this.stationInfo!.amperageLimitationOcppKey!, + this.stationInfo.amperageLimitationOcppKey, // prettier-ignore // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - (this.stationInfo!.maximumAmperage! * getAmperageLimitationUnitDivider(this.stationInfo)).toString() + (this.stationInfo.maximumAmperage! * getAmperageLimitationUnitDivider(this.stationInfo)).toString() ) } if (getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles) == null) { @@ -2122,15 +2106,11 @@ export class ChargingStation extends EventEmitter { private getAmperageLimitation (): number | undefined { if ( isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) && - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - getConfigurationKey(this, this.stationInfo!.amperageLimitationOcppKey!) != null + getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey) != null ) { return ( - convertToInt( - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - getConfigurationKey(this, this.stationInfo!.amperageLimitationOcppKey!)!.value - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - ) / getAmperageLimitationUnitDivider(this.stationInfo!) + convertToInt(getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey)?.value) / + getAmperageLimitationUnitDivider(this.stationInfo) ) } } @@ -2285,9 +2265,7 @@ export class ChargingStation extends EventEmitter { let configuredSupervisionUrlIndex: number switch (Configuration.getSupervisionUrlDistribution()) { case SupervisionUrlDistribution.RANDOM: - configuredSupervisionUrlIndex = Math.floor( - secureRandom() * (supervisionUrls as string[]).length - ) + configuredSupervisionUrlIndex = Math.floor(secureRandom() * supervisionUrls.length) break case SupervisionUrlDistribution.ROUND_ROBIN: case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY: @@ -2302,12 +2280,13 @@ export class ChargingStation extends EventEmitter { SupervisionUrlDistribution.CHARGING_STATION_AFFINITY }` ) - configuredSupervisionUrlIndex = (this.index - 1) % (supervisionUrls as string[]).length + configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length break } - configuredSupervisionUrl = (supervisionUrls as string[])[configuredSupervisionUrlIndex] + configuredSupervisionUrl = supervisionUrls[configuredSupervisionUrlIndex] } else { - configuredSupervisionUrl = supervisionUrls as string + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + configuredSupervisionUrl = supervisionUrls! } if (isNotEmptyString(configuredSupervisionUrl)) { return new URL(configuredSupervisionUrl) diff --git a/src/charging-station/Helpers.ts b/src/charging-station/Helpers.ts index f15bb084..50b26885 100644 --- a/src/charging-station/Helpers.ts +++ b/src/charging-station/Helpers.ts @@ -65,7 +65,7 @@ import { isEmptyString, isNotEmptyArray, isNotEmptyString, - isValidTime, + isValidDate, logger, secureRandom } from '../utils/index.js' @@ -373,7 +373,7 @@ export const resetConnectorStatus = (connectorStatus: ConnectorStatus | undefine } connectorStatus.chargingProfiles = connectorStatus.transactionId != null && isNotEmptyArray(connectorStatus.chargingProfiles) - ? connectorStatus.chargingProfiles?.filter( + ? connectorStatus.chargingProfiles.filter( chargingProfile => chargingProfile.transactionId !== connectorStatus.transactionId ) : [] @@ -680,11 +680,11 @@ export const waitChargingStationEvents = async ( const getConfiguredMaxNumberOfConnectors = (stationTemplate: ChargingStationTemplate): number => { let configuredMaxNumberOfConnectors = 0 if (isNotEmptyArray(stationTemplate.numberOfConnectors)) { - const numberOfConnectors = stationTemplate.numberOfConnectors as number[] + const numberOfConnectors = stationTemplate.numberOfConnectors configuredMaxNumberOfConnectors = numberOfConnectors[Math.floor(secureRandom() * numberOfConnectors.length)] } else if (stationTemplate.numberOfConnectors != null) { - configuredMaxNumberOfConnectors = stationTemplate.numberOfConnectors as number + configuredMaxNumberOfConnectors = stationTemplate.numberOfConnectors } else if (stationTemplate.Connectors != null && stationTemplate.Evses == null) { configuredMaxNumberOfConnectors = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition @@ -951,16 +951,14 @@ export const canProceedChargingProfile = ( logPrefix: string ): boolean => { if ( - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - (isValidTime(chargingProfile.validFrom) && isBefore(currentDate, chargingProfile.validFrom!)) || - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - (isValidTime(chargingProfile.validTo) && isAfter(currentDate, chargingProfile.validTo!)) + (isValidDate(chargingProfile.validFrom) && isBefore(currentDate, chargingProfile.validFrom)) || + (isValidDate(chargingProfile.validTo) && isAfter(currentDate, chargingProfile.validTo)) ) { logger.debug( `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${ chargingProfile.chargingProfileId } is not valid for the current date ${ - currentDate instanceof Date ? currentDate.toISOString() : currentDate + isDate(currentDate) ? currentDate.toISOString() : currentDate }` ) return false @@ -974,7 +972,7 @@ export const canProceedChargingProfile = ( ) return false } - if (!isValidTime(chargingProfile.chargingSchedule.startSchedule)) { + if (!isValidDate(chargingProfile.chargingSchedule.startSchedule)) { logger.error( `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has an invalid startSchedule date defined` ) @@ -1028,7 +1026,7 @@ const prepareRecurringChargingProfile = ( ): boolean => { const chargingSchedule = chargingProfile.chargingSchedule let recurringIntervalTranslated = false - let recurringInterval: Interval + let recurringInterval: Interval | undefined switch (chargingProfile.recurrencyKind) { case RecurrencyKindType.DAILY: recurringInterval = { @@ -1087,13 +1085,11 @@ const prepareRecurringChargingProfile = ( `${logPrefix} ${moduleName}.prepareRecurringChargingProfile: Recurring ${ chargingProfile.recurrencyKind } charging profile id ${chargingProfile.chargingProfileId} recurrency time interval [${toDate( - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - recurringInterval!.start + recurringInterval?.start as Date ).toISOString()}, ${toDate( - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - recurringInterval!.end + recurringInterval?.end as Date ).toISOString()}] has not been properly translated to current date ${ - currentDate instanceof Date ? currentDate.toISOString() : currentDate + isDate(currentDate) ? currentDate.toISOString() : currentDate } ` ) } diff --git a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts index 704be2ad..8f1a4593 100644 --- a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts @@ -804,8 +804,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const connectorStatus = chargingStation.getConnectorStatus(connectorId!) if (connectorId != null && isNotEmptyArray(connectorStatus?.chargingProfiles)) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - connectorStatus!.chargingProfiles = [] + connectorStatus.chargingProfiles = [] logger.debug( `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}` ) diff --git a/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts b/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts index bd96c4b3..b8048927 100644 --- a/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts +++ b/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts @@ -198,7 +198,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { const { id, chargingProfilePurpose, stackLevel } = commandPayload let clearedCP = false if (isNotEmptyArray(chargingProfiles)) { - chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => { + chargingProfiles.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => { let clearCurrentCP = false if (chargingProfile.chargingProfileId === id) { clearCurrentCP = true diff --git a/src/charging-station/ocpp/OCPPServiceUtils.ts b/src/charging-station/ocpp/OCPPServiceUtils.ts index 6a2e28ac..3dd6ff79 100644 --- a/src/charging-station/ocpp/OCPPServiceUtils.ts +++ b/src/charging-station/ocpp/OCPPServiceUtils.ts @@ -491,7 +491,7 @@ export const buildMeterValue = ( ) ? getRandomFloatFluctuatedRounded( getLimitFromSampledValueTemplateCustomValue( - powerPerPhaseSampledValueTemplates.L1?.value, + powerPerPhaseSampledValueTemplates.L1.value, connectorMaximumPowerPerPhase / unitDivider, connectorMinimumPowerPerPhase / unitDivider, { @@ -500,7 +500,7 @@ export const buildMeterValue = ( fallbackValue: connectorMinimumPowerPerPhase / unitDivider } ), - powerPerPhaseSampledValueTemplates.L1?.fluctuationPercent ?? + powerPerPhaseSampledValueTemplates.L1.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT ) : undefined @@ -509,7 +509,7 @@ export const buildMeterValue = ( ) ? getRandomFloatFluctuatedRounded( getLimitFromSampledValueTemplateCustomValue( - powerPerPhaseSampledValueTemplates.L2?.value, + powerPerPhaseSampledValueTemplates.L2.value, connectorMaximumPowerPerPhase / unitDivider, connectorMinimumPowerPerPhase / unitDivider, { @@ -518,7 +518,7 @@ export const buildMeterValue = ( fallbackValue: connectorMinimumPowerPerPhase / unitDivider } ), - powerPerPhaseSampledValueTemplates.L2?.fluctuationPercent ?? + powerPerPhaseSampledValueTemplates.L2.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT ) : undefined @@ -527,7 +527,7 @@ export const buildMeterValue = ( ) ? getRandomFloatFluctuatedRounded( getLimitFromSampledValueTemplateCustomValue( - powerPerPhaseSampledValueTemplates.L3?.value, + powerPerPhaseSampledValueTemplates.L3.value, connectorMaximumPowerPerPhase / unitDivider, connectorMinimumPowerPerPhase / unitDivider, { @@ -536,7 +536,7 @@ export const buildMeterValue = ( fallbackValue: connectorMinimumPowerPerPhase / unitDivider } ), - powerPerPhaseSampledValueTemplates.L3?.fluctuationPercent ?? + powerPerPhaseSampledValueTemplates.L3.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT ) : undefined @@ -757,7 +757,7 @@ export const buildMeterValue = ( ) ? getRandomFloatFluctuatedRounded( getLimitFromSampledValueTemplateCustomValue( - currentPerPhaseSampledValueTemplates.L1?.value, + currentPerPhaseSampledValueTemplates.L1.value, connectorMaximumAmperage, connectorMinimumAmperage, { @@ -766,7 +766,7 @@ export const buildMeterValue = ( fallbackValue: connectorMinimumAmperage } ), - currentPerPhaseSampledValueTemplates.L1?.fluctuationPercent ?? + currentPerPhaseSampledValueTemplates.L1.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT ) : undefined @@ -775,7 +775,7 @@ export const buildMeterValue = ( ) ? getRandomFloatFluctuatedRounded( getLimitFromSampledValueTemplateCustomValue( - currentPerPhaseSampledValueTemplates.L2?.value, + currentPerPhaseSampledValueTemplates.L2.value, connectorMaximumAmperage, connectorMinimumAmperage, { @@ -784,7 +784,7 @@ export const buildMeterValue = ( fallbackValue: connectorMinimumAmperage } ), - currentPerPhaseSampledValueTemplates.L2?.fluctuationPercent ?? + currentPerPhaseSampledValueTemplates.L2.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT ) : undefined @@ -793,7 +793,7 @@ export const buildMeterValue = ( ) ? getRandomFloatFluctuatedRounded( getLimitFromSampledValueTemplateCustomValue( - currentPerPhaseSampledValueTemplates.L3?.value, + currentPerPhaseSampledValueTemplates.L3.value, connectorMaximumAmperage, connectorMinimumAmperage, { @@ -802,7 +802,7 @@ export const buildMeterValue = ( fallbackValue: connectorMinimumAmperage } ), - currentPerPhaseSampledValueTemplates.L3?.fluctuationPercent ?? + currentPerPhaseSampledValueTemplates.L3.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT ) : undefined @@ -1239,7 +1239,7 @@ export class OCPPServiceUtils { // This is intentional } - public static ajvErrorsToErrorType (errors: ErrorObject[] | null | undefined): ErrorType { + public static ajvErrorsToErrorType (errors: ErrorObject[] | undefined | null): ErrorType { if (isNotEmptyArray(errors)) { for (const error of errors as DefinedError[]) { switch (error.keyword) { diff --git a/src/charging-station/ui-server/ui-services/AbstractUIService.ts b/src/charging-station/ui-server/ui-services/AbstractUIService.ts index c0a7c799..44caca54 100644 --- a/src/charging-station/ui-server/ui-services/AbstractUIService.ts +++ b/src/charging-station/ui-server/ui-services/AbstractUIService.ts @@ -163,7 +163,7 @@ export abstract class AbstractUIService { ): void { if (isNotEmptyArray(payload.hashIds)) { payload.hashIds = payload.hashIds - ?.map(hashId => { + .map(hashId => { if (this.uiServer.chargingStations.has(hashId)) { return hashId } diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index e8c52603..3827d0dd 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -66,7 +66,7 @@ export const formatDurationSeconds = (duration: number): string => { } // More efficient time validation function than the one provided by date-fns -export const isValidTime = (date: Date | number | undefined): boolean => { +export const isValidDate = (date: Date | number | undefined): date is Date | number => { if (typeof date === 'number') { return !isNaN(date) } else if (isDate(date)) { @@ -76,8 +76,8 @@ export const isValidTime = (date: Date | number | undefined): boolean => { } export const convertToDate = ( - value: Date | string | number | null | undefined -): Date | null | undefined => { + value: Date | string | number | undefined | null +): Date | undefined | null => { if (value == null) { return value } @@ -105,7 +105,7 @@ export const convertToInt = (value: unknown): number => { return Math.trunc(value) } 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 +119,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 +133,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 @@ -206,7 +206,7 @@ export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] return timeSeries.map(timeSeriesItem => timeSeriesItem.value) } -export const isObject = (item: unknown): boolean => { +export const isObject = (item: unknown): item is object => { return item != null && typeof item === 'object' && !Array.isArray(item) } @@ -262,34 +262,30 @@ export const cloneObject = (object: T): T => { } export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => { - return isObject(object) && Object.hasOwn(object as object, property) + return isObject(object) && Object.hasOwn(object, 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 isEmptyString = (value: unknown): value is string | undefined | null => { + return value == null || (isString(value) && value.trim().length === 0) } -export const isNotEmptyString = (value: unknown): boolean => { - return isString(value) && (value as string).trim().length > 0 +export const isNotEmptyString = (value: unknown): value is string => { + return isString(value) && value.trim().length > 0 } -export const isEmptyArray = (object: unknown): boolean => { +export const isEmptyArray = (object: unknown): object is unknown[] => { return Array.isArray(object) && object.length === 0 } -export const isNotEmptyArray = (object: unknown): boolean => { +export const isNotEmptyArray = (object: unknown): object is unknown[] => { return Array.isArray(object) && object.length > 0 } diff --git a/src/utils/index.ts b/src/utils/index.ts index 397ea764..58fc2376 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -45,7 +45,7 @@ export { isEmptyString, isNotEmptyArray, isNotEmptyString, - isValidTime, + isValidDate, logPrefix, max, min, diff --git a/tests/utils/Utils.test.ts b/tests/utils/Utils.test.ts index f85b8322..efd0470d 100644 --- a/tests/utils/Utils.test.ts +++ b/tests/utils/Utils.test.ts @@ -21,11 +21,10 @@ import { isEmptyArray, isEmptyObject, isEmptyString, - isIterable, isNotEmptyArray, isNotEmptyString, isObject, - isValidTime, + isValidDate, max, min, once, @@ -70,21 +69,13 @@ await describe('Utils test suite', async () => { }) await it('Verify isValidTime()', () => { - expect(isValidTime(undefined)).toBe(false) - expect(isValidTime(null)).toBe(false) - expect(isValidTime('')).toBe(false) - expect(isValidTime({})).toBe(false) - expect(isValidTime([])).toBe(false) - expect(isValidTime(new Map())).toBe(false) - expect(isValidTime(new Set())).toBe(false) - expect(isValidTime(new WeakMap())).toBe(false) - expect(isValidTime(new WeakSet())).toBe(false) - expect(isValidTime(-1)).toBe(true) - expect(isValidTime(0)).toBe(true) - expect(isValidTime(1)).toBe(true) - expect(isValidTime(-0.5)).toBe(true) - expect(isValidTime(0.5)).toBe(true) - expect(isValidTime(new Date())).toBe(true) + expect(isValidDate(undefined)).toBe(false) + expect(isValidDate(-1)).toBe(true) + expect(isValidDate(0)).toBe(true) + expect(isValidDate(1)).toBe(true) + expect(isValidDate(-0.5)).toBe(true) + expect(isValidDate(0.5)).toBe(true) + expect(isValidDate(new Date())).toBe(true) }) await it('Verify convertToDate()', () => { @@ -302,21 +293,6 @@ await describe('Utils test suite', async () => { expect(hasOwnProp({ 1: '1' }, 2)).toBe(false) }) - await it('Verify isIterable()', () => { - expect(isIterable('')).toBe(true) - expect(isIterable(' ')).toBe(true) - expect(isIterable('test')).toBe(true) - expect(isIterable(undefined)).toBe(false) - expect(isIterable(null)).toBe(false) - expect(isIterable(0)).toBe(false) - expect(isIterable([0, 1])).toBe(true) - expect(isIterable({ 1: 1 })).toBe(false) - expect(isIterable(new Map())).toBe(true) - expect(isIterable(new Set())).toBe(true) - expect(isIterable(new WeakMap())).toBe(false) - expect(isIterable(new WeakSet())).toBe(false) - }) - await it('Verify isEmptyString()', () => { expect(isEmptyString('')).toBe(true) expect(isEmptyString(' ')).toBe(true) diff --git a/ui/web/src/composables/Utils.ts b/ui/web/src/composables/Utils.ts index 7f070e49..a9eb33b3 100644 --- a/ui/web/src/composables/Utils.ts +++ b/ui/web/src/composables/Utils.ts @@ -3,17 +3,6 @@ export const ifUndefined = (value: T | undefined, isValue: T): T => { return value as T } -// const isIterable = (obj: T): boolean => { -// if (obj == null) { -// return false -// } -// return typeof (obj as unknown as Iterable)[Symbol.iterator] === 'function' -// } - -// const ifNotIterableDo = (obj: T, cb: () => void): void => { -// if (isIterable(obj) === false) cb() -// } - // export const compose = (...fns: ((arg: T) => T)[]): ((x: T) => T) => { // return (x: T) => fns.reduceRight((y, fn) => fn(y), x) // } -- 2.34.1