Skip to content

Instantly share code, notes, and snippets.

@idiotWu
Created April 4, 2015 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idiotWu/69e355ed3555559a393c to your computer and use it in GitHub Desktop.
Save idiotWu/69e355ed3555559a393c to your computer and use it in GitHub Desktop.
redo/undo manager
var Manager = function (obj) {
this.target = obj;
this.history = [];
this.step = -1;
return this;
}
Manager.prototype.set = function (key, value) {
var me = this,
target = me.target;
me.step = me.history.length;
me.history.push({
action: 'set',
key: key,
value: value,
previousValue: target[key]
});
target[key] = value;
}
Manager.prototype.get = function (key) {
return this.target[key];
}
Manager.prototype.del = function (key) {
var me = this,
target = me.target;
me.step = me.history.length;
me.history.push({
action: 'del',
key: key,
value: undefined,
previousValue: target[key]
});
delete target[key];
}
Manager.prototype.undo = function () {
var me = this,
step = me.step,
target = me.target,
history = me.history;
if (step === -1) {
throw new Error('nothing to undo.');
}
var operation = history[step];
target[operation.key] = operation.previousValue;
me.step = --step;
}
Manager.prototype.redo = function () {
var me = this,
step = me.step,
target = me.target,
history = me.history;
if (step > history.length - 2) {
throw new Error('nothing to redo.');
}
var operation = history[++step];
if (operation.action === 'del') {
delete target[operation.key];
} else {
target[operation.key] = operation.value;
}
me.step = step;
}
var undoRedo = function (obj) {
return new Manager(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment