Created
January 16, 2018 17:52
-
-
Save ShMcK/a3c26310e92dcc9197ca90fd1be5ae93 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 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