Skip to content

Instantly share code, notes, and snippets.

@aduth

aduth/reducer.js Secret

Created March 7, 2019 21:01
Show Gist options
  • Save aduth/a06a58c88a5617e27d08d890649f159a to your computer and use it in GitHub Desktop.
Save aduth/a06a58c88a5617e27d08d890649f159a to your computer and use it in GitHub Desktop.
/**
* External dependencies
*/
import { get, omit, has } from 'lodash';
import EquivalentKeyMap from 'equivalent-key-map';
/**
* Reducer function returning next state for selector resolution of
* subkeys, object form:
*
* reducerKey -> selectorName -> EquivalentKeyMap<Array,boolean>
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Next state.
*/
export function isResolved( state = {}, action ) {
switch ( action.type ) {
case 'START_RESOLUTION':
case 'FINISH_RESOLUTION': {
const { reducerKey, selectorName, args } = action;
const isStarting = action.type === 'START_RESOLUTION';
const subState = get( state, [ reducerKey, selectorName ] );
const nextSubState = new EquivalentKeyMap( subState );
nextSubState.set( args, isStarting );
return {
...state,
[ reducerKey ]: {
...state[ reducerKey ],
[ selectorName ]: nextSubState,
},
};
}
case 'INVALIDATE_RESOLUTION': {
const { reducerKey, selectorName, args } = action;
const subState = get( state, [ reducerKey, selectorName ] );
const nextSubState = new EquivalentKeyMap( subState );
nextSubState.delete( args );
return {
...state,
[ reducerKey ]: {
...state[ reducerKey ],
[ selectorName ]: nextSubState,
},
};
}
case 'INVALIDATE_RESOLUTION_FOR_STORE':
return has( state, action.reducerKey ) ?
omit( state, [ action.reducerKey ] ) :
state;
case 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR': {
const { reducerKey, selectorName } = action;
return has( state, [ reducerKey, selectorName ] ) ?
{
...state,
[ reducerKey ]: omit(
state[ reducerKey ],
[ selectorName ]
),
} :
state;
}
}
return state;
}
export default isResolved;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment