13 Chaining functional tools

 
Image

In this chapter

  • Learn to combine functional tools to do complex queries over data.
  • Understand how to replace complex, existing for loops with chains of functional tools.
  • Learn how to build data transformation pipelines to do work.

We’ve learned to use the functional tools in isolation to do the work we typically do with for loops over arrays. But as the computation gets more complex, a single functional tool can’t do the job. In this chapter, we will learn how to express complex calculations as a series of steps called a chain. Each step is an application of a functional tool. By combining multiple functional tools together, we can build very complex computations, yet make sure that each step is simple and easy to read and write. This skill is very common among functional programmers. It shows how deep the power of functional tools can get.

The customer communications team continues

Data request: Biggest purchases from our best customers

We suspect that our most loyal customers also make the biggest purchases. We would like to know what the biggest purchase is for each of our best customers (three or more purchases).

Image Requested by: Chief marketing officer

Image Owned by: Kim on dev team

Image

Harry: This one seems more complicated.

John: Yeah. We need to get the biggest purchase, but only from the best customers. That sounds hard.

Clarifying chains, method 1: Name the steps

Clarifying chains, method 2: Naming the callbacks

Clarifying chains: Two methods compared

Example: Emails of customers who have made one purchase

Refactoring existing for loops to functional tools

Tip 1: Make data

Tip 2: Operate on whole array at once

Tip 3: Take many small steps

Tip 3: Take many small steps

Comparing functional to imperative code

Summary of chaining tips

Debugging tips for chaining

Many other functional tools

reduce() for building values

sitemap