Composing Functions Left to Right

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. Specifically, we will focus on the composeRight function, which allows us to combine multiple functions into a single function that is executed from left to right. Through practical examples, we will see how function composition can simplify our code and make it more modular.


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-28597{{"`Composing Functions Left to Right`"}} javascript/data_types -.-> lab-28597{{"`Composing Functions Left to Right`"}} javascript/arith_ops -.-> lab-28597{{"`Composing Functions Left to Right`"}} javascript/comp_ops -.-> lab-28597{{"`Composing Functions Left to Right`"}} javascript/higher_funcs -.-> lab-28597{{"`Composing Functions Left to Right`"}} javascript/spread_rest -.-> lab-28597{{"`Composing Functions Left to Right`"}} end

Reversing Function Composition

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

Here's how to perform left-to-right function composition:

  • Use Array.prototype.reduce() method to perform left-to-right function composition.
  • The first (leftmost) function can accept one or more arguments, while the remaining functions must be unary.
const composeRight = (...fns) =>
  fns.reduce(
    (f, g) =>
      (...args) =>
        g(f(...args))
  );

For example:

const add = (x, y) => x + y;
const square = (x) => x * x;
const addAndSquare = composeRight(add, square);
addAndSquare(1, 2); // 9

Summary

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

Other JavaScript Tutorials you may like