Creating compound functions using a series of arrow functions

Examining the compose function (borrowed from Redux)

function compose(...funcs) {
    if (funcs.length === 0) {
      return arg => arg
    }

    if (funcs.length === 1) {
      return funcs[0]
    }

    return funcs.reduce((a, b) => (...args) => a(b(...args)))
  }

const double = x => x * 2
const square = x => x * x
const double1 = x => x * 3
compose(double, square, double1)(5)

In the final return statement

funcs.reduce((a, b) => (...args) => a(b(...args)))

Why is a function that takes ..args being returned, instead of just

funcs.reduce((a, b) => a(b(...args))) ?

Answer №1

If you choose the suggested approach, you will encounter a compile error because you are trying to return the result of a(b(...args)) without passing the arguments (args). This means that args is not defined.

On the other hand, in the alternative approach, a function is returned which takes parameters (args - 5 is passed as args) and returns the result of a(b(...args)) using:

(...args) => a(b(...args))

Take a look at this example which demonstrates the distinction between these two methods.

function a(str) {
  console.log('In a');
  console.log(str);
  return str;
}

function b(str) {
  console.log('In b');
  console.log(str);
  return str;
}

const message = a(b('text')); // Immediate result with your approach.
console.log(`Message is ${message}`);

const func = (someText) => a(b(someText)); // Given approach where `func` needs to be called to obtain the result.

const anotherMessage = func('anotherText'); // Here `func` needs to be called and a parameter needs to be passed to it.
console.log(`Message is ${anotherMessage}`);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring Radiobuttons are Selected on a Page After Clicking the Submit Button

Seeking assistance with this issue: I am working on a page that includes radio buttons: <label>Delivery type:</label> <input type="radio" name="delivery" value="7" class="delivery-item" id="del-type-7" onclick=""><label class="label" ...

"Utilize the addEventListener function in combination with the 'for' keyword to

I have been working on a Chrome extension where I use a "for" loop to change the display style of elements named "mode" to none, except for one which should be displayed at the end of the loop. However, whenever I click on the button to activate it, my tab ...

Instructions on how to automatically navigate to a different tab upon clicking an <a> element on a separate webpage, and subsequently display the designated tab on that

I have a button on my home page that, when clicked, should open a specific tab section on another page. The button is located on one page and the tabs are on a different page. On the second page, I have multiple tabs but will only mention one here, which ...

Utilizing JSON for live population of search filter results

I'm currently developing a search function for my website that will sift through a JSON Object using regular expressions. My goal is to have the results displayed in real time as the user types, similar to how Google shows search suggestions. However ...

Encountering the error message "This expression cannot be invoked" within a Typescript React Application

I'm working on separating the logic from the layout component in my Typescript React Application, but I suspect there's an issue with the return type of my controller function. I attempted to define a type to specify the return type, but TypeScr ...

`Where to include controller.js scripts in an Angular application`

As I dive into learning angular.js with .NET MVC, one major issue that keeps coming up is the fact that many tutorials advise referencing multiple controllers and services in the main (_Layout) page, which can make it quite messy. Although it may seem sim ...

The argument type does not match the parameter type partial<>

While attempting to validate my Ionic React form, I encountered an error when calling the validationSchema within the useForm method. The specific error message received is as follows: Argument of type '{ validationSchema: ......' is not assignab ...

What is the best way to prevent an iFrame from causing its parent window to scroll?

I recently came across an HTML document that includes an iframe towards the bottom of its content. Specifically, the iframe is embedding a Google Spreadsheet, using the following code: <iframe id="gsheet-group" width="100%" height=& ...

Uncovering the Mystery: The Issue of Duplicate Items When Writing Arrays to localStorage in JavaScript

Struggling to create a Javascript quiz for my coding bootcamp. I'm facing challenges with retrieving and saving previous high scores from local storage. Can someone explain why the newScore is being written TWICE to the highScores arrayItems array in ...

Issue with $sce.trustAsResourceUrl(url) function in angularJS

Having trouble with loading a file into an iframe. Here is the code for the iframe: <iframe width="100%" height="800px" scrolling="no" ng-src="{{someUrl}}"></iframe> In the controller, I am trying to: $scope.someUrl = $sce.trustAsResourceUr ...

Please ensure to submit the form only one time

[I keep receiving repeated notifications]. I am trying to execute a PHP script using a cron job, and I have come across two options to automatically submit a form or click a button. However, the scripts are performing the action repeatedly when I only wan ...

Select a different inspiring quote every hour

Wouldn't it be great to add a touch of inspiration to my page with a new motivational quote that changes every hour or day? I'm thinking of compiling all the quotes in a document and having javascript randomly select one to display on my website. ...

When working with THREE.js in Electron, web development tools seem to vanish into thin air

Exploring electron is fairly new to me (if you know of any good documentation, please leave it in the comments) and I've encountered an issue that has left me puzzled: Everything seems fine until I load the THREE.js library. At that point, even thoug ...

Is it possible to share a variable between different scopes in an Angular environment?

As I dive into building my first real Angular.js application, focused on assisting judges during courtroom hearings, I am encountering various challenges and learning how to overcome them. The application consists of views such as Calendar, Documents, and ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

Integrating Gesture Handling in Leaflet JS for two-finger scrolling enforcement

Have you ever noticed that when you're using a mobile device and scrolling down a webpage with a Google map, the map goes dark and prompts you to "Use two fingers to move the map"? https://i.stack.imgur.com/4HD1M.jpg I am interested in incorporating ...

What is the best way to include a new property to an existing interface and then export the updated interface in Typescript?

Can you provide guidance on creating a new interface - UIInterface that combines SummaryInterface with additional properties? For example: import { SummaryInterface } from 'x-api'; // summaryInterface includes 20+ predefined properties generated ...

Challenges of modifying a scope object in Angular through reference

I am encountering a challenge when trying to update a reference of an object within my code. Here's the scenario: function modifyUserDetails(user) { $scope.initialUser = user; $scope.alteredUser = angular.copy(user); } ...

Clicking on the input triggers the appearance of a border using the OnClick function

I am currently developing my own website with a login feature that requires input tags of text-type. I would like to implement a functionality where clicking on these input tags will display a border, even when the mouse is not directly hovering over them. ...

Updating a database seamlessly via a dropdown menu without having to refresh the entire webpage

Before we proceed, please take a look at the following code: $(document).ready(function() { $("#alternatecolor [type=button]").each(function() { $(this).on('click', function() { btnObj = $(this); rowId = $(this).attr("rowId") ...