Created
July 8, 2022 14:30
-
-
Save wolivera/f019311d32a0d0b6e0112765ad5105d5 to your computer and use it in GitHub Desktop.
GoF Command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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