function sum(x, y) {
if (arguments.length === 1) {
// Currying: Return a function that takes the second argument.
return function(y) {
return x + y;
};
} else {
// Regular addition when two arguments are provided.
return x + y;
}
}
// Examples:
console.log(sum(2)(3)); // Output: 5
console.log(sum(2, 3)); // Output: 5
// More robust version handling various input types and potential errors:
function sumRobust(x, y) {
if (arguments.length === 1) {
return function(y) {
if (typeof x !== 'number' || typeof y !== 'number') {
return NaN; // Handle non-numeric inputs
}
return x + y;
};
} else {
if (typeof x !== 'number' || typeof y !== 'number') {
return NaN; // Handle non-numeric inputs
}
return x + y;
}
}
console.log(sumRobust(2)(3)); // Output: 5
console.log(sumRobust(2, 3)); // Output: 5
console.log(sumRobust("a", 3)); // Output: NaN
console.log(sumRobust(2)("b")); // Output: NaN (using currying)
// Even more robust version using nullish coalescing operator (??) and optional chaining (?.) for undefined checks (modern JavaScript):
function sumExtraRobust(x, y) {
if (arguments.length === 1) {
return function(y) {
// Check if either x or y are not numbers after the inner function is called
return typeof x === 'number' && typeof y === 'number' ? x + y : NaN;
};
} else {
// Check if either x or y are not numbers initially
return typeof x === 'number' && typeof y === 'number' ? x + y : NaN;
}
}
console.log(sumExtraRobust(2)(3)); // Output: 5
console.log(sumExtraRobust(2, 3)); // Output: 5
console.log(sumExtraRobust("a", 3)); // Output: NaN
console.log(sumExtraRobust(2)("b")); // Output: NaN (using currying)
console.log(sumExtraRobust(2)); // Returns a function waiting for the second argument. No NaN yet!
console.log(sumExtraRobust(2)(undefined)); // Output: NaN
console.log(sumExtraRobust(undefined, 3)); // Output: NaN
This uses a technique called currying. If only one argument is provided, the sum
function returns a new function that "remembers" the first argument (x
). This inner function then waits for the second argument (y
) to be provided. When the inner function is finally called with y
, it performs the addition and returns the result. If both arguments are provided initially, it performs regular addition.
The more robust versions demonstrate handling non-numeric inputs and undefined values, making the function more resilient in a real-world application. The sumExtraRobust
example leverages modern JavaScript features for cleaner and more concise null/undefined checks. Choose the version that best suits your needs and coding style.