Composition with Higher Order Functions
by jpsierens
Babel + JSX
// we have two simple functions, add and multiply
const add = (x, y) => x+y;
const multiply = (x, y) => x*y;
// we want to make it possible to log these functions. But instead of creating
// a class and having log() be a method, why not just create a function
// that does that for us? That way we decide when something needs logging.
// This is composition using a higher order function: it takes a function as parameter, and
// returns an enhanced version of it.
const withLogging = (wrapped) => (x, y) => console.log(wrapped(x, y));
// now we can enhance both functions with logging capabilities.
const addWithLogging = withLogging(add);
const multWithLogging = withLogging(multiply);
addWithLogging(2, 3); //5
multWithLogging(2, 3); //6