Skip to content

Instantly share code, notes, and snippets.

@andrew--r
Created August 6, 2017 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrew--r/7e0a520b2ec3115feffba5ee59509380 to your computer and use it in GitHub Desktop.
Save andrew--r/7e0a520b2ec3115feffba5ee59509380 to your computer and use it in GitHub Desktop.
class FARule {
constructor(state, action, nextState) {
this.state = state;
this.action = action;
this.nextState = nextState;
}
applies(state, action) {
return this.state === state && this.action === action;
}
getNextState() {
return this.nextState;
}
toString() {
const { state, action, nextState } = this;
return `FARule<${state} --> ${action} --> ${nextState}>`;
}
}
class DFA {
constructor(state, finalStates, rules) {
this.state = state;
this.finalStates = finalStates;
this.rules = rules;
}
handle(action) {
const { state, finalStates, rules } = this;
const nextState = rules
.filter((rule) => rule.applies(state, action))
.map((rule) => rule.getNextState())
.pop();
return nextState !== undefined ? new DFA(nextState, finalStates, rules) : this;
}
getState() {
return this.state;
}
isFinished() {
const { finalStates, state } = this;
return finalStates.some((finalState) => state === finalState);
}
}
const dataStates = {
notAsked: 'notAsked',
loading: 'loading',
loaded: 'loaded',
failed: 'failed',
deprecated: 'deprecated',
};
const actions = {
load: 'load',
receive: 'receive',
fail: 'fail',
deprecate: 'deprecate'
};
const rulebook = [
new FARule(dataStates.notAsked, actions.load, dataStates.loading),
new FARule(dataStates.deprecated, actions.load, dataStates.loading),
new FARule(dataStates.loading, actions.receive, dataStates.loaded),
new FARule(dataStates.loading, actions.fail, dataStates.failed),
new FARule(dataStates.loaded, actions.deprecate, dataStates.deprecated)
];
const dataDFA = new DFA(dataStates.notAsked, [dataStates.loaded], rulebook);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment