FiniteStateMachine.js 983 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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, useCallback = false) {
  27. let current = this.getCurrentState();
  28. let target = this.getState(key);
  29. if(useCallback) {
  30. current.leave(target, () => {
  31. target.enter(current);
  32. this.setCurrentState(key);
  33. });
  34. } else {
  35. current.leave(target, () => {});
  36. target.enter(current);
  37. this.setCurrentState(key);
  38. }
  39. }
  40. }