Skip to content

Instantly share code, notes, and snippets.

@borisd
Created April 20, 2017 00:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borisd/c08eba0f96b88cac9af5e1a9919ae349 to your computer and use it in GitHub Desktop.
Save borisd/c08eba0f96b88cac9af5e1a9919ae349 to your computer and use it in GitHub Desktop.
Simple Redux Implementation
const reducer = (state, action) => action.type == 'INC'
? Object.assign({}, state, { counter: state.counter + 1 })
: state;
const store = createStore(reducer, { counter: 1 });
const unsubscribe = store.subscribe(() => console.log('Counter: ' + store.getState().counter));
store.dispatch({ type: 'INC' })
store.dispatch({ type: 'INC' })
unsubscribe();
store.dispatch({ type: 'INC' })
class Store {
constructor(reducer, state) {
Object.assign(this, { state, reducer, cbs: [] });
}
getState() {
return this.state
}
dispatch(action) {
this.state = this.reducer(this.state, action);
this.cbs.forEach(cb => cb());
}
subscribe(cb) {
this.cbs.push(cb);
return () => {
this.cbs = this.cbs.filter(i => i !== cb);
}
}
}
const createStore = (reducer, initialState) => new Store(reducer, initialState);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment