refactor(ui): cleanup UI client instance getter
[e-mobility-charging-stations-simulator.git] / ui / web / src / composables / Utils.ts
CommitLineData
39cd8fcb
JB
1import { UIClient } from './UIClient'
2
4940561f
JB
3export const convertToBoolean = (value: unknown): boolean => {
4 let result = false
5 if (value != null) {
6 // Check the type
7 if (typeof value === 'boolean') {
8 return value
9 } else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value === '1')) {
10 result = true
11 } else if (typeof value === 'number' && value === 1) {
12 result = true
13 }
14 }
15 return result
16}
17
18export const convertToInt = (value: unknown): number => {
19 if (value == null) {
20 return 0
21 }
4940561f
JB
22 if (Number.isSafeInteger(value)) {
23 return value as number
24 }
25 if (typeof value === 'number') {
26 return Math.trunc(value)
27 }
f5ee1403 28 let changedValue: number = value as number
4940561f
JB
29 if (typeof value === 'string') {
30 changedValue = parseInt(value)
31 }
32 if (isNaN(changedValue)) {
33 throw new Error(`Cannot convert to integer: '${String(value)}'`)
34 }
35 return changedValue
36}
0344ad2b
JB
37
38export const setToLocalStorage = <T>(key: string, value: T): void => {
39 localStorage.setItem(key, JSON.stringify(value))
40}
41
42export const getFromLocalStorage = <T>(key: string, defaultValue: T): T => {
43 const item = localStorage.getItem(key)
44 return item != null ? (JSON.parse(item) as T) : defaultValue
45}
2610da71 46
b767fda7 47export const deleteFromLocalStorage = (key: string): void => {
2610da71
JB
48 localStorage.removeItem(key)
49}
50
51export const getLocalStorage = (): Storage => {
52 return localStorage
53}
54
55export const randomUUID = (): `${string}-${string}-${string}-${string}-${string}` => {
56 return crypto.randomUUID()
57}
39cd8fcb
JB
58
59export const useUIClient = (): UIClient => {
60 return UIClient.getInstance()
61}