I used the if conditinal to see if I could except the case in that removeItem() is called without argument… But I understand now that this is not possible since I declared removeItem to ask at lease for the argument index.
Your explanation regarding index 0 explains all my confusion.
const immutableReducer = (state = [0,1,2,3,4,5], action) => {
switch(action.type) {
case ‘REMOVE_ITEM’:
// don’t mutate state here or the tests will fail
return […state].slice(0,action.index).concat([…state].slice(action.index+1,state.length))
//A copy of state array is sliced from index position 0 to one position short of required item, and this array is concatenated with another sliced array starting from one position ahead of item to end of state array
default:
return state;
}
};
In this specific case, the state is not mutated. However, be careful using splice in such cases because e.g. what if the state array was an array of objects… Then the spread operator won’t be successful in making a deep copy of all the objects. Subsequently, using splice will mutate the original state array. The point is, if you can do what you want with slice or any other inherently non-mutating method, use that instead of methods like splice.
Yes, that is a good point. I’m new to functional programming principles and while I like the idea of it, my initial implementations of feel like I’m making the code harder to read!
Yeah, there is a bit of that sometimes… If something goes wrong, it is easier to debug later, but you still pay a price for it(i.e. creating new variables to copy objects).