Skip to content

Instantly share code, notes, and snippets.

@ben196888
Last active November 23, 2018 05:25
Show Gist options
  • Save ben196888/350cc87a676b450446514b9492d22362 to your computer and use it in GitHub Desktop.
Save ben196888/350cc87a676b450446514b9492d22362 to your computer and use it in GitHub Desktop.
Provide a simple solution to create big portion of state when given some small portions
sb = new StateBuilder()
state = sb.setQuery({})
.setConverstion.setMultipleChoiceQuestion({})
.setConverstion.setFreeTextQuestion({})
.build()
class StateBuilder extends GenericStateBuilder {
constructor(args) {
super(args)
}
get setConversation() {
// Singleton
if (!this._conversationStateBuilder) {
this._conversationStateBuilder = new ConversationStateBuilder(this.rootStateBuilder)
this.state.consersation = this._conversationStateBuilder
}
return this._conversationStateBuilder
}
setQuery(state) {
this.state.query = state
return this.rootStateBuilder
}
}
class GenericStateBuilder {
constructor(that = this) {
this.rootStateBuilder = that
this.state = {}
}
build() {
const getState = () => Object.entries(this.state)
.reduce((acc, [key, value]) => {
if (value instanceof GenericStateBuilder) {
acc[key] = value.build();
} else if (value !== undefined) {
acc[key] = value
}
return acc
}, {})
return getState()
}
}
class ConversationStateBuilder extends GenericStateBuilder {
constructor(args) {
super(args)
}
setMultipleChoiceQuestion(state) {
this.state.questions = state
return this.rootStateBuilder
}
setFreeTextQuestion(state) {
this.state.freeText = state
return this.rootStateBuilder
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment