CodeBlanks Logo Icon CodeBlanks

Challenge - Functional chain

JavaScript course · Advanced · Lesson 97/100

Build a text-processing chain with pure functions, composition and currying.

Functional chain

In this challenge you will build a chain of pure functions. Pure functions always return the same output for the same input and have no side effects.

To combine two functions you write compose(f, g); the returned function computes f(g(x)). This is called function composition.

To make a multi-argument function callable step by step you use currying: curryAdd(a) returns a function that takes b and returns a + b.

Exercise Write compose and curryAdd

Write compose(f, g) that returns a function taking x and returning f(g(x)). Then write curryAdd(a) that takes a and returns a function taking b and returning a + b.

Show example solution
Start with function compose(f, g) { return function(x) { return f(g(x)); }; }. Then write function curryAdd(a) { return function(b) { return a + b; }; }.

Example solution:
function compose(f, g) {
  return function(x) {
    return f(g(x));
  };
}

function curryAdd(a) {
  return function(b) {
    return a + b;
  };
}

Test yourself

  1. What does compose(f, g)(x) return?

    function compose(f, g) {
      return function(x) {
        return f(g(x));
      };
    }
    • g(f(x))
    • f(x) then g(x)
    • f(g(x))
    • x(f, g)
    Show answer

    f(g(x)) — Correct! compose(f, g)(x) applies g first, then passes the result to f.

  2. Complete the compose function

    function compose(f, g) {
      return function(x) {
        ____
      };
    }
    Show answer
    function compose(f, g) {
      return function(x) {
        return f(g(x));
      };
    }
  3. Match the functional concepts

    compose(f, g)
    computes f(g(x))
    curry(f)
    step-by-step args
    pure function
    no side effects
    higher-order
    returns a function

All lessons in Advanced