Skip to content

Instantly share code, notes, and snippets.

@ripter
Created March 23, 2020 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ripter/8afa44918e188a09d096949653c8990a to your computer and use it in GitHub Desktop.
Save ripter/8afa44918e188a09d096949653c8990a to your computer and use it in GitHub Desktop.
Reducer Array CRUD
/**
* 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