-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraphite.ts
87 lines (76 loc) · 2.35 KB
/
graphite.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
interface Graphite {
set: (key: string, value: any) => void;
get: (key: string, callback?: (value: any) => void) => void;
push: (key: string, ...values: any[]) => any[] | null;
pull: (key: string, ...values: any[]) => any[] | null;
has: (key: string, value: any) => boolean;
delete: (key: string) => any;
add: (key: string, amount: number) => number | null;
sub: (key: string, amount: number) => number | null;
}
const Graphite: Graphite = {
set: function(key: string, value: any): void {
localStorage.setItem(key, JSON.stringify(value));
const event = new CustomEvent('GraphiteStorageEvent', {
detail: { key, value },
});
window.dispatchEvent(event);
},
get: function(key: string, callback?: (value: any) => void): void {
const value = JSON.parse(localStorage.getItem(key));
callback && callback(value);
},
push: function(key: string, ...values: any[]): any[] | null {
const array = this.get(key);
if (Array.isArray(array)) {
array.push(...values);
this.set(key, array);
return array;
}
return null;
},
pull: function(key: string, ...values: any[]): any[] | null {
const array = this.get(key);
if (Array.isArray(array)) {
const newArray = array.filter(item => !values.includes(item));
this.set(key, newArray);
return newArray;
}
return null;
},
has: function(key: string, value: any): boolean {
const array = this.get(key);
if (Array.isArray(array)) {
return array.includes(value);
}
return false;
},
delete: function(key: string): any {
const value = this.get(key);
localStorage.removeItem(key);
return value;
},
add: function(key: string, amount: number): number | null {
const value = this.get(key);
if (typeof value === 'number') {
const newValue = value + amount;
this.set(key, newValue);
return newValue;
}
return null;
},
sub: function(key: string, amount: number): number | null {
const value = this.get(key);
if (typeof value === 'number') {
const newValue = value - amount;
this.set(key, newValue);
return newValue;
}
return null;
},
};
window.addEventListener('GraphiteStorageEvent', function(event: CustomEvent) {
const { key, value } = event.detail;
localStorage.setItem(key, JSON.stringify(value));
});
window.Graphite = Graphite;