Created
December 29, 2016 17:56
-
-
Save jtulk/4490fc83c9dfd7b3edcc95b3e3b5bb46 to your computer and use it in GitHub Desktop.
A more efficient reducer for adding/editing/removing objects in an array using a hash table
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 initialState = { | |
byId: ['1', '2', '3'], | |
byHash: { | |
'1': {id: '1', content: {title: 'item 1'}}, | |
'2': {id: '2', content: {title: 'item 2'}}, | |
'3': {id: '3', content: {title: 'item 3'}} | |
} | |
} | |
const action1 = { | |
type: 'add', | |
id: '4', | |
payload: { id: '4', content: {title: 'item 4' }} | |
} | |
const action2 = { | |
type: 'update', | |
id: '2', | |
payload: { content: {title: 'item 2 updated' }} | |
} | |
const action3 = { | |
type: 'remove', | |
id: '4' | |
} | |
const reducer = (state = intialState, action = {}) => { | |
switch(action.type){ | |
case 'add': { | |
return { | |
byId: [ ...state.byId, action.id], | |
byHash: { | |
...state.byHash, | |
[action.id]: action.payload | |
} | |
} | |
} | |
case 'update': { | |
state.byHash[action.id] = { | |
...state.byHash[action.id], | |
...action.payload | |
} | |
return { | |
...state | |
} | |
} | |
case 'remove': { | |
const prunedIds = state.byId.filter(item => { | |
return item !== action.id // return all the items not matching the action.id | |
}) | |
delete state.byHash[action.id] // delete the hash associated with the action.id | |
return { | |
byId: prunedIds, | |
byHash: state.byHash | |
} | |
} | |
default: { | |
return state | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment