command-pattern-queue
Version:
```typescript // command interface export interface ICommand { execute(): void unexecute(): void }
69 lines • 2.96 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandQueue = void 0;
class CommandQueue {
constructor() {
this.executed = [];
this.redo = [];
}
executeCommand(command) {
return __awaiter(this, void 0, void 0, function* () {
yield command.execute();
this.executed.push(command);
});
}
executeCommands(commands) {
return __awaiter(this, void 0, void 0, function* () {
for (const command of commands) {
yield this.executeCommand(command);
}
});
}
undoCommand(numberOfCommands = 1) {
return __awaiter(this, void 0, void 0, function* () {
if (this.getMaxUndo() < numberOfCommands) {
throw new Error(`Maximum undo commands is ${this.getMaxRedo()}, you try to undo ${numberOfCommands}`);
}
for (let i = 0; i < numberOfCommands; i++) {
if (this.executed.length == 0) {
throw new Error("There is no revocable command");
}
yield this.executed[this.executed.length - 1].unexecute();
this.redo.push(this.executed[this.executed.length - 1]);
this.executed.pop();
}
});
}
redoCommand(numberOfCommands = 1) {
return __awaiter(this, void 0, void 0, function* () {
if (this.getMaxRedo() < numberOfCommands) {
throw new Error(`Reduable commands is ${this.getMaxRedo()}, you try to redo ${numberOfCommands}`);
}
for (let i = 0; i < numberOfCommands; i++) {
if (this.executed.length == 0) {
throw new Error("There is no reduable command");
}
yield this.redo[this.redo.length - 1].execute();
this.executed.push(this.executed[this.executed.length - 1]);
this.redo.pop();
}
});
}
getMaxUndo() {
return this.executed.length;
}
getMaxRedo() {
return this.redo.length;
}
}
exports.CommandQueue = CommandQueue;
//# sourceMappingURL=CommandQueue.js.map