]> Piment Noir Git Repositories - e-mobility-charging-stations-simulator.git/blame - ui/web/src/composables/Utils.ts
chore(deps-dev): apply updates
[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 29 if (typeof value === 'string') {
48847bc0 30 changedValue = Number.parseInt(value)
4940561f 31 }
55a17ee0 32 if (Number.isNaN(changedValue)) {
408b4e6d
JB
33 // eslint-disable-next-line @typescript-eslint/no-base-to-string
34 throw new Error(`Cannot convert to integer: '${value.toString()}'`)
4940561f
JB
35 }
36 return changedValue
37}
0344ad2b 38
0344ad2b
JB
39export const getFromLocalStorage = <T>(key: string, defaultValue: T): T => {
40 const item = localStorage.getItem(key)
41 return item != null ? (JSON.parse(item) as T) : defaultValue
42}
2610da71 43
01841aad 44// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
558db46f
JB
45export const setToLocalStorage = <T>(key: string, value: T): void => {
46 localStorage.setItem(key, JSON.stringify(value))
47}
48
b767fda7 49export const deleteFromLocalStorage = (key: string): void => {
2610da71
JB
50 localStorage.removeItem(key)
51}
52
53export const getLocalStorage = (): Storage => {
54 return localStorage
55}
56
57export const randomUUID = (): `${string}-${string}-${string}-${string}-${string}` => {
58 return crypto.randomUUID()
59}
39cd8fcb 60
22427713
JB
61export const validateUUID = (
62 uuid: `${string}-${string}-${string}-${string}-${string}`
63): uuid is `${string}-${string}-${string}-${string}-${string}` => {
64 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)
65}
66
39cd8fcb
JB
67export const useUIClient = (): UIClient => {
68 return UIClient.getInstance()
69}