Marco V
Marco V

Reputation: 2623

A single function that can be invoked in two ways

I'm trying to write a single function that can be invoked in two ways:

sum(3,5); //8

OR

sum(3)(5); //8

This is aparently not enough:

function sum (a,b){
  return a + b;
}

Here is where I am so far:

http://jsfiddle.net/marcusdei/a8tds42d/1/

Upvotes: 0

Views: 109

Answers (4)

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

What you need is to write a curry function. Kevin Ennis has shown in great details on how to implement one here.

https://medium.com/@kevincennis/currying-in-javascript-c66080543528

Here's the function from the above post (just in case the post goes away)

function curry( fn ) {
   var arity = fn.length;
   return (function resolver() {
      var memory = Array.prototype.slice.call( arguments );
      return function() {
        var local = memory.slice(), next;
        Array.prototype.push.apply( local, arguments );
        next = local.length >= arity ? fn : resolver;
        return next.apply( null, local );
      };
   }());
}

And a fiddle

Or you can use Ramda.js and here's to use Ramda

http://bit.ly/1IfaVM5

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45135

Just as another alternative:

function sum (a,b) { 
    if (b === undefined) { 
        return sum.bind(null, a); 
    } 
    return a + b; 
}

Using bind to curry.

Upvotes: 2

Jamiec
Jamiec

Reputation: 136104

Why aside (why would you want to do that? - ans: homework)

function sum (a,b){
    if(b === undefined)
    {
        return function summer(next){
            return a + next;
        }
    }
    return a + b;
}

Upadted fiddle: http://jsfiddle.net/a8tds42d/2/

Upvotes: 3

Johan Karlsson
Johan Karlsson

Reputation: 6476

You can do something like this:

function sum (a,b){
    if(b == undefined){
        return function(b){
            return a + b;   
        }
    } else {
      return a + b;        
    }
}

Upvotes: 5

Related Questions