refactor: improve types testing types definition
authorJérôme Benoit <jerome.benoit@sap.com>
Sat, 13 Jan 2024 11:53:58 +0000 (12:53 +0100)
committerJérôme Benoit <jerome.benoit@sap.com>
Sat, 13 Jan 2024 11:53:58 +0000 (12:53 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/charging-station/AutomaticTransactionGenerator.ts
src/charging-station/ChargingStation.ts
src/charging-station/Helpers.ts
src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts
src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts
src/charging-station/ocpp/OCPPServiceUtils.ts
src/charging-station/ui-server/ui-services/AbstractUIService.ts
src/utils/Utils.ts
src/utils/index.ts
tests/utils/Utils.test.ts
ui/web/src/composables/Utils.ts

index e12fba9497629207fdd1e368c4ecd50cbfb2687c..6158d7b05435f3a067a2963e859403095c2bfe32 100644 (file)
@@ -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(
index 92fbb80c6e21bde391c74ffccdd52100a38bd26a..78561276c22cc0df9cc0dc4985258a6dbbda648f 100644 (file)
@@ -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)
index f15bb0847116696e88413b55bd16752479ff4b44..50b26885bbf999e21e5e92d243475a0a68c55871 100644 (file)
@@ -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
       } `
     )
   }
index 704be2adbc3f7977258c3d68aaf4bd9eb771ce66..8f1a4593d3a02476b819a25a44c4f8ed0ad83a73 100644 (file)
@@ -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}`
       )
index bd96c4b3fab81d8c4fc10e79b979774a9309d9fd..b8048927ccb824f4ff8e20320cfd356c33af6f0f 100644 (file)
@@ -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
index 6a2e28ac50e80272fd24f225239f61c6d9196a9a..3dd6ff7938a2be849dfc90374efa92e5cef663df 100644 (file)
@@ -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) {
index c0a7c7997974f0027b94189e276ed23f6a93bcf2..44caca5472daca4084a8e5177a47d225ac304901 100644 (file)
@@ -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
           }
index e8c52603fbc238ce2d7f5278844ed662a93ea30c..3827d0dde99c519d6efb9477ff39e60cfb3d18ab 100644 (file)
@@ -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 = <T>(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 = <T>(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
 }
 
index 397ea764603fef677999c0d233312730dae9a7e0..58fc23762b3cc5fd9f709bfcee5db0cdbc116647 100644 (file)
@@ -45,7 +45,7 @@ export {
   isEmptyString,
   isNotEmptyArray,
   isNotEmptyString,
-  isValidTime,
+  isValidDate,
   logPrefix,
   max,
   min,
index f85b8322249f5c1032679c2d64e80f2dfd25d47d..efd0470db275e4ac25deede04fe75d2b70983a69 100644 (file)
@@ -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)
index 7f070e49a8aa7fde7f8e268f6369172494c8e13c..a9eb33b3277cbba434c0d7c671fb76834985b6ff 100644 (file)
@@ -3,17 +3,6 @@ export const ifUndefined = <T>(value: T | undefined, isValue: T): T => {
   return value as T
 }
 
-// const isIterable = <T>(obj: T): boolean => {
-//   if (obj == null) {
-//     return false
-//   }
-//   return typeof (obj as unknown as Iterable<T>)[Symbol.iterator] === 'function'
-// }
-
-// const ifNotIterableDo = <T>(obj: T, cb: () => void): void => {
-//   if (isIterable(obj) === false) cb()
-// }
-
 // export const compose = <T>(...fns: ((arg: T) => T)[]): ((x: T) => T) => {
 //   return (x: T) => fns.reduceRight((y, fn) => fn(y), x)
 // }