Created
November 13, 2018 01:04
-
-
Save rhysforyou/7de68c10399ad2fd4c44de9f376198e2 to your computer and use it in GitHub Desktop.
Redux but without support for middleware
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(reducer, preloadedState = undefined) { | |
this.reducer = reducer; | |
this.state = reducer(preloadedState, { type: '@@INIT' }); | |
this.listeners = []; | |
} | |
getState() { | |
return this.state; | |
} | |
dispatch(action) { | |
this.state = this.reducer(this.state, action); | |
for (let listener of this.listeners) { | |
listener(); | |
} | |
return action; | |
} | |
subscribe(listener) { | |
this.listeners = this.listeners.concat(listener); | |
return () => { | |
const index = this.listeners.indexOf(listener); | |
this.listeners.splice(index, 1); | |
}; | |
} | |
replaceReducer(nextReducer) { | |
this.reducer = nextReducer; | |
} | |
} | |
export function createStore(reducer, preloadedState) { | |
return new Store(reducer, preloadedState); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment