Bruce Mu Bruce Mu - 25 days ago 17
Javascript Question

How to make this piece of code looks better

This is one of my redux reducers and I feel it looks very ugly. Possible to improve it? The goal that I want to achieve is very simple. If in my current state I already have this item, increase the quantity by 1, otherwise, add this item to state.

function globalReducer(state = initialState, action) {
switch (action.type) {
case ADD_TO_CART: {
let { item } = action;
if (state.getIn(['sideCart', 'orderItems', item.id])) {
item.quantity = state.getIn(['sideCart', 'orderItems', item.id]).get('quantity') + 1;
} else {
item.quantity = 1;
}
item = fromJS(item);
const newState = state.setIn(['sideCart', 'orderItems', item.get('id')], item);
return newState;
}
default:
return state;
}
}


The state should be looks like this:

sideCart: {
orderItems: {
1: {
id: 'orderItems-1',
name: 'AI Brown\'s BBQ Fillet of Beef with Brown Mushroom Brandy Sauce',
quantity: 10,
price: 12,
subitems: ['0', '1', '2'],
instruction: 'No rosemary for beef',
},
2: {
id: 'orderItems-2',
name: 'AI Brown\'s BBQ Fillet',
quantity: 10,
price: 14,
subitems: ['0', '1', '2'],
instruction: 'No rosemary for beef',
},
},
}

Answer

This is how I would enhance it syntactically:

const reduceCart = (state, action) => {
  let { item } = action;
  const stateIn = state.getIn(['sideCart', 'orderItems', item.id]);
  item.quantity = stateIn 
      ? stateIn + 1
      : 1; 
  item = fromJS(item);
  return state.setIn(['sideCart', 'orderItems', item.get('id')], item);
};

const globalReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TO_CART: return reduceCart(state, action);
    default: return state;
  }
};
Comments