Pipe Small Functions Together

Each wrapper from the last lesson added one behavior around one function. Marco’s answer sheets need something else. Teams write their answers by hand, and Marco types them in as written, stray spaces and capital letters included. Before his script can mark an answer, it has to tidy it, and each tidying step is a small function of its own.

In this lesson, you’ll join small functions into one named transformation with a pipe() function that you build from .reduce(). You’ll also read its mirror image, compose(), and decide when a plain chain or a named function reads better than either. Start with the way you’d write it today, one call inside another.

Read Steps in the Order They Run

Nested calls run from the inside out, which is the opposite of the order you read them in. Here are Marco’s three steps for one question in the Eighties category, called the way you already know:

Language: JavaScript Filename: nested.js
const trimSpaces = (answer) => answer.trim();
const lowerCase = (answer) => answer.toLowerCase();

function markAnswer(answer) {
  if (answer === "depeche mode") {
    return 1;
  }
  return 0;
}

const raw = "  Depeche Mode ";
console.log(markAnswer(lowerCase(trimSpaces(raw))));

Run it, and the messy answer still earns its point:

Language: Shell
$ node nested.js
1

To follow the last line, you start at trimSpaces(raw) in the middle and work outward. Each new step adds another pair of parentheses. A method chain from the standings reads in running order, but it only works with methods the value already has. A string has .trim() and .toLowerCase(), but it has no .markAnswer().

A pipe gives your own functions that running order. pipe() is a higher-order function: it takes the steps as arguments and returns one new function that runs them in the order you listed them:

Language: JavaScript Filename: pipe.js
const trimSpaces = (answer) => answer.trim();
const lowerCase = (answer) => answer.toLowerCase();

function markAnswer(answer) {
  if (answer === "depeche mode") {
    return 1;
  }
  return 0;
}

function pipe(...fns) {
  return (value) => fns.reduce((acc, fn) => fn(acc), value);
}

const tidyScore = pipe(trimSpaces, lowerCase, markAnswer);
console.log(tidyScore("  Depeche Mode "));
console.log(tidyScore("Duran Duran"));

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.