Skip to content

Instantly share code, notes, and snippets.

@rhysforyou
Created November 13, 2018 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhysforyou/7de68c10399ad2fd4c44de9f376198e2 to your computer and use it in GitHub Desktop.
Save rhysforyou/7de68c10399ad2fd4c44de9f376198e2 to your computer and use it in GitHub Desktop.
Redux but without support for middleware
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