Skip to content

Instantly share code, notes, and snippets.

@Jalson1982
Created January 11, 2019 14:29
Show Gist options
  • Save Jalson1982/a953146a65c2324b77a40d52b8b41e7a to your computer and use it in GitHub Desktop.
Save Jalson1982/a953146a65c2324b77a40d52b8b41e7a to your computer and use it in GitHub Desktop.
const initialState = {
orders: []
};
const preparedOrdersReducer = (state = initialState, action) => {
switch (action.type) {
case SET_PREPARED_ORDERS:
return {
...state,
orders: generatePreparedOrder(state.orders, action.payload)
};
default:
return state;
}
};
const generatePreparedOrder = (orders, data) => {
//Search with ID
for (let i = 0; i < orders.length; i++) {
if (orders[i].id == data.id) {
//If find the same id order, it will combine items.
orders[i].items = generatePreparedItem(orders[i].items, data.items);
return orders;
}
}
//If there is not same id order, new order will be pushed.
orders = [...orders, data];
return orders;
};
const generatePreparedItem = (oldItems, items) => {
//Search with EAN of item
for (let i = 0; i < items.length; i++) {
let j = 0;
for (j = 0; j < oldItems.length; j++) {
if (items[i].EAN == oldItems[j].EAN) {
//If you find the same EAN item, it will be replaced.
oldItems[j] = items[i];
break;
}
}
if (j == oldItems.length) {
//Not found with same EAN item, it will be pushed.
oldItems = [...oldItems, items[i]];
}
}
return oldItems;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment