Skip to content

Instantly share code, notes, and snippets.

@wolivera
Created July 8, 2022 14:30
Show Gist options
  • Save wolivera/f019311d32a0d0b6e0112765ad5105d5 to your computer and use it in GitHub Desktop.
Save wolivera/f019311d32a0d0b6e0112765ad5105d5 to your computer and use it in GitHub Desktop.
GoF Command
function copy(x) { return x; }
function cut(x) { return x; }
function paste(x) { return x; }
class Command {
constructor (execute, value) {
this.execute = execute;
this.value = value;
}
}
const CopyCommand = (value) => {
return new Command(copy, value);
};
const CutCommand = (value) => {
return new Command(cut, value);
};
const PasteCommand = (value) => {
return new Command(paste, value);
};
class Input {
constructor() {
this.current = '';
this.commands = [];
}
action(command) {
const name = command.execute.toString().substr(9, 3);
return name.charAt(0).toUpperCase() + name.slice(1);
}
execute (command) {
this.current = command.execute(this.current, command.value);
this.commands.push(command);
console.log(this.action(command) + ": " + command.value);
}
}
const input = new Input();
// issue commands
input.execute(CopyCommand('hi!'));
input.execute(CutCommand('sample text'));
input.execute(PasteCommand('ToDo'));
// Cop: hi!
// Cut: sample text
// Pas: ToDo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment