Skip to content

Instantly share code, notes, and snippets.

@kucukkanat
Last active May 30, 2018 13:13
Show Gist options
  • Save kucukkanat/2177f641c026bc20a6b811f6d0664db0 to your computer and use it in GitHub Desktop.
Save kucukkanat/2177f641c026bc20a6b811f6d0664db0 to your computer and use it in GitHub Desktop.
A rewrite of redux
var _ = require('lodash');
var globalStore;
function getInstance(){
if (!globalStore) globalStore = createStore();
return globalStore;
}
function createStore() {
var currentState = {};
var subscribers = [];
var currentReducerSet = {};
currentReducer = function(state, action) {
return state;
};
function dispatch(action) {
var prevState = currentState;
currentState = currentReducer(_.cloneDeep(currentState), action);
subscribers.forEach(function(subscriber){
subscriber(currentState, prevState);
});
}
function addReducers(reducers) {
currentReducerSet = _.assign(currentReducerSet, reducers);
currentReducer = function(state, action) {
var ret = {};
_.each(currentReducerSet, function(reducer, key) {
ret[key] = reducer(state[key], action);
});
return ret;
};
}
function subscribe(fn) {
subscribers.push(fn);
}
function unsubscribe(fn) {
subscribers.splice(subscribers.indexOf(fn), 1);
}
function getState() {
return _.cloneDeep(currentState);
}
return {
addReducers,
dispatch,
subscribe,
unsubscribe,
getState
};
}
module.exports = getInstance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment