-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3-universal.js
More file actions
91 lines (69 loc) · 2.04 KB
/
3-universal.js
File metadata and controls
91 lines (69 loc) · 2.04 KB
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
'use strict';
class Inventory {
items = {};
addItem(itemName, quantity) {
const prev = this.items[itemName] || 0;
this.items[itemName] = prev + quantity;
}
removeItem(itemName, quantity) {
const prev = this.items[itemName];
if (!prev) {
if (quantity !== 0) throw Error('Insufficient quantity');
return;
}
const current = prev - quantity;
this.items[itemName] = current;
if (current > 0) this.items[itemName] = current;
else if (current === 0) delete this.items[itemName];
else throw Error('Insufficient quantity');
}
showItems() {
console.log('Current Inventory:\n ', this.items);
}
save() {
return Object.assign({}, this.items);
}
restore(snapshot) {
this.items = snapshot;
}
}
class HistoryManager {
#directory = new Map();
saveSnapshot(historizable) {
const snapshot = historizable.save();
const history = this.#directory.get(historizable);
if (history) history.push(snapshot);
else this.#directory.set(historizable, [snapshot]);
}
restoreSnapshot(historizable) {
const history = this.#directory.get(historizable);
if (!history) return;
const snapshot = history.pop();
historizable.restore(snapshot);
if (history.length === 0) this.#directory.delete(historizable);
}
}
// Usage
const inventory = new Inventory();
const historyManager = new HistoryManager();
// Initial items
inventory.addItem('keyboard', 10);
inventory.addItem('laptop', 5);
historyManager.saveSnapshot(inventory);
inventory.addItem('phone', 20);
inventory.addItem('router', 15);
historyManager.saveSnapshot(inventory);
inventory.addItem('mouse', 25);
inventory.showItems();
// Current Inventory:
// { keyboard: 10, laptop: 5, phone: 20, router: 15, mouse: 25 }
// Undo last addition
historyManager.restoreSnapshot(inventory);
inventory.showItems();
// Current Inventory:
// { keyboard: 10, laptop: 5, phone: 20, router: 15 }
// Undo another change
historyManager.restoreSnapshot(inventory);
inventory.showItems();
// Current Inventory:
// { keyboard: 10, laptop: 5 }