Functional Fundamentals: Compose

This is part three in a series on functional programming concepts. Here are parts one and two.

Last time we looked at building up a chain of operations with higher-order functions. While this method works, it quickly becomes verbose. There is a better way!

Compose is an often used function in functional programming. It allows you to chain functions together that accept a single argument and return the type that the next function is expecting.

Going with our example from part two:

function discount(x) {  
    return 0.8 * x;

function half(x) {
	return x / 2;

var discountHalfPrice = compose(discount, half);  
discountHalfPrice(10); // 4

What is compose doing under the hood? It accepts two functions as parameters and returns a function that accepts an argument. When this returned function is called, the argument is passed to the right function, the result of that then passed to the left function. With compose, it's key to remember that functions are processed right to left.

function compose(f, g) {
	return function(x) {
 		return f(g(x));