Is it possible to implement JavaScript infinite currying for addition that allows for an unlimited number of function calls and an unlimited number

During a recent interview, I was given the task to create a function based on the code snippet below:

add(2,3,4)(5,6)(7,8); // Should yield 35

The code snippet above showcases a function called 'add' that can be invoked multiple times and can handle an infinite number of arguments per invocation. Ultimately, it is expected to return the total sum of all the arguments provided across all invocations.

Below is a partial solution for this problem, which requires a final invocation without any arguments.

/**
 * @description
 * infiniteAdd(2,3)(4,5)(6,7)()
 * The above operation results in 27
 */

function infiniteAdd() {
  // Creating closure for subsequent function invocations
  var prevArgs = Array.prototype.slice.call(arguments);

  return function() {
    var currArgs = Array.prototype.concat.call(prevArgs, Array.prototype.slice.call(arguments));

    if (arguments.length < 1) {
      // Calculate sum when no arguments are passed
      return Array.prototype.reduce.call(currArgs,
        function(acc, curr) {
          return acc + curr;
        }
      );
    }
    
    // Recursively call the main function until no more arguments are provided
    return infiniteAdd.apply(null, currArgs);
  }
}

console.log(infiniteAdd(2, 3)(4, 5)(6, 7)());

Answer №1

If you want to create a currying function for addition, you can follow the code snippet below:

function add(...args) {
  return args.reduce((a, b) => a + b);
}

function curryAdd(fn) {
  var newFn = fn.bind(null);

  function calculate(...args) {
    newFn = newFn.bind(null, ...args);
    return calculate;
  }

  calculate.toString = () => newFn();

  return (...arg) => {
    newFn = fn.bind(null);
    return calculate(...arg);
  }
}

var addition = curryAdd(add)

console.log(addition(2, 3, 4)(5, 6)(7, 8))

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 process for storing a block of JavaScript code within a JavaScript variable?

My objective is to assign a block or JavaScript code into a JavaScript variable so that I can display a block similar to the one shown below in my Vue template. https://i.sstatic.net/rE0UV.png It is possible to add a block of HTML code into a JavaScript v ...

Creating a targeted jQueryUI tab focus

My jQueryUI tabs have a click function defined on a specific tab which works correctly with ajax calls: $("a[href='#tabs-1ua']").click(function (event, ui) { //ajax call }); Now I want to capture not just clicks but any type of focus on thi ...

Continuously refresh the if/else statement

I'm currently facing an issue with my jQuery code regarding a responsive navigation bar. I am trying to add a class called 'mobile' to the navigation bar when it reaches close to the logo. Below is the snippet of my code: function respon ...

Is it necessary to include a back button when navigating through paginated tables?

Within my AngularJS application, I have implemented pagination on the user list page. This allows me to retrieve ten users at a time from the server, with each click loading another set of ten users on a new page. The user details are presented in a tabl ...

Disregarding any negative values while utilizing the np.log(array) function

While attempting to calculate the logarithm of a specific column in a numpy array, like this: logSFROIIdC = np.log(data_dC[:, 9]), an error is returned by the compiler: -c:13: RuntimeWarning: divide by zero encountered in log. I understand the reason for ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

Converting a curl command to a $.ajax() call in JavaScript: A step-by-step guide

I'm attempting to retrieve data from the Zomato API by using jquery ajax, however, they have provided a curl command instead. curl -X GET --header "Accept: application/json" --header "user-key: key" "https://developers.zomato.com/api/v2.1/cities" Is ...

What steps can I take to give priority to a particular ajax call?

Every 10 seconds, two ajax based methods are executed. However, when I submit the form for processing, it waits for the previous ajax calls to complete before processing. I want to prioritize the form submission. Below is the script that I am using: func ...

When using useEffect in React, the handleKeyDown function is causing the output to double with each

Whenever a user inputs something, the output doubles each time, leading to a long loop after just a few inputs. Below is the code snippet: const [direction,setDirection] = useState(Array(1).fill(0)); const directions = ["botNorth","botEa ...

Dealing with 404 errors encountered when making requests to external websites, utilizing either basic Javascript or JQuery

I have links in my application that redirect to external websites. For example, a link might look like this: <http://www.google.com'>>General Search<>. Users input the href and we dynamically create the link without any validation of it ...

Having Trouble with Your React.js Rendering?

I'm starting to learn React.js but I'm having trouble rendering it into the HTML. I can't figure out what's wrong. Any help would be greatly appreciated. Below are the HTML and JSX code: (Note: Full links to the react library are incl ...

Calculating the time difference between two dates in the format yyyy-MM-ddTHH:mm:ss.fffffff can be done by following these steps

Can someone help me figure out how to calculate the difference in days between the date and time 2021-02-23T08:31:37.1410141 (in the format yyyy-MM-ddTHH:mm:ss.fffffff) obtained from a server as a string, and the current date-time in an Angular application ...

Using JSON object as an argument in React functional component

Currently, I'm trying to assign a JSON object to a const variable. I've been successful with using vars in the past, like so: {this.props.user.map(function(user){... However, when it comes to stateless consts, I'm encountering some confusi ...

JavaScript tool package with non-JavaScript alternative

Currently in search of a reliable Javascript widget toolkit that boasts a modern UI design like Dojo, incorporates AJAX for navigation, and effects. Essential requirement is flexibility and seamless fallback to an HTML-only version for console users. Whi ...

Attempting to transfer a JSON object from a frontend Form Input to an Express backend

Apologies for bringing up what may seem like a basic issue, but I've been searching extensively (even through axios' documentation) and haven't been able to pinpoint exactly what I need to resolve this issue. I have created a simple To-Do we ...

Updating style of element in EJS following POST request in Node.js using Express

I am working on a form page that is supposed to display a Success Alert (Boostrap) once the user fills out the form and clicks the Submit button. <form class="well form-horizontal" action="/contact" method="post" id="contact_form"> ... (input fiel ...

Storing additional data from extra text boxes into your database can be achieved using AJAX or PHP. Would you

A dynamic text box has been created using Jquery/JavaScript, allowing users to click on an "Add More" button to add additional input boxes for entering data. However, a challenge arises when attempting to store this user-generated data in a database. Assi ...

Displaying various data sets from data tables created using Ajax on Highcharts

I am currently working on integrating multiple data series into Highcharts' plot. I want to retrieve the data from an ajax self-calling function, which would allow for almost real-time updates to the charts without redrawing the entire chart each time ...

Click on a thumbnail to open the gallery

I am currently working on implementing a feature that will allow a gallery to open when a thumbnail is clicked. At the moment, the code I have looks like this: <div class="row"> <div class="col-lg-12"> <h1 class="page-h ...

Generate a unique identifier and verify its presence within an array of objects

Is there a way to generate a unique identifier and add it to an object in an array, only if the id does not already exist in any other objects within the array? Within the React code snippet provided below, the "saveColor" function was intended to accompl ...