Skip to content

Instantly share code, notes, and snippets.

@JamesTheHacker
Created October 12, 2017 13:03
Show Gist options
  • Save JamesTheHacker/5ab43d5946f4163e6784507b5837c46e to your computer and use it in GitHub Desktop.
Save JamesTheHacker/5ab43d5946f4163e6784507b5837c46e to your computer and use it in GitHub Desktop.
/*
* This class is a high level view of how Redux works under the hood.
* This example includes no error handling or immutability and is used
* purely as an example to demonstrate how Redux works.
*/
class FauxRedux {
// Just like Redux we accept a reducer, and some initial state
constructor(reducer, initialState = {}) {
this.store = [ initialState ];
this.reducer = reducer;
this.subscribers = [];
}
// Dispatch an action
dispatch(action) {
const newState = this.reducer(
this.getState(),
action
);
this.store.push(newState);
this.notify(action.type);
}
// Get the latest state from the store
getState() {
return this.store[this.store.length - 1];
}
// Subscribe to notifications
subscribe(callback) {
this.subscribers.push(callback);
}
// Notify all subscribers
notify(action) {
this.subscribers.map(
subscriber => subscriber(action)
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment