1

Is there any way I could write a function in order to call it in both ways like this?

I know how to write both params structures in the function but I would like to know how to validate both params structures in a single function.

functionToCall(1, 'value', true);

and

functionToCall({
    param1: 1,
    param2: 'value',
    param3: true
});

3 Answers3

0

You could check the first parameter, if it is an object and take a destruturing for the missing parameters.

This approach does not work if the first parameter is an object as a regular wanted type or if the type is any.

function functionToCall(param1, param2, param3) {
    if (param1 && typeof param1 === 'object') {
        ({ param1, param2, param3 } = param1);
    }
    console.log(param1, param2, param3);
}

functionToCall(1, 'value', true);
functionToCall({ param1: 1, param2: 'value', param3: true });
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use rest params to get an array of parameters. If the length of the args array is 1, use object destructuring. If it's not 1 use array destructuring on the args array.

const functionToCall = (...args) => {
  let param1, param2, param3;
  if (args.length === 1) ({ param1, param2, param3 } = args[0]);
  else ([param1, param2, param3] = args);
  
  console.log(param1, param2, param3);
};

functionToCall(1, 'value', true);

functionToCall({
    param1: 1,
    param2: 'value',
    param3: true
});
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You can do like this for example

const functionToCall = () => {
  val [param1, param2, param3] = arguments.length == 1 
    ? Object.entries(arguments[0]).map(v => v[1]) 
    : arguments     
}
Dmitry Reutov
  • 2,995
  • 1
  • 5
  • 20