Skip to content

Instantly share code, notes, and snippets.

@moredip
Last active July 13, 2017 15:42
Show Gist options
  • Save moredip/862b2754513a1f01709ea24c2cdb979b to your computer and use it in GitHub Desktop.
Save moredip/862b2754513a1f01709ea24c2cdb979b to your computer and use it in GitHub Desktop.
Introduce Partial Application
const priceByCommodityAndCountry = {
'MANGO': [
{
origin: 'US',
price: 101
},
{
origin: 'BR',
price: 120
}
],
'BANANA': [
{
origin: 'US',
price: 111
},
{
origin: 'MX',
price: 90
}
],
'APPLE': [
{
origin: 'US',
price: 67
},
{
origin: 'BR',
price: 66
}
]
};
const EXPENSIVE_THRESHOLD=100;
function getExpensiveFruitSoldByCountry(targetCountry){
let expensiveFruit = [];
function isFromCountry(sourcedFruit){
return hasOrigin(sourcedFruit,targetCountry);
}
function isExpensive(sourcedFruit){
return isMoreExpensiveThanThreshold(sourcedFruit,EXPENSIVE_THRESHOLD);
}
Object.entries(priceByCommodityAndCountry).forEach( function([fruitName,sourcedFruits]){
sourcedFruits.forEach( function(sourcedFruit){
if( !isFromCountry(sourcedFruit) ){
return;
}
if( !isExpensive(sourcedFruit) ){
return;
}
expensiveFruit.push(fruitName);
});
});
return expensiveFruit;
}
function hasOrigin(fruit,origin){
return fruit.origin === origin;
}
function isMoreExpensiveThanThreshold(fruit,threshold){
return fruit.price > threshold;
}
console.log('expensive fruit:');
console.log('US:', getExpensiveFruitSoldByCountry('US'));
console.log('MX:', getExpensiveFruitSoldByCountry('MX'));
console.log('BR:', getExpensiveFruitSoldByCountry('BR'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment