Created
January 14, 2018 19:56
-
-
Save gadzhimari/c44c05affa16169c4fb2b8a2e9142e04 to your computer and use it in GitHub Desktop.
Calculate total price in different currencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const selected = [ | |
{ price: 20 }, | |
{ price: 45 }, | |
{ price: 67 }, | |
{ price: 1305 } | |
]; | |
const reducers = { | |
rubles: function(state, item) { | |
const newPrice = state.rubles + item.price; | |
return { ...state, rubles: newPrice }; | |
}, | |
dollars: function(state, item) { | |
const newPrice = state.dollars + item.price / 71.6024; | |
return { ...state, dollars: newPrice }; | |
}, | |
euros: function(state, item) { | |
const newPrice = state.euros + item.price / 79.0133; | |
return { ...state, euros: newPrice }; | |
}, | |
yens: function(state, item) { | |
const newPrice = state.yens + item.price / 0.6341; | |
return { ...state, yens: newPrice }; | |
}, | |
pounds: function(state, item) { | |
const newPrice = state.pounds + item.price / 101.7829; | |
return { ...state, pounds: newPrice }; | |
} | |
}; | |
const combineReducers = function(reducers) { | |
return function(state, item) { | |
return Object.keys(reducers).reduce(function(nextState, key) { | |
return reducers[key](nextState, item); | |
}, state); | |
} | |
}; | |
const priceReducer = combineReducers(reducers); | |
const totalPrice = selected.reduce(priceReducer, { | |
rubles: 0, | |
pounds: 0, | |
dollars: 0, | |
euros: 0, | |
yens: 0 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment