-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.ts
92 lines (81 loc) · 1.8 KB
/
index.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
88
89
90
91
92
import { Elm } from "./Main.elm";
import * as ConcurrentTask from "../../../runner";
const app = Elm.Main.init({
node: document.querySelector("main"),
flags: {
basket: loadBasket(),
trees: loadTrees(),
},
});
ConcurrentTask.register({
tasks: {
"localstorage:getItem": getItem,
"localstorage:setItem": setItem,
},
ports: {
send: app.ports.send,
receive: app.ports.receive,
},
});
type ReadError = "NO_VALUE" | "READ_BLOCKED";
function getItem(options: { key: string }): string | { error: ReadError } {
try {
const item = localStorage.getItem(options.key);
if (item === null) {
return { error: "NO_VALUE" };
} else {
return item;
}
} catch (e) {
return { error: "READ_BLOCKED" };
}
}
type WriteError = "QUOTA_EXCEEDED" | "WRITE_BLOCKED";
function setItem(options: {
key: string;
value: string;
}): void | { error: WriteError } {
try {
localStorage.setItem(options.key, options.value);
} catch (e) {
if (e.name === "QuotaExceededError") {
return { error: "QUOTA_EXCEEDED" };
} else {
return { error: "WRITE_BLOCKED" };
}
}
}
// Load Initial Fruits
interface Fruits {
apples: number;
oranges: number;
peaches: number;
pears: number;
}
function loadTrees(): Fruits {
return {
apples: loadInt("tree:apples"),
oranges: loadInt("tree:oranges"),
peaches: loadInt("tree:peaches"),
pears: loadInt("tree:pears"),
};
}
function loadBasket(): Fruits {
return {
apples: loadInt("basket:apples"),
oranges: loadInt("basket:oranges"),
peaches: loadInt("basket:peaches"),
pears: loadInt("basket:pears"),
};
}
function loadInt(key): number {
const val = localStorage.getItem(key);
try {
if (val) {
return parseInt(val);
}
return 0;
} catch (e) {
return 0;
}
}