Created
October 15, 2017 08:26
-
-
Save abiodun0/b65cbf4b2b3a7041f79639060a8a2ea9 to your computer and use it in GitHub Desktop.
complete Redux with Ramda
This file contains hidden or 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
const counterReducer = (state = 0, {type}) => { | |
switch(type) { | |
case 'INC': return state + 1 | |
case 'DEC': return state - 1 | |
default: return state | |
} | |
} | |
const todoReducer = (state = 0, {type, text}) => { | |
switch(type) { | |
case 'ADD_TODO': return [...state, {text, completed: false }] | |
default: return state | |
} | |
} | |
const redux = (reducers, state) => { | |
const listeners = [] | |
const reducingFns = | |
R.mapObjIndexed((reducer, key) => R.useWith(reducer, [R.prop(key), R.identity])) | |
const update = R.converge(R.applySpec, [reducingFns]) | |
const updateState = update(reducers) | |
return { | |
dispatch: (action) => { | |
state = updateState(state, action) | |
R.forEach(f => f(state), listeners) | |
}, | |
subscribe: (f) => { | |
listeners.push(f) | |
} | |
} | |
} | |
const store = redux({ | |
counter: counterReducer, | |
todos: todoReducer, | |
}, {counter: 0, todos: []}) | |
store.subscribe(state => console.log('LOG:', JSON.stringify(state, null, 4))) | |
store.dispatch({type: 'INC'}) | |
store.dispatch({type: 'INC'}) | |
store.dispatch({type: 'INC'}) | |
store.dispatch({type: 'INC'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment