Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active September 28, 2017 08:47
Show Gist options
  • Save mizchi/d8966adda10e1dced7e1e3a235b57da0 to your computer and use it in GitHub Desktop.
Save mizchi/d8966adda10e1dced7e1e3a235b57da0 to your computer and use it in GitHub Desktop.
Reducer is subset of Rx
const Rx = require('rx')
const combineReducers = reducerMap => {
const initialState = Object.entries(
reducerMap
).reduce((acc, [key, reducer]) => {
return Object.assign({}, acc, {
[key]: reducer(undefined, { type: '__init' })
})
}, {})
return (state = initialState, action) => {
console.log('run combined reducer')
return Object.entries(reducerMap).reduce((acc, [key, reducer]) => {
return Object.assign({}, acc, {
[key]: reducer(state[key], action)
})
}, {})
}
}
const ADD = 'add'
const add = n => ({ type: ADD, payload: n })
const initialState = {
value: 0
}
const counter = (state = initialState, action) => {
switch (action.type) {
case ADD:
return { value: action.payload + state.value }
default:
return state
}
}
const rootReducer = combineReducers({ counter })
const actions = Rx.Observable.from([add(1), add(2), add(3)])
const scanned = actions.scan(rootReducer, undefined) // need undefined to pass with reducer on init
scanned.subscribe(x => {
console.log('subscribe', x)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment