Easier way to call a function with many parameters?

3024 views javascript
2

for example I got the following function in Javascript/Typescript (real one is a generated REST Api from OpenApiGenerator)

doStuffAsGet(a: string, b: string; c: string; d: string, e: string, ...)

Now I would only call the function with parameter c, the rest should be undefined. Is there a way not to have to write many many undefined only to supply this one parameter?

answered question

Change your function signature to accept an option object.

You can wrap your function with another one that accepts only single parameter: const doSimpleStauff = (c: string) => doStuffAsGet(undefined, undefined, c, ...)

3 Answers

5

Optional parameters:

function doStuffAsGet(a: string, b: string, c: string, d?: string, e?: string) {

}

doStuffAsGet('a', 'b', 'c');
doStuffAsGet('a', 'b', 'c', 'd');
doStuffAsGet('a', 'b', 'c', 'd', 'e');

You can make a, b, and c required, but have the rest optional (you choose which you must have)

You can also have defaults:

function doStuffAsGet(a: string, b: string, c: string, d: string = '', e: string = '') {

}

doStuffAsGet('a', 'b', 'c');
doStuffAsGet('a', 'b', 'c', 'd');
doStuffAsGet('a', 'b', 'c', 'd', 'e');

And rest parameters...

function doStuffAsGet(a: string, ...others: string[]) {

}

doStuffAsGet('a', 'b', 'c');
doStuffAsGet('a', 'b', 'c', 'd');
doStuffAsGet('a', 'b', 'c', 'd', 'e');
doStuffAsGet('a', 'b', 'c', 'd', 'e', 'f');

Note in the above example, a is needed, so you can't call the function with zero arguments. Again, you choose what is needed and what isn't.

A combinations of these may get you what you need.

posted this
7

Rest parameters, deconstruction... All in the following example :

function doStuffAsGet(...args) {
  const [, , c] = args;

  console.log(args[2], c);
}

doStuffAsGet('a', 'b', 'c', 'd', 'e');

doStuffAsGet(void 0, void 0, 'c', void 0, void 0, void 0);

doStuffAsGet(void 0, void 0, 'c');

const args = [];

for (let i = 0; i < 2; i += 1) {
  args.push(void 0);
}

doStuffAsGet(...args, 'c');

posted this
7

I would try and use the rest and spread operators, I don't know the goal of this function so I can't help you there, but check this out

https://javascript.info/rest-parameters-spread-operator

posted this

Have an answer?

JD

Please login first before posting an answer.