Last active
November 1, 2015 15:17
-
-
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
This file contains 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
// 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