0

I have this code:

const obj = new plugin.process({
  extensions: [...bindings, a, b]
});

Is there anyway to make the bindings optional based on another parm?

Say I have a boolean flag

 const obj = new plugin.process({
      extensions: [...bindings && myFlag, a, b]
    });

Any ideas?

1
  • Just construct the array before the .process() call and don't squeeze everything in one fanzy line of code Commented Jan 11, 2022 at 8:32

2 Answers 2

1

You could simply construct the array before passing it into process.

First create your default array, this could be:

const extensions = [a, b]

Then add an extra condition in case your boolean is true:

if(myFlag) {
  extensions.push(...bindings)
}

Combining this together:

const extensions = [a, b]

if(myFlag) {
  extensions.push(...bindings)
}

const obj = new plugin.process({
  extensions
});

If bindings need to be added before a and b, we can write logic like this:

const extensions = []

if(myFlag) {
  extensions.push(...bindings)
}

extensions.push(a, b)

const obj = new plugin.process({
  extensions
});
Sign up to request clarification or add additional context in comments.

3 Comments

The content of bindings has to be placed before a and b
@Andreas Added some more information
@Andreas bindings will be added before a and b since you first push bindings, then a and b
0

Use this

const obj = new plugin.process({
  extensions: [
    ...bindings,
    ...(myFlag ? [a, b] : [])
  ]
});

1 Comment

This will work, but it's bad practice in general. It's not because it's compact that it's good. It's harder to read and understand what is going on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.