FiniteStateMachine.js 801 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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. getAllStates() {
  24. return Object.values(this.states)
  25. }
  26. transitionTo(key) {
  27. let current = this.getCurrentState();
  28. let target = this.getState(key);
  29. current.leave(target);
  30. target.enter(current);
  31. this.setCurrentState(key);
  32. }
  33. }