Skip to content

Instantly share code, notes, and snippets.

@nakamura-to
Created March 21, 2012 04:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakamura-to/2144167 to your computer and use it in GitHub Desktop.
Save nakamura-to/2144167 to your computer and use it in GitHub Desktop.
Command Pattern in JavaScript
// see http://d.hatena.ne.jp/ashigeru/20090113/1231857274
function edit(start, end, chars, buf) {
var undo = buf.val.slice(start, end);
buf.val = buf.val.slice(0, start) + chars + buf.val.slice(end);
return edit.bind(null, start, start + chars.length, undo);
}
function sequence(commands, buf) {
var undos = [];
commands.forEach(function (command) {
undos.push(command(buf));
});
return sequence.bind(null, undos);
}
var buf = {val: 'Hello, world!'};
var com = sequence.bind(null, [edit.bind(null, 0, 5, 'こんにちは'), edit.bind(null, 12, 13, '???')]);
console.log(buf.val);
var undo = com(buf);
console.log(buf.val);
var redo = undo(buf);
console.log(buf.val);
redo(buf);
console.log(buf.val);
// Hello, world!
// こんにちは, world???
// Hello, world!
// こんにちは, world???
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment