Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

overload the overloadedFunc() function

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading