Skip to content

Instantly share code, notes, and snippets.

@bietkul
Created February 15, 2019 01:57
Show Gist options
  • Save bietkul/38905d32b088c1e48bdcd37378476152 to your computer and use it in GitHub Desktop.
Save bietkul/38905d32b088c1e48bdcd37378476152 to your computer and use it in GitHub Desktop.
import some from 'lodash/some';
import AppConstants from '../utils/constants';
const initialProductState = {
items: [],
totalPrice: 0,
};
const addItems = (items = [], payload) => {
const newItems = items.map(item => item);
if (!some(items, e => e._id === payload._id)) {
newItems.push(payload);
}
return newItems;
};
const removeItem = (items = [], id) => {
const newItems = items.map(item => item);
newItems.every((e, index) => {
if (e._id === id) {
newItems.splice(index, 1);
return false;
}
return true;
});
return newItems;
};
function checkout(state = initialProductState, action) {
switch (action.type) {
case AppConstants.CHECKOUT.ADD_PRODUCT:
return {
...state,
items: addItems(state.items, action.payload),
};
case AppConstants.CHECKOUT.REMOVE_PRODUCT:
return {
...state,
items: removeItem(state.items, action.payload),
};
default:
return state;
}
}
export default checkout;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment