Skip to content

Instantly share code, notes, and snippets.

@romagny13
Created July 13, 2017 11:34
Show Gist options
  • Save romagny13/f272ff1623d6e128cd04a8a5a7fd024b to your computer and use it in GitHub Desktop.
Save romagny13/f272ff1623d6e128cd04a8a5a7fd024b to your computer and use it in GitHub Desktop.
Understand Redux in 5 minutes
export class Store {
constructor(executor, initialState = {}) {
this.subscribers = [];
this.state = initialState;
// function that executes reducer or combined reducers and returns the new state
this.executor = executor;
}
notifySubscribers() {
for (let i = 0; i < this.subscribers.length; i++) {
this.subscribers[i]();
}
}
getState() {
return this.state;
}
dispatch(actionResult) {
this.state = this.executor(this.state, actionResult);
this.notifySubscribers();
}
subscribe(fn) {
this.subscribers.push(fn);
}
}
export function createStore(reducerOrCombinedReducers, initialState) {
return new Store((state, actionResult) => {
// returns the new state with reducer function or combined reducer function
return reducerOrCombinedReducers(state, actionResult);
}, initialState);
}
export function combineReducers(reducerObject) {
// returns a function that executes all reducers
return (state, actionResult) => {
// executes all reducers and return the new state
let newState = {};
for (let type in reducerObject) {
if (reducerObject.hasOwnProperty(type)) {
let reducer = reducerObject[type];
newState[type] = reducer(state[type], actionResult);
}
}
return newState;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment