Commit | Line | Data |
---|---|---|
4940561f JB |
1 | export const convertToBoolean = (value: unknown): boolean => { |
2 | let result = false | |
3 | if (value != null) { | |
4 | // Check the type | |
5 | if (typeof value === 'boolean') { | |
6 | return value | |
7 | } else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value === '1')) { | |
8 | result = true | |
9 | } else if (typeof value === 'number' && value === 1) { | |
10 | result = true | |
11 | } | |
12 | } | |
13 | return result | |
14 | } | |
15 | ||
16 | export const convertToInt = (value: unknown): number => { | |
17 | if (value == null) { | |
18 | return 0 | |
19 | } | |
4940561f JB |
20 | if (Number.isSafeInteger(value)) { |
21 | return value as number | |
22 | } | |
23 | if (typeof value === 'number') { | |
24 | return Math.trunc(value) | |
25 | } | |
f5ee1403 | 26 | let changedValue: number = value as number |
4940561f JB |
27 | if (typeof value === 'string') { |
28 | changedValue = parseInt(value) | |
29 | } | |
30 | if (isNaN(changedValue)) { | |
31 | throw new Error(`Cannot convert to integer: '${String(value)}'`) | |
32 | } | |
33 | return changedValue | |
34 | } | |
0344ad2b JB |
35 | |
36 | export const setToLocalStorage = <T>(key: string, value: T): void => { | |
37 | localStorage.setItem(key, JSON.stringify(value)) | |
38 | } | |
39 | ||
40 | export const getFromLocalStorage = <T>(key: string, defaultValue: T): T => { | |
41 | const item = localStorage.getItem(key) | |
42 | return item != null ? (JSON.parse(item) as T) : defaultValue | |
43 | } | |
2610da71 | 44 | |
b767fda7 | 45 | export const deleteFromLocalStorage = (key: string): void => { |
2610da71 JB |
46 | localStorage.removeItem(key) |
47 | } | |
48 | ||
49 | export const getLocalStorage = (): Storage => { | |
50 | return localStorage | |
51 | } | |
52 | ||
53 | export const randomUUID = (): `${string}-${string}-${string}-${string}-${string}` => { | |
54 | return crypto.randomUUID() | |
55 | } |