Skip to content

Instantly share code, notes, and snippets.

@EnoahNetzach
Created September 8, 2016 22:17
Show Gist options
  • Save EnoahNetzach/bbea0f67f067e53dd7da3a7b2199b1b5 to your computer and use it in GitHub Desktop.
Save EnoahNetzach/bbea0f67f067e53dd7da3a7b2199b1b5 to your computer and use it in GitHub Desktop.
redux utility for creating reducers reusing the same fn for multiple actions Raw
const noOp = a => a
const createReducer = initialState => {
const storedReducers = {}
const resolveReducer = (state, action) => (typeof state === 'undefined'
? initialState
: (storedReducers[action.type] || noOp)(state, action)
)
const traverser = actions => ({
reducer: reducer => {
(Array.isArray(actions) ? actions : [actions]).forEach(action => {
storedReducers[action] = reducer
})
return resolveReducer
}
})
resolveReducer.actions = traverser
return resolveReducer
}
const userReducer = createReducer({ a: 42, n: null })
.actions(['USER_1', 'USER_2'])
.reducer((state, { type }) => ({ ...state, n: 'a', type }))
.actions('USER_3')
.reducer((state, { type }) => ({ ...state, n: 'b', type }))
const initState = userReducer(undefined, {})
const state1 = userReducer(initState, { type: 'USER_1' })
const state2 = userReducer(state1, { type: 'USER_2' })
const state3 = userReducer(state2, { type: 'USER_3' })
const state4 = userReducer(state3, { type: 'USER_4' })
console.log(initState, state1, state2, state3, state4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment