-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1-theory.js
More file actions
107 lines (80 loc) · 2.17 KB
/
1-theory.js
File metadata and controls
107 lines (80 loc) · 2.17 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
'use strict';
// Memento: Captures and stores the state of the Originator
class InventorySnapshot {
constructor(state) {
this.state = state;
}
getState() {
return this.state;
}
}
// Originator: The object whose state we want to save and restore
class Inventory {
constructor() {
this.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 new InventorySnapshot({ ...this.items });
}
restore(snapshot) {
this.items = snapshot.getState();
}
}
// Caretaker: Manages snapshots for the Originator
class InventoryHistoryManager {
constructor() {
this.history = [];
}
saveSnapshot(inventory) {
this.history.push(inventory.save());
}
restoreSnapshot(inventory) {
if (this.history.length > 0) {
const snapshot = this.history.pop();
inventory.restore(snapshot);
}
}
}
// Usage
const inventory = new Inventory();
const historyManager = new InventoryHistoryManager();
// 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 }