Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Example 1
- function add(x, y) { return x + y; }
- function sub(x, y) { return x - y; }
- function mul(x, y) { return x * y; }
- function div(x, y) { return x / y; }
- const Command = function (execute, undo, value) {
- this.execute = execute;
- this.undo = undo;
- this.value = value;
- }
- const AddCommand = function (value) {
- return new Command(add, sub, value);
- };
- const SubCommand = function (value) {
- return new Command(sub, add, value);
- };
- const MulCommand = function (value) {
- return new Command(mul, div, value);
- };
- const DivCommand = function (value) {
- return new Command(div, mul, value);
- };
- const Calculator = function () {
- let current = 0;
- let commands = [];
- let index = 0;
- function action(command) {
- let name = command.execute.toString().substr(9, 3);
- return name.charAt(0).toUpperCase() + name.slice(1);
- }
- return {
- execute: function (command) {
- current = command.execute(current, command.value);
- commands.push(command);
- index++;
- console.log(action(command) + ": " + command.value);
- },
- undo: function () {
- if (index > 0) {
- let command = commands[index - 1];
- current = command.undo(current, command.value);
- index--;
- console.log("Undo " + action(command) + ": " + command.value);
- }
- },
- redo: function () {
- if (index < commands.length) {
- let command = commands[index];
- current = command.execute(current, command.value);
- index++;
- console.log("Redo " + action(command) + ": " + command.value);
- }
- },
- getCurrentValue: function () {
- return current;
- }
- }
- }
- const calculator = new Calculator();
- // issue commands
- calculator.execute(new AddCommand(100));
- calculator.execute(new SubCommand(24));
- calculator.execute(new MulCommand(6));
- calculator.execute(new DivCommand(2));
- calculator.undo();
- calculator.undo();
- calculator.redo();
- calculator.redo();
- calculator.redo();
- console.log(`Answer: ${calculator.getCurrentValue()}`);
- //Example 2
- const carManager = {
- // request information
- requestInfo: function (model, id) {
- return "The information for " + model + " with ID " + id + " is foobar";
- },
- // purchase the car
- buyVehicle: function (model, id) {
- return "You have successfully purchased Item " + id + ", a " + model;
- },
- // arrange a viewing
- arrangeViewing: function (model, id) {
- return "You have successfully booked a viewing of " + model + " ( " + id + " ) ";
- }
- };
- carManager.execute = function (name) {
- return carManager[name] && carManager[name].apply(carManager, [].slice.call(arguments, 1));
- };
- console.log(carManager.execute("buyVehicle", "Ford Escort", "453543"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement