Composing Functions Efficiently in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of function composition in JavaScript. We will learn how to combine multiple functions into a single function that performs a sequence of operations in a left-to-right order. Through the use of the pipeFunctions function, we will discover the benefits of function composition and how it can simplify our code and make it more readable.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28546{{"`Composing Functions Efficiently in JavaScript`"}} javascript/data_types -.-> lab-28546{{"`Composing Functions Efficiently in JavaScript`"}} javascript/arith_ops -.-> lab-28546{{"`Composing Functions Efficiently in JavaScript`"}} javascript/comp_ops -.-> lab-28546{{"`Composing Functions Efficiently in JavaScript`"}} javascript/higher_funcs -.-> lab-28546{{"`Composing Functions Efficiently in JavaScript`"}} javascript/spread_rest -.-> lab-28546{{"`Composing Functions Efficiently in JavaScript`"}} end

Function Composition with Pipes

To start practicing coding with pipes, open the Terminal/SSH and type node.

The pipeFunctions function performs left-to-right function composition using Array.prototype.reduce() with the spread operator (...). The first (leftmost) function can accept one or more arguments, while the remaining functions must be unary.

const pipeFunctions = (...fns) =>
  fns.reduce(
    (f, g) =>
      (...args) =>
        g(f(...args))
  );

Here is an example of how to use pipeFunctions to create a new function multiplyAndAdd5 that multiplies two numbers and then adds 5 to the result:

const add5 = (x) => x + 5;
const multiply = (x, y) => x * y;
const multiplyAndAdd5 = pipeFunctions(multiply, add5);
multiplyAndAdd5(5, 2); // 15

In this example, multiplyAndAdd5 is a new function that takes two arguments, 5 and 2, and applies multiply to them first, resulting in 10, and then applies add5 to the result, resulting in 15.

Summary

Congratulations! You have completed the Pipe Functions lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like