Created
March 23, 2020 19:26
-
-
Save ripter/8afa44918e188a09d096949653c8990a to your computer and use it in GitHub Desktop.
Reducer Array CRUD
This file contains hidden or 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
/** | |
* Returns a new list, based on the previous list. | |
* Action describes how to create the new list. | |
* Shallow Copy | |
*/ | |
export function updateList(prevList: objectList, action: KeywordDispatchAction): objectList { | |
const { type, listIndex, data } = action; | |
// console.group('Action', type); | |
switch (type) { | |
case ACTION.create: | |
return prevList.concat(data); | |
case ACTION.update: | |
if (listIndex == null) { throw new Error(`Update on list "${action.listName}" requested, but listIndex "${listIndex}" is an invalid index.`); } | |
return prevList.map((item, index) => { | |
if (index !== listIndex) { | |
return item; | |
} | |
return Object.assign({}, item, data); | |
}); | |
case ACTION.delete: | |
if (listIndex == null) { throw new Error(`Update on list "${action.listName}" requested, but listIndex "${listIndex}" is an invalid index.`); } | |
return prevList.filter((_, index) => index !== listIndex); | |
default: | |
return prevList; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment