Last active
May 30, 2018 13:13
-
-
Save kucukkanat/2177f641c026bc20a6b811f6d0664db0 to your computer and use it in GitHub Desktop.
A rewrite of redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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