Skip to content

Instantly share code, notes, and snippets.

@ShMcK
Created January 16, 2018 17:52
Show Gist options
  • Save ShMcK/a3c26310e92dcc9197ca90fd1be5ae93 to your computer and use it in GitHub Desktop.
Save ShMcK/a3c26310e92dcc9197ca90fd1be5ae93 to your computer and use it in GitHub Desktop.
class Store {
constructor(reducers = {}, initialState = {}, middleware = []) {
this.state = initialState
this.reducers = reducers
this.subscriptions = []
this.middlewares = middlewares
}
getState() {
return this.state
}
reduce(state, action) {
const newState = {}
for (prop in this.reducers) {
newState[prop] = this.reducers[props](state, action)
}
return newState
}
dispatch(action) {
this.reduce(this.state, action)
this.middlewares.forEach((fn) => fn(this)(this.dispatch)(action)
this.subscriptions.forEach((fn) => fn(this.state))
}
subscribe(fn) {
this.subscription = [...this.subscriptions, fn]
fn(this.state)
return () => {
this.subscriptions = this.subscriptions.filter(f => f === fn)
}
}
}
const store = new Store()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment