Function Composition

1. What is Function Composition?

Function composition is the process of combining two or more functions to produce a new function. It is equivalent to taking the output of one function and using it as the input for the next.

In mathematics, if you want to apply function g and then function f to a value x, you write it as:

f(g(x))

  • Order of Execution: Inside-Out (g runs first, then f).

  • Order of Reading: Right-to-Left.

2. The Tool: reduceRight()

To implement standard mathematical composition in JavaScript, we need a tool that processes an array of functions from Right-to-Left.

  • reduce() (Left-to-Right): Iterates index 0 --> End.

  • reduceRight() (Right-to-Left): Iterates End --> Index 0.

Because mathematical composition is written as f(g(x)), if we store our functions in an array [f, g], we must process g (the last element) first. This makes reduceRight the perfect tool.

3. Example 1: Mathematical Pipeline

Let's look at a classic numeric transformation. We want to:

  1. Double a number (x times 2).

  2. Add 5 to the result (x + 5).

  3. Square that result (x^2).

Mathematically: Square(Add5(Double(x)))

4. Example 2: String Formatting

Function composition is incredibly useful for processing text. Imagine we want to turn a messy user input into a URL slug.

Goal: Turn " Hello World " into "<div>hello world</div>".

Steps:

  1. Trim whitespace.

  2. Lowercase the text.

  3. Wrap in HTML tags.

5. Example 3: E-commerce Price Calculation

Composition helps manage complex business logic by breaking it down into small, reusable utility functions.

Scenario: Calculate final price.

  1. Apply a 10% Discount.

  2. Add 5% Tax to the discounted price.

  3. Add a flat $10 Shipping fee.

6. Composition vs. Piping

It is important to distinguish between "Compose" and "Pipe" based on how you prefer to list your functions.

Style

Direction

Array Order

Method

Compose

Right-to-Left

[f, g, h] means f(g(h(x)))

reduceRight

Pipe

Left-to-Right

[h, g, f] means h to g to f

reduce

  • Compose follows standard mathematical notation.

  • Pipe follows the logical "flow" of data (like Unix pipes |).

If you find reduceRight confusing, you can simply reverse the order of your array and use reduce—that is essentially "Piping".

Last updated