@nanomatic/design_patterns
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Command pattern

@nanomatic/design_patterns

Status License


Implementation of the all design patterns.

📝 Table of Contents

🏁 Getting Started

Installing

npm i @nanomatic/design_patterns

Using

Example code below:

import { Command, Commands } from '@nanomatic/design_patterns'

const add = (x: number = 0, y: number = 0) => x + y;
const sub = (x: number = 0, y: number = 0) => x - y;
const mul = (x: number = 0, y: number = 0) => x * y;
const div = (x: number = 0, y: number = 0) => x / y;

const addCommand = (value: number = 0) => new Command(add, sub, value);
const subCommand = (value: number = 0) => new Command(sub, add, value);
const mulCommand = (value: number = 1) => new Command(mul, div, value);
const divCommand = (value: number = 1) => new Command(div, mul, value);

// Helper function
const showResult = ({ getValue }: Commands) => console.log(`Result: ${getValue()}`);

const calculator = new Commands(0);         // Initial value.

calculator.add(addCommand(20));             // Add to queue without execute.
calculator.add(subCommand(16)).execute();   // Be aware - the first command in the queue will be executed only!
calculator.add(mulCommand(2)).execute();    // Be aware - the second command in the queue will be executed only!
calculator.add(divCommand(4)).execute();    // Be aware - the third command in the queue will be executed only!

calculator.execute();                       // You have to execute last command by calling "execute" method once again.

calculator.undo(3);                         // You can also undo some commands...
calculator.redo(3);                         // ...or redo how many times you want.

showResult(calculator);

calculator.clear();                         // Clear all pervious commands.

// ---------------------------------------------------------
// At every time, you can easly pass all commands as a array
// ---------------------------------------------------------
calculator.add([
    addCommand(20),
    subCommand(16),
    mulCommand(2),
    divCommand(4)
]).redoAll();                               // Execute all commands by calling "redoAll" method instead of "execute" 3 times.

calculator.undoAll();                       // You can also undo all commands...
calculator.redo(3);                         // ...or redo how many times you want.

calculator.execute(addCommand(2));          // It's possible to execute new command directly

showResult(calculator);

⛏️ Built With

✍️ Authors

Package Sidebar

Install

npm i @nanomatic/design_patterns

Homepage

nanomatic.pl

Weekly Downloads

3

Version

1.0.0

License

MIT

Unpacked Size

9.39 kB

Total Files

4

Last publish

Collaborators

  • nano_matic