You need the length property of arguments, iterate < arguments.length and return an object with the two wanted function.
While you take result as variable, it keeps the value from the former calculation. The result is in the first part 15 and later 7, instead of 2.
function calculator(firstNumber) {
function sum() {
for (let i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
function dif() {
for (let i = 0; i < arguments.length; i++) {
result -= arguments[i];
}
return result;
}
var result = firstNumber;
return { sum: sum, dif: dif };
}
var myCalculator = calculator(10);
console.log(myCalculator.sum(2, 3));
console.log(myCalculator.dif(1, 2, 5));
If you like to get always the result with firstNumber, you could initialize the result with firstNumber.
function calculator(firstNumber) {
function sum() {
var result = firstNumber;
for (let i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
function dif() {
var result = firstNumber;
for (let i = 0; i < arguments.length; i++) {
result -= arguments[i];
}
return result;
}
return { sum: sum, dif: dif };
}
var myCalculator = calculator(10);
console.log(myCalculator.sum(2, 3));
console.log(myCalculator.dif(1, 2, 5));