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 });