Function Composition

MediumFunctional Programming15 min4 tests

Implement a compose function that takes multiple functions and returns a new function that applies them right-to-left.

Requirements

  • compose(f, g, h)(x) should equal f(g(h(x)))
  • Should work with any number of functions
  • With no functions, return the identity function

Example

const add1 = x => x + 1;
const double = x => x * 2;
compose(add1, double)(5); // 11 (double first: 10, then add1: 11)
Hints (3)
  1. Use reduceRight to apply functions from right to left.
  2. The initial value of the reduce is the input argument.
  3. Handle the edge case of zero functions passed.

Topics

  • Functional Programming

Asked at

Meta · Stripe · Airbnb

Join Us
blur