Last active
August 29, 2015 14:26
-
-
Save jquense/c9d2d82d3a7f5aa441be to your computer and use it in GitHub Desktop.
implementation of redux's combineReducers adding flux waitFor()
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
import { createStore } from 'redux'; | |
import combineReducers from './combineReducers'; | |
let Store = createStore(combineReducers({ | |
reducerA(state = 0, action, waitFor){ | |
if ( action.type === 'TEST'){ | |
waitState = waitFor(waitFor.reducerB) | |
if ( waitState.reducerB === 5 ) | |
state = 10 | |
} | |
return state | |
} | |
reducerB(state = 5, action, waitFor){ | |
if ( action.type === 'TEST'){ | |
state = 5 | |
} | |
return state | |
} | |
})) |
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
import invariant from 'react/lib/invariant'; | |
import transform from 'lodash/object/transform'; | |
import pick from 'lodash/object/pick'; | |
export default function combineReducers(reducers) { | |
var tokens = transform(reducers, (obj, _, name) => obj[name] = name) | |
return function combination(state = {}, action) { | |
var pendingState = {} | |
, pending = Object.create(null) | |
, handled = Object.create(null); | |
Object.assign(waitFor, tokens); | |
Object.keys(reducers).forEach( name => { | |
let reducer = reducers[name]; | |
if (typeof reducer === 'function' && !pending[name]) { | |
invokeReducer(name) | |
} | |
}) | |
return pendingState; | |
function invokeReducer(name) { | |
pending[name] = true; | |
pendingState[name] = reducers[name](state[name], action, waitFor); | |
handled[name] = true; | |
} | |
function waitFor(...names){ | |
names.forEach( name => { | |
if (pending[name]) { | |
invariant(handled[name], | |
`Circular \`waitFor()\` detected while waiting for: ${name}`) | |
return | |
} | |
invariant(reducers[name], | |
`Attempting to waitFor a reducer that is not loaded: ${name}`) | |
invokeReducer(name) | |
}) | |
return pick(pendingState, names) | |
} | |
}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks like a typo on the last
waitfor
on this line https://gist.github.com/jquense/c9d2d82d3a7f5aa441be#file-app-js-L8