125k views
5 votes
Write a sum method which will work properly when invoked using either syntax below.

(sum(2,3)); // Outputs 5
(sum(2)(3)); // Outputs 5

User Frelling
by
8.0k points

1 Answer

4 votes

Final answer:

To write a sum method that can be invoked using either syntax, you can create a function that takes two arguments and returns their sum. Additionally, you can define a nested function that takes one argument and returns another function, which in turn takes another argument and returns their sum.

Step-by-step explanation:

To write a sum method that can be invoked using either syntax, you can create a function that takes two arguments and returns their sum. Additionally, you can define a nested function that takes one argument and returns another function, which in turn takes another argument and returns their sum. Here is an example:


function sum(a, b) {
if (typeof b === 'undefined') {
return function(c) {
return a + c;
};
}
return a + b;
}

console.log(sum(2,3)); // Outputs 5
console.log(sum(2)(3)); // Outputs 5
User Petr Macek
by
7.6k points