sampath Neeru
sampath Neeru

Reputation: 21

how to write a single function named `add`. Such that once it has received 2 arguments, it returns the sum of the 2 values

How to write a single function named add. Such that once it has received 2 arguments, it returns the sum of the 2 values. Assume all values are numbers.:

for example // add(1, 2) = 3

// add(1)(2) = 3

// add()(1)()(2) = 3

// add()(1)(2) = 3

Upvotes: 1

Views: 221

Answers (5)

Bergi
Bergi

Reputation: 664936

I tried

function calcSum(a,b){ var ab = function (b) { return a+b; } if(typeof a == 'undefined'){ return ab; } if(typeof b == 'undefined'){ return ab; } else { return ab(b); } }

This doesn't look too bad - it's working for calcSum(1,2) and calcSum(1)(2). However, you're not correctly treating the cases where nothing (or undefined) is passed:

  • calcSum() should return a function that still expects two arguments
  • calcSum(1)() = ab() should return a function that still expects one argument

You already matched the first case, but you returned ab (which takes only one value) instead of calcSum (the function that would take two values). To fix this, use

function calcSum(a,b){
    var ab = function(b) {
        if (typeof b == 'undefined') return ab;
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        else return a+b;
    }
    if (typeof a == 'undefined') return calcSum;
//                                      ^^^^^^^^
    if (typeof b == 'undefined') return ab; // actually you don't need this, ab(b) already handles this case as well now
    else return ab(b);
}

Upvotes: 1

6502
6502

Reputation: 114559

let add = (...a)=>a.length==2 ? a[0]+a[1] : (...b)=>add(...a.concat(b));

The idea is simple... we declare a variadic function and if we got two elements then we're done (and return the sum) otherwise we return a new variadic function that will collect more elements and call the function itself recursively passing what got already a concatenated with the new elements b.

Upvotes: 0

Henny Mugge
Henny Mugge

Reputation: 45

const add = (...toAddArr) => {
    let result = 0;
    for (let toAddNr of toAddArr) {
        result += toAddNr;
    }
    return result;
}

console.log(add(1, 2, 3, 4, 5));

This example uses the rest operator to get unlimited arguments and pass it as an array and the for/of loop to iterate over it.

Upvotes: 0

mub
mub

Reputation: 141

What do you think about this suggestion:

function add(){
  return Array.from(arguments).reduce((accumulator, currentValue) => accumulator + currentValue)
}

// you can also add as many argument you want.
const b = add(1,2,3,4); // 10

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138427

Too easy:

 const curry = (fn, ...previous) => (...args) => args.length + previous.length >= fn.length ? fn(...previous, ...args) : curry(fn, ...previous, ...args);

 const add = curry((a, b) => a + b);

Upvotes: 1

Related Questions