Undo/Redo

 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
function undoRedo(object) {
var storage = object;
var undoStack = [];
var redoStack = [];
return {
set: function(key, value) {
redoStack = [];
var event = {
action: "set",
key: key,
value: value,
previous: storage[key]
};
undoStack.push(event);
storage[key] = value;
},
get: function(key) {
return storage[key];
},
del: function(key) {
redoStack = [];
var event = {
action: "del",
key: key,
previous: storage[key]
};
undoStack.push(event);
delete storage[key];
},
undo: function() {
var event = undoStack.pop();
storage[event.key] = event.previous;
redoStack.push(event);
},
redo: function() {
if (redoStack.length === 0) {
throw new Error("nothing to redo");
}
var event = redoStack.pop();
if (event.action === "set") {
storage[event.key] = event.value;
} else if (event.action === "del") {
delete storage[event.key];
}
undoStack.push(event);
}
};
}