-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathundoRedo.js
More file actions
93 lines (79 loc) · 2.15 KB
/
undoRedo.js
File metadata and controls
93 lines (79 loc) · 2.15 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
function undoRedo( object ) {
// action, key
var _undoAction = undefined;
var _redoAction = undefined;
var _previousValues = {};
// prepopulate with existing keys
for ( var key in object ) {
_previousValues[ key ] = object[ key ];
}
object.set = function( key, value ) {
// if the key already exists
if ( this.hasOwnProperty( key ) ) {
_undoAction = [ 'set', key ];
_previousValues[ key ] = this[ key ];
} else {
_undoAction = [ 'del', key ];
_previousValues[ key ] = undefined;
}
this[ key ] = value;
_redoAction = undefined;
return;
};
object.get = function( key ) {
return this[ key ];
};
object.del = function( key ) {
// set, key, value
_undoAction = [ 'set', key ];
_previousValues[ key ] = this[ key ];
_redoAction = undefined;
return delete this[ key ];
};
object.undo = function() {
if ( Array.isArray( _undoAction ) ) {
var action= _undoAction[ 0 ];
var key = _undoAction[ 1 ];
if ( action === 'del' ) {
_redoAction = [ 'set', key ];
_previousValues[ key ] = this[ key ];
delete this[ key ];
_undoAction = undefined;
} else {
var oldValue = this[ key ];
if ( _previousValues[ key ] ) {
_redoAction = [ 'set', key ];
this[ key ] = _previousValues[ key ];
_previousValues[ key ] = oldValue;
//save for redo
} else {
_redoAction = [ 'del', key ];
}
this[ key ] = _undoAction[ 2 ];
_undoAction = undefined;
return;
}
} else {
throw new Error( 'There is nothing to undo.' );
}
};
object.redo = function() {
if ( Array.isArray( _redoAction ) ) {
var action= _redoAction[ 0 ];
var key = _redoAction[ 1 ];
if ( action === 'del' ) {
// set, key, value
_undoAction = [ 'set', key ];
delete this[ key ];
_undoAction = undefined;
} else {
this[ key ] = _previousValues[ key ];
_undoAction = undefined;
}
return;
} else {
throw new Error( 'There is nothing to redo.' );
}
};
return object;
}