-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.js
53 lines (44 loc) · 1.16 KB
/
state.js
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
import { Store } from "./store";
export class State {
#items;
#store;
constructor() {
this.#store = new Store("tasks");
this.#items = this.#store.items;
}
get items() {
return [...this.#items];
}
async addItem(name) {
if (name?.length < 1) throw "Invalid name";
this.#items.push({
id: `${crypto.randomUUID()}-${Date.now()}`,
name,
completed: false,
});
setTimeout(() => this.#store.saveItems(this.#items), 0);
}
async findItem(id) {
const taskIdx = this.#items.findIndex((task) => task.id === id);
if (taskIdx === -1) throw "Not found";
return [taskIdx, this.#items[taskIdx]];
}
async updateItem(id, updates) {
try {
const [, task] = await this.findItem(id);
for (const prop in updates) task[prop] = updates[prop];
setTimeout(() => this.#store.saveItems(this.#items), 0);
} catch (error) {
console.error(error);
}
}
async deleteItem(id) {
try {
const [taskIdx] = await this.findItem(id);
this.#items.splice(taskIdx, 1);
setTimeout(() => this.#store.saveItems(this.#items), 0);
} catch (error) {
console.error(error);
}
}
}