Compose

14 Oct 2019

Composing functions together is the concept of ‘melding’ or combining functions together.

So- we could make a function:

function upperEveryOther(string){
  var splitIt = string.split('');
  for(var i=0; i<splitIt.length; i++) {
  	if(i%2===0) splitIt[i] = splitIt[i].toUpperCase();
  }
  return splitIt.join('')
}

This function accepts a string, and returns a string with every other character capitalized. Now consider this function:

function addBanana(string){
	return string + 'banana ';
}

This function also accepts a string, and simply returns a new string with ‘banana’ added to the end. Pretty straightforward.

function compose(func1, func2) {
	return function(input){
		return func2(func1(input))
	}
}

This will be our composition function. It receives two functions and returns another function that takes an input and feeds that input through both functions. However- order matters, meaning once func1 is run with the input first, and then func2 is run with the return value of func1(input).

Here’s an example that illustrates this:

var addBananaFirst = compose(addBanana, upperEveryOther);

This returns a function that takes one argument. What do you think will be logged to the console?

console.log(addBananaFirst('Hello World'));

This will log HeLlO WoRlD BaNaNa. Notice that every other character in ‘banana’ is capitalized.

Now let’s compare that example with this one:

var UpperEveryOtherFirst = compose(upperEveryOther, addBanana)

This returns a function with func1 bound to upperEveryOther and func2 bound to addBanana. When we run it:

console.log(UpperEveryOtherFirst('Hello World'));

The input is first fed into the call to upperEveryOther and the return value of that call is given to the call to addBanana. Therefore HeLlO WoRlD banana will be logged.