Skip to content

Instantly share code, notes, and snippets.

@morlay
Created August 4, 2016 01:31
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 morlay/37d98cdbff05ff73cab076c5d9a983f2 to your computer and use it in GitHub Desktop.
Save morlay/37d98cdbff05ff73cab076c5d9a983f2 to your computer and use it in GitHub Desktop.
Simple Redux-like Store
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