Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Created October 15, 2017 08:26
Show Gist options
  • Save abiodun0/b65cbf4b2b3a7041f79639060a8a2ea9 to your computer and use it in GitHub Desktop.
Save abiodun0/b65cbf4b2b3a7041f79639060a8a2ea9 to your computer and use it in GitHub Desktop.
complete Redux with Ramda
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