Created
August 6, 2017 19:42
-
-
Save andrew--r/7e0a520b2ec3115feffba5ee59509380 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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