Javascript function challenge add(1,2) and add(1)(2) both should return 3

1

A friend of mine challenged me to write a function that works with both of these scenarios

add(1,2)  // 3
add(1)(2) // 3

My instinct was the write an add() function that returns itself but I'm not sure I'm heading in the right direction. This failed.

function add(num1, num2){
    if (num1 && num2){
        return num1 + num2;
    } else {
        return this;
    }
}

alert(add(1)(2));

So I started reading up on functions that return other functions or return themselves.

http://davidwalsh.name/javascript-functions https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for

I am going to keep trying, but if someone out there has a slick solution, I'd love to see it!

MicFin

Posted 2015-07-09T00:54:40.233

Reputation: 113

Question was closed 2015-07-09T01:59:20.587

Welcome to PPCG! You tagged this as code-golf, meaning that the shortest possible code will win the contest. If this is your intention, you should remove the code-challenge tag. – Dennis – 2015-07-09T01:09:33.070

I have an answer here on stackoverflow

– Patrick Roberts – 2015-07-09T03:52:13.653

FYI this is called currying. – gcampbell – 2016-06-10T10:34:03.970

Answers

6

JavaScript (as asked)

This is a "correct" way to do it but hardly the golfiest way. It's unclear if you're asking for shortest code (the question looks like it will be closed soon anyway.)

function add(a, b) {
    if(typeof b === "undefined")
        return function(c) { return a + c }
    return a + b
}

Calvin's Hobbies

Posted 2015-07-09T00:54:40.233

Reputation: 84 000

Is there any reason not to just use b === undefined here? – 12Me21 – 2018-03-23T17:43:29.863

3

JavaScript ES6, 23 bytes

add=(a,b)=>b==+b?a+b:c=>a+c

If you are willing to use ES6, you can use fat-arrow functions and conditionals to write the function.

JavaScript, 55 bytes

function add(a,b){return b==+b?a+b:function(c){return a+c}}

Here's the same function in regular (current version of) JavaScript.

b? will check if b is a non-falsey value

a+b if it is, return the sum of a and b

:c=>a+c if it's not, return a function with a single argument c which returns the sum of c and a

Downgoat

Posted 2015-07-09T00:54:40.233

Reputation: 27 116

@vihan1086 Still doesn't work for add(1,-1). – Tyilo – 2015-07-09T02:07:57.567

add=(a,b)=>b==+b?a+b:c=>a+c. – jimmy23013 – 2015-07-09T02:13:47.223

@Tyilo didn't consider that as a valid input, fixed – Downgoat – 2015-07-09T03:40:10.687