Tutorial: Creating command object

Creating command object

Creating a command object

Let say we are wanting to create an object which has undo and redo capabibility, for example a calculator.

1. Class creation

The first thing to do is to create the class for our editor which will extends the Commands component. This component will add several methods such as execute, undo and redo.

We are thus creating a new file, called Editor.class.js with the following code:

const Commands = require('@gilles.rasigade/pattern').Commands;

module.exports = class Editor extends Commands {
  constructor(char = '') {
    super();
    this.char = char;
  }
  toString() { return this.char; }

  _add(char = '') {
    this.char += char;
  }
  _remove(char = '') {
    this.char = this.char.slice(0, -char.length);
  }

  add(char) {
    this.execute('_add', [ char ], '_remove', [ char ]);
    return this;
  }
}
2. Use example

The Commands class allows to call methods of the object with their reverse equivalent. For example, adding 1 to a number can be reverse by removing 1 from this same number.

In our example, we are wanting to add characters to the editor and remove them on undo. We can do this thanks to the private methods we defined in the Editor class _add and _remove.

const Editor = require('./Editor);

const editor = new Editor();

editor.add('Hello');
editor.add(' World');

console.log(`Current char\t${editor}`);
// Current char: Hello World

editor.undo();

console.log(`After undo\t${editor}`);
// Current char: Hello

editor.redo();

console.log(`After redo\t${editor}`);
// Current char: Hello World

Other methods can be retained for the _redo method but the result must be the same.