Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Created August 29, 2017 05:48
Show Gist options
  • Save AndrewRayCode/051fc852061db19f3cba4479e7ffbb0a to your computer and use it in GitHub Desktop.
Save AndrewRayCode/051fc852061db19f3cba4479e7ffbb0a to your computer and use it in GitHub Desktop.
// Apply a series of reducers, continuation passing style, to the state object,
// and return the transformed state
export function applyMiddleware(
keysDown:Object,
actions:Object,
gameData:Object,
oldState:Object,
initialState:Object,
...reducers
):Object {
// Keep track of what reducer we're on, because when a reducer calls next()
// it needs to call the next reducer in the array
let index = -1;
const next = newState => {
index = index + 1;
if( !reducers[ index ] && index < reducers.length ) {
console.error( 'One of your reducers is undefined: ', reducers );
throw new Error( 'One of your reducers is undefined.' );
}
return reducers[ index ] ?
// Either call the next reducer...
reducers[ index ]( keysDown, actions, gameData, oldState, newState, next ) :
// Or we're at the end
newState;
};
return {
...oldState,
...next( initialState ),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment