FiniteStateMachine.js 743 B

123456789101112131415161718192021222324252627282930313233343536
  1. export class StateNotRegisteredError extends Error{};
  2. export class FiniteStateMachine {
  3. constructor() {
  4. this.states = {};
  5. this.currentState = null;
  6. }
  7. registerState(key, state) {
  8. this.states[key] = state;
  9. }
  10. setCurrentState(key) {
  11. this.currentState = key;
  12. }
  13. getState(key) {
  14. try {
  15. return this.states[key];
  16. } catch(e) {
  17. throw new StateNotRegisteredError(`The state ${key} is not registered`);
  18. }
  19. }
  20. getCurrentState() {
  21. return this.getState(this.currentState);
  22. }
  23. transitionTo(key) {
  24. let current = this.getCurrentState();
  25. let target = this.getState(key);
  26. current.leave(target);
  27. target.enter(current);
  28. this.setCurrentState(key);
  29. }
  30. }