Add initial classes structure for the OCPP 2.0 stack
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
index f174407500db95556d6d1c04fb0b4c95355923b7..94fa3d186e432712238ceee87e7f3491244cb5b7 100644 (file)
@@ -52,7 +52,9 @@ export default class Utils {
     return Utils.formatDurationMilliSeconds(duration * 1000);
   }
 
-  public static convertToDate(value: unknown): Date | null | undefined {
+  public static convertToDate(
+    value: Date | string | number | null | undefined
+  ): Date | null | undefined {
     if (Utils.isNullOrUndefined(value)) {
       return value as null | undefined;
     }
@@ -60,7 +62,7 @@ export default class Utils {
       return value;
     }
     if (Utils.isString(value) || typeof value === 'number') {
-      return new Date(value as string | number);
+      return new Date(value);
     }
     return null;
   }
@@ -74,11 +76,14 @@ export default class Utils {
       return value as number;
     }
     if (typeof value === 'number') {
-      changedValue = Math.trunc(value);
+      return Math.trunc(value);
     }
     if (Utils.isString(value)) {
       changedValue = parseInt(value as string);
     }
+    if (isNaN(changedValue)) {
+      throw new Error(`Cannot convert to integer: ${value.toString()}`);
+    }
     return changedValue;
   }
 
@@ -90,6 +95,9 @@ export default class Utils {
     if (Utils.isString(value)) {
       changedValue = parseFloat(value as string);
     }
+    if (isNaN(changedValue)) {
+      throw new Error(`Cannot convert to float: ${value.toString()}`);
+    }
     return changedValue;
   }
 
@@ -98,7 +106,7 @@ export default class Utils {
     if (value) {
       // Check the type
       if (typeof value === 'boolean') {
-        result = value;
+        return value;
       } else if (
         Utils.isString(value) &&
         ((value as string).toLowerCase() === 'true' || value === '1')
@@ -220,7 +228,7 @@ export default class Utils {
     `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
 
   /**
-   * @param [retryNumber=0]
+   * @param retryNumber - the number of retries that have already been attempted
    * @returns delay in milliseconds
    */
   public static exponentialDelay(retryNumber = 0): number {
@@ -259,7 +267,7 @@ export default class Utils {
   }
 
   public static JSONStringifyWithMapSupport(
-    obj: Record<string, unknown> | Record<string, unknown>[],
+    obj: Record<string, unknown> | Record<string, unknown>[] | Map<string, unknown>,
     space?: number
   ): string {
     return JSON.stringify(
@@ -280,7 +288,7 @@ export default class Utils {
   /**
    * Convert websocket error code to human readable string message
    *
-   * @param code websocket error code
+   * @param code websocket error code
    * @returns human readable string message
    */
   public static getWebSocketCloseEventStatusString(code: number): string {