OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Currying a function that takes infinite arguments

  • Thread starter Thread starter runtimeZero
  • Start date Start date
R

runtimeZero

Guest
Using ES5, how do you curry a function that takes infinite arguments.

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

The function above takes only three arguments but we want our curried version to be able to take infinite arguments.

Hence, of all the following test cases should pass:

Code:
var test = add(1);

test(2);     //should return 3
test(2,3);   //should return 6
test(4,5,6); //should return 16

Here is the solution that I came up with:

Code:
function add(a, b, c) {
    var args = Array.prototype.slice.call(arguments);

    return function () {
        var secondArgs = Array.prototype.slice.call(arguments);
        var totalArguments = secondArgs.concat(args);

        var sum = 0;

        for (i = 0; i < totalArguments.length; i++) {
            sum += totalArguments[0];
        }

        return sum;
    }
}

However, I have been told that it's not very “functional” in style.

<p>Using ES5, how do you curry a function that takes infinite arguments.</p>

<pre class="lang-js prettyprint-override"><code>function add(a, b, c) {
return a + b + c;
}
</code></pre>

<p>The function above takes only three arguments but we want our curried version to be able to take infinite arguments.</p>

<p>Hence, of all the following test cases should pass:</p>

<pre class="lang-js prettyprint-override"><code>var test = add(1);

test(2); //should return 3
test(2,3); //should return 6
test(4,5,6); //should return 16
</code></pre>

<p>Here is the solution that I came up with:</p>

<pre class="lang-js prettyprint-override"><code>function add(a, b, c) {
var args = Array.prototype.slice.call(arguments);

return function () {
var secondArgs = Array.prototype.slice.call(arguments);
var totalArguments = secondArgs.concat(args);

var sum = 0;

for (i = 0; i < totalArguments.length; i++) {
sum += totalArguments[0];
}

return sum;
}
}
</code></pre>

<p>However, I have been told that it's not very “functional” in style.</p>
 

Latest posts

Online statistics

Members online
0
Guests online
3
Total visitors
3
Ads by Eonads
Top