Skip to content

Instantly share code, notes, and snippets.

@mrbalihai
Last active November 7, 2020 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrbalihai/22b14c87e75f7c1fccac3f83e9906fd5 to your computer and use it in GitHub Desktop.
Save mrbalihai/22b14c87e75f7c1fccac3f83e9906fd5 to your computer and use it in GitHub Desktop.
Code examples for mrbalihai.github.io/2016/02/07/javascript-function-composition.html
var add = function(a, b) { return a + b; };
var sum = function (arr) { return arr.reduce(add, 0) };
var getProperty = function(obj, propName) { return obj[propName]; };
var getWhisky = function (obj) { return getProperty(obj, 'whisky' };
var getPrices = function (arr) {
return arr.map(function (a) {
return getProperty(a, 'price');
});
};
var getTotalWhiskyPrice = function (obj) {
return sum(getPrices(getWhisky(obj)));
};
getTotalWhiskyPrice(products); // => 176.4
let add = (a, b) => a + b;
let sum = (arr) => arr.reduce(add, 0);
let getProperty = (obj, propName) => obj[propName];
let getWhisky = (obj) => getProperty(obj, 'whisky');
let getPrices = (arr) => arr.map((a) => getProperty(a, 'price'));
let getTotalWhiskyPrice = (obj) => sum(getPrices(getWhisky(obj));
getTotalWhiskyPrice(products); // => 176.4
var products = {
'whisky': [
{
'name': 'Ardberg Uigeadail',
'price': 54.35,
'currency': 'GBP'
},
{
'name': 'Laphroaig Quarter Cask',
'price': 39.95,
'currency': 'GBP'
},
{
'name': 'Klichoman Machir Bay',
'price': 42.25,
'currency': 'GBP'
},
{
'name': 'Talisker Storm',
'price': 39.85,
'currency': 'GBP'
}
]
};
var _ = require('lodash');
var getWhisky = _.partialRight(_.get, 'whisky');
var getPrices = _.partialRight(_.map, 'price');
var getTotalWhiskyPrice = _.flowRight(_.sum,
getPrices,
getWhisky);
getTotalWhiskyPrice(products); // => 176.4
var _ = require('ramda');
// var _ = require('lodash/fp');
var getWhisky = _.prop('whisky');
var getPrices = _.map(_.prop('price')); // Using Ramda
//var getPrices = _.map('price'); // Using lodash-fp
var getTotalwhiskyPrice = _.compose(_.sum,
getPrices,
getWhisky);
getTotalWhiskyPrice(products); // => 176.4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment