Reputation: 47
I need to overload a function overloadedFunc() which takes 3 arguments. For the 1st argument of the function set the default value [1, 2, 3], for the 2nd - the value 2, for the 3rd - the function that returns the product of the first two arguments, and the function can multiply both arrays and numbers. The overloadedFunc() function returns the result of the default function. I have a code but it throws an error. How can I solve this problem?
function overloadedFunc(arg1 = [1, 2, 3], arg2 = 2, arg3 = multiply()) {
const res = multiply(arg1, arg2);
return res;
}
function multiply(arg1, arg2) {
arg1.forEach((item) => {
item * arg2;
});
}
console.log(overloadedFunc()); // [2, 4, 6]
console.log(overloadedFunc([2, 4, 6], 3)); // [6, 12, 18]
console.log(overloadedFunc(10)); // 20
Upvotes: 0
Views: 49
Reputation: 48600
In overloadedFunc
, you need to take multiply
as a default (do not invoke the function); and you need to call arg3
.
You can simplify the multiply
function to return a mapping.
const multiply = (arr, n) =>
Array.isArray(arr)
? arr.map(x => x * n)
: arr * n;
const overloadedFunc = (
arg1 = [1, 2, 3],
arg2 = 2,
arg3 = multiply
) =>
arg3(arg1, arg2);
console.log(overloadedFunc()); // [2, 4, 6]
console.log(overloadedFunc([2, 4, 6], 3)); // [6, 12, 18]
console.log(overloadedFunc(10)); // 20
.as-console-wrapper { top: 0; max-height: 100% !important; }
This can be re-written to simplify the arg3
(aka multiply
) callback.
const multiply = (scalar, multiplier) => scalar * multiplier;
const overloadedFunc = (
arg1 = [1, 2, 3],
arg2 = 2,
arg3 = multiply
) =>
Array.isArray(arg1)
? arg1.map(x => arg3(x, arg2))
: arg3(arg1, arg2);
console.log(overloadedFunc()); // [2, 4, 6]
console.log(overloadedFunc([2, 4, 6], 3)); // [6, 12, 18]
console.log(overloadedFunc(10)); // 20
.as-console-wrapper { top: 0; max-height: 100% !important; }
Upvotes: 1
Reputation: 376
look at the 3rd parameter, you are calling the function multiply()
without any parameters, if you wanna send the reference use multiply
The code will be like this:
// fixing the 3rd parameter
function overloadedFunc(arg1 = [1, 2, 3], arg2 = 2, arg3 = multiply) {
const res = multiply(arg1, arg2);
return res;
}
// return the result in multiply function
function multiply(arg1, arg2) {
arg1.forEach((item) => {
item * arg2;
});
return arg1;
}
// fix the 3rd call to use [10] in array instead of 10 as a number
console.log(overloadedFunc()); // [2, 4, 6]
console.log(overloadedFunc([2, 4, 6], 3)); // [6, 12, 18]
console.log(overloadedFunc([10])); // [20]
Upvotes: 0