Last active
September 28, 2017 08:47
-
-
Save mizchi/d8966adda10e1dced7e1e3a235b57da0 to your computer and use it in GitHub Desktop.
Reducer is subset of Rx
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
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