Skip to content

Instantly share code, notes, and snippets.

@gmmorris
Last active November 1, 2015 15:17
Show Gist options
  • Save gmmorris/de5060fa93caf1066b2a to your computer and use it in GitHub Desktop.
Save gmmorris/de5060fa93caf1066b2a to your computer and use it in GitHub Desktop.
An example of a higher order function for my How to Grok a Higher Order Class article
// Our higher order function which converts pennies to pounds (£) (or cents to dollars, for that matter)
function convertPenniesToPounds(priceFunction) {
return function() {
return priceFunction.apply(this, arguments)/100;
}
}
// we have component which fetches a price in pennies
const PriceFetcher = {
getPriceInPence : function(productId) {
// fetch price from API
}
};
// we add a function to get the price in pounds
PriceFetcher.getPriceInPounds = convertPenniesToPounds(PriceFetcher.getPriceInPence);
// we can now call getPriceInPounds and it'll return the price in pounds (or the price in pennied times 100)
assert(PriceFetcher.getPriceInPounds('7376481') === 100*PriceFetcher.getPriceInPence('7376481'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment