What is the proper way for the curry function to function effectively?

Here's a function that I came across:

function curry(fn) {
    var args = [].slice.call(arguments, 1);
    return function() {
        return fn.call(this, args.concat([].slice.call(arguments)));
    };
}

I always thought this was the correct way for the function to look and work like this:

function add(a, b, c, d) {
   return a+b+c+d;
}


curry(add, 1, 2)(3, 4);

However, after reading the information on Wikipedia Article, it seems that

it can be called as a chain of functions, each with a single argument

This means the curry function should actually look like this:

function curry(fn) {
    var args = [];
    return function curring() {
        args = args.concat([].slice.call(arguments));
        if (args.length >= fn.length) {
            return fn.apply(this, args);
        } else {
            return curring;
        }
    };
}

And it should be used in this manner:

function add(a, b, c, d) {
   return a+b+c+d;
}

curry(add)(1)(2)(3)(4);

Is this approach correct?

Answer №1

Essentially, currying transforms a function with multiple arguments into a sequence of functions, each accepting only one argument, similar to how your second curry function operates:

  • By invoking all these functions in succession, you essentially execute the original function, resulting in the same output:
    curry(add)(1)(2)(3)(4) yields the equivalent result as add(1, 2, 3, 4), which is 10

  • If you only call a subset of these functions, you generate a partially applied function:

    1. addOne = curry(add)(1);
    2. addOneAndTwo = addOne(2);
    3. addOneAndTwo(3)(4) equates to 10

In Javascript, currying is often used interchangeably with partial application, much like in the case of your first curry function. Summarizing the Prototype documentation:

curry caters (burns in) arguments into a function, creating a new function that, upon invocation, will pass along the curried arguments alongside any new ones to the original.

For more elaborate insights, refer to What is the distinction between currying and partial application.

Below is a functional implementation of a genuine currying function in javascript crafted by Evan Borden.

Some things to keep in mind:

  • In the initial function, utilizing fn.call is incorrect. Instead, opt for fn.apply, where the array provided as the second argument is treated as an array of arguments, while call interprets it as a singular argument.

  • Your subsequent function engenders a curried function that can be invoked only once, since each instance of calling curring modifies the encapsulated args array, initially established during the initiation of curry.

    Let's illustrate this further:

    1. addOne = curry(add)(1); defines addOne with its distinct args set to [1]

    2. addOne(2)(3)(4) results in 10 and alters args to [1, 2, 3, 4]

    3. addOne(2)(3)(4) (subsequent attempt) fails with addOne(...) is not a function,
      since addOne(2) attempts to execute add(1, 2, 3, 4, 2)

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

What is the alternative method of invoking a function within another function in React Native without utilizing a constructor?

Within my RegisterTaster function, I need to execute another function called endRegisterAlert. Since I'm not using a constructor and instead treating the class as a const in React Native, how can I achieve this? What is the best way to call the endRe ...

Prevent IonContent from scrolling to the bottom or top when using Ionic framework

In my Ionic app, I have a long text page with 2 buttons that trigger the actions scrollToBottom and scrollToTop. Due to the length of the page, I have set the scroll duration to be 30 seconds. I am facing two issues here: How can I stop the scrolling ...

Vue: Optimizing JSON response filtering

I am struggling with filtering a JSON response using Vue. return this.offers.filter(type => type.offers == 'Junior'); When I keep it as return this.offers, the following is displayed in my HTML: {"-MN5agCddYAdy7c8GSSz": { "comp ...

Why doesn't WebStorm display TypeScript inspection errors in real-time?

I'm currently utilizing WebStorm 2017.2.4 in conjunction with Angular 4.3 - I am facing an issue where TypeScript errors are not being displayed: https://i.sstatic.net/pcLQX.png Query How can I enable real-time inspections to occur immediately? (I ...

Is it possible to incorporate a YouTube video into a webpage without displaying any external links to YouTube above the video player?

Looking for a solution to embed a YouTube video on my webpage without the link appearing when hovering over it and without the suggested videos at the end. Just the option to replay the video without the distraction of related videos. ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...

Removing CSS from a Link in react-router-dom

My attempt to create unique divs for different pages using the code in my home.js didn't go as planned. <Link to="Subject1"> <Product title="The Lean Startup" image="https://images-na.ssl-images-amazon.co ...

Align boxes in the center within a DIV container

Here is the box design that I have created: https://i.sstatic.net/3rtcn.jpg The green color boxes are generated dynamically inside a "col-md-10" div. If there are less than 3 boxes in the second row, I would like to center align them. For example, in thi ...

Utilizing jQuery/Javascript to replicate the data from a table while excluding the header and then pasting it to the

I am attempting to replicate the data from a table while disregarding the header/title row and copying it to the clipboard in the exact same way as manual selection and copy. I came across a post on how to choose Select a complete table with Javascript (t ...

The functionality of the like button in Flask with jQuery/JSON seems to be malfunctioning

I am currently in the process of developing a small flask application and attempting to create a like button that can function without requiring a page refresh. After considering jQuery as a potential solution, I began writing some code. However, it appea ...

Automatically change a text based on its location

Currently leveraging the amazing flexible-nav to showcase the current subtopic within my post. I am also considering the possibility of extracting this current-string and showcasing it at the top of the page in my main navigation bar. This way, the text w ...

Steps for changing the language in KeyboardDatePicker material ui

Currently, I am utilizing material ui on my website and leveraging the KeyboardDatePicker API with successful results. The only issue is that the months' names and button text are displayed in English, whereas I would prefer them to be in Spanish. Des ...

The initiation of jQuery animation through user interaction hinges on the completion of the preceding animation

In my project, I've designed a timeline that offers users the ability to zoom in and out by simply clicking on corresponding buttons. Since the timeline is too large to fit entirely on the screen, it is contained within a scrollable div. To ensure tha ...

submitting a form including a file through ajax communication

For the past two weeks, I've been trying to find a solution to my unique problem. I've created a custom form that I need to upload along with one or more files. Our backend is running ruby on Rails, and the data must be formatted into a specific ...

I'm curious about the origin of this.on event handler. Is it part of a particular library or framework?

While casually perusing through the application.js file in the express source code, I stumbled upon this interesting piece of code. I'm curious about the origin of this '.on' event. Is it part of vanilla JavaScript or is it a feature provid ...

Is it possible to create floating unordered lists using Bootstrap in HTML?

Is there a way to float text left or maintain list order in the HTML code of my page while using a dense CSS from this bootstrap template? For example, I would like my list to remain organized regardless of how many items are added: https://i.sstatic.net ...

Decreased storage space requirements following transfer to S3 bucket using nodejs

I am currently facing an issue with uploading files from a specific folder location to an S3 bucket using the nodejs aws-sdk. The files I am working with are deepzoom images (.dzi). While the files seem to be successfully uploaded to my S3 bucket, I have n ...

Unable to retrieve JSON information using AJAX

Trying to retrieve data from the server without refreshing the page using AJAX. The issue is that the data appears as text rather than in JSON format. Here is my code: $.ajax({ type: "GET", url: "http://localhost:8080/search?key=" + QUERY + "", ...

If a checkbox is checked, then the value in the textbox should be multiplied by 0

I'm faced with a challenge involving a non-clickable textbox that is meant to hold a running total. Each time a checkbox is clicked, its value should be added to the total in the textbox. However, I am now struggling to figure out how to perform mult ...

The Evolution of Bulma's Navigation Menu

Creating a transparent menu in Bulma has been successful for the desktop viewport: VIEW DESKTOP MENU However, when attempting to implement the same design on mobile, the menu ends up like this: VIEW MOBILE/TABLET MENU The mobile version seems to inheri ...