Skip to content

Instantly share code, notes, and snippets.

@velopert
Created May 9, 2017 17:51
Show Gist options
  • Save velopert/376e333bb5a202fd85e0d677e2561e66 to your computer and use it in GitHub Desktop.
Save velopert/376e333bb5a202fd85e0d677e2561e66 to your computer and use it in GitHub Desktop.
solution, using immutablejs
import { List, Map, fromJS } from 'immutable';
const initialState = Map({
fruits: fromJS([ // this will turn this array into List of Map
{
"itemName": "banana",
"price": 1.00,
"quantityRemaining": 10
},
{
"itemName": "apple",
"price": 2.00,
"quantityRemaining": 5
},
{
"itemName": "raspberry",
"price": 5.00,
"quantityRemaining": 2
},
{
"itemName": "kiwi",
"price": 3.00,
"quantityRemaining": 15
},
{
"itemName": "pineapple,
"price": 7.00,
"quantityRemaining": 1
},
{
"itemName": "strawberries",
"price": 2.00,
"quantityRemaining": 3
}
])
});
function fruitReducer(state = initialState, action) {
switch(action.type) {
case 'DEDUCT':
let ref = state;
action.payload.forEach(
deduction => {
const index = ref.findIndex(item => item.itemName === deduction.itemName);
ref = ref.updateIn(
['fruits', index],
item => item.set('quantityRemaining', item.get('quantityRemaining') - deduction.quantityRemaining
}
);
return ref;
default:
return state;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment