X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=ui%2Fweb%2Fsrc%2Fcomposables%2FUtils.ts;h=0c8a83996e905c7e046d624ad9a8bd64124d1df1;hb=cffc32b7bc5a6569525e92b562af8a93760bc339;hp=54d926ade4012a93944481ef50ff85aa57e04fc0;hpb=9d76f5ec92a3f5865ef2cefd5a253cab3aa2e5fe;p=e-mobility-charging-stations-simulator.git diff --git a/ui/web/src/composables/Utils.ts b/ui/web/src/composables/Utils.ts index 54d926ad..0c8a8399 100644 --- a/ui/web/src/composables/Utils.ts +++ b/ui/web/src/composables/Utils.ts @@ -1,3 +1,67 @@ -export const compose = (...fns: ((arg: T) => T)[]): ((x: T) => T) => { - return (x: T) => fns.reduceRight((y, fn) => fn(y), x) +import { UIClient } from './UIClient' + +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 +} + +export const convertToInt = (value: unknown): number => { + if (value == null) { + return 0 + } + if (Number.isSafeInteger(value)) { + return value as number + } + 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 getFromLocalStorage = (key: string, defaultValue: T): T => { + const item = localStorage.getItem(key) + return item != null ? (JSON.parse(item) as T) : defaultValue +} + +export const setToLocalStorage = (key: string, value: T): void => { + localStorage.setItem(key, JSON.stringify(value)) +} + +export const deleteFromLocalStorage = (key: string): void => { + localStorage.removeItem(key) +} + +export const getLocalStorage = (): Storage => { + return localStorage +} + +export const randomUUID = (): `${string}-${string}-${string}-${string}-${string}` => { + return crypto.randomUUID() +} + +export const validateUUID = ( + uuid: `${string}-${string}-${string}-${string}-${string}` +): uuid is `${string}-${string}-${string}-${string}-${string}` => { + return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(uuid) +} + +export const useUIClient = (): UIClient => { + return UIClient.getInstance() }