X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=ui%2Fweb%2Fsrc%2Fcomposables%2FUtils.ts;h=fffd7a54966a54a2e092d4eef2a4d5360b45036b;hb=0344ad2b24f8b043b5848a0fea8b5a120d6781db;hp=36ecd4b7e2ae52cb52403b5377d6d3713044d633;hpb=ebbfbf1c01e010d051956867484b74a94237f546;p=e-mobility-charging-stations-simulator.git diff --git a/ui/web/src/composables/Utils.ts b/ui/web/src/composables/Utils.ts index 36ecd4b7..fffd7a54 100644 --- a/ui/web/src/composables/Utils.ts +++ b/ui/web/src/composables/Utils.ts @@ -1,47 +1,43 @@ -export default class Utils { - // STATE - public static isUndefined(value: unknown): boolean { - return typeof value === 'undefined'; +export const convertToBoolean = (value: unknown): boolean => { + let result = false + if (value != null) { + // Check the type + if (typeof value === 'boolean') { + return value + } else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value === '1')) { + result = true + } else if (typeof value === 'number' && value === 1) { + result = true + } } + return result +} - public static ifUndefined(value: T | undefined, isValue: T): T { - if (Utils.isUndefined(value) === true) return isValue; - return value as T; +export const convertToInt = (value: unknown): number => { + if (value == null) { + return 0 } - - public static isIterable(obj: any): boolean { - if (obj === null || obj === undefined) { - return false; - } - return typeof obj[Symbol.iterator] === 'function'; + if (Number.isSafeInteger(value)) { + return value as number } - - // public static ifNotIterableDo(obj: T, cb: () => void): void { - // if (this.isIterable(obj) === false) cb(); - // } - - public static async promiseWithTimeout( - promise: Promise, - timeoutMs: number, - timeoutError: Error, - timeoutCallback: () => void = () => { - /* This is intentional */ - } - ): Promise { - // Create a timeout promise that rejects in timeout milliseconds - const timeoutPromise = new Promise((_, reject) => { - setTimeout(() => { - timeoutCallback(); - reject(timeoutError); - }, timeoutMs); - }); - - // Returns a race between timeout promise and the passed promise - return Promise.race([promise, timeoutPromise]); + if (typeof value === 'number') { + return Math.trunc(value) + } + let changedValue: number = value as number + if (typeof value === 'string') { + changedValue = parseInt(value) + } + if (isNaN(changedValue)) { + throw new Error(`Cannot convert to integer: '${String(value)}'`) } + return changedValue +} + +export const setToLocalStorage = (key: string, value: T): void => { + localStorage.setItem(key, JSON.stringify(value)) +} - // FUNCTIONAL - // public static compose(...fns: ((arg: T) => T)[]): (x: T) => T { - // return (x: T) => fns.reduceRight((y, fn) => fn(y), x); - // } +export const getFromLocalStorage = (key: string, defaultValue: T): T => { + const item = localStorage.getItem(key) + return item != null ? (JSON.parse(item) as T) : defaultValue }