Created
August 4, 2016 01:31
-
-
Save morlay/37d98cdbff05ff73cab076c5d9a983f2 to your computer and use it in GitHub Desktop.
Simple Redux-like Store
This file contains 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, initialState) { | |
this.state = initialState; | |
this.reducer = reducer; | |
this.trigger = () => null; | |
} | |
subscribe(callback) { | |
this.trigger = callback; | |
} | |
getState() { | |
return this.state; | |
} | |
dispatch(action) { | |
this.state = this.reducer(this.state, action); | |
this.trigger(); | |
} | |
} | |
const ADD = 'ADD'; | |
const DELETE = 'DELETE'; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case ADD: | |
return state + 1; | |
case DELETE: | |
return state - 1; | |
default: | |
return state; | |
} | |
}; | |
const store = new Store(reducer, 0); | |
store.subscribe(() => { | |
console.log('Next State', store.getState()); | |
}); | |
store.dispatch({ type: ADD }); | |
store.dispatch({ type: ADD }); | |
store.dispatch({ type: ADD }); | |
store.dispatch({ type: DELETE }); | |
store.dispatch({ type: DELETE }); | |
store.dispatch({ type: DELETE }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment