Command stacker to control undo/redo
npm install command-stacker
A lightweight JavaScript utility library to undo and redo commands.
```
npm install command-stacker
`typescript
import CommandStacker from 'command-stacker'
let counter = 0
const incrementCommand = {
run: () => counter++,
undo: () => counter--
}
const commandStacker = new CommandStacker()
commandStacker.run(incrementCommand)
// counter = 1
commandStacker.undo()
// counter = 0
commandStacker.redo()
// counter = 1
`
A Command is an object implementing the following interface:
`typescript`
type Command = {
run: () => void
undo: () => void
}
The CommandStacker class has two arrays representing the commands it manages: undoStack and redoStack.
It has the following methods:
Adds a Command to the undoStack and clears the redoStack.
Runs a Command, pushes it to the undoStack and clears the redoStack.
Undoes the last command from undoStack, adds it to the redoStack and returns it.undoStack
If the is empty, undefined is returned.
Pops the last command from redoStack, adds it to the undoStack and returns it.redoStack
If the is empty, undefined is returned.
Clears all commands from undoStack and redoStack.
It is possible to define your own custom Command type and pass it as a generic argument to CommandStacker:
`typescript
type CustomCommand = Command & {
name: string
}
const commandStacker = new CommandStacker
let counter = 0
const incrementCommand = {
name: 'increment',
run: counter++,
undo: counter--
}
commandStacker.run(command)
``