Check only one set of boolean parameters

Well, these are hackies:

function b2n(boo) { return boo ? 1 : 0; } if(b2n(opt1) + b2n(opt2) + b2n(opt3) !== 1) { throw new Error("Exactly one option must be set"); } 

Is there a better way to do this in Javascript? Using any of

  • more intelligent logical / numerical control
  • hidden array or functional operations

And so on. Support for Javascript and Node.

In my real problem, the options come from the Node module commander, so I am not dealing with true logical, just true and false things. Maybe a solution commander.

+6
source share
6 answers

Assuming you have a set of options, you can do:

 if(opts.filter(Boolean).length !== 1) {} 

It seems to me that you should have one variable with three possible states ...

 var opt = 'a'; // (or 'b', or 'c') 
+8
source

You can do it:

 if ( !!opt1 + !!opt2 + !!opt3 !== 1 ) { 

It works because

  • !! makes a boolean value from any value ( true if objects are evaluated as true in if(value) )
  • when adding booleans you get 1 for true and 0 for false .
+6
source

I think you are too smart, which is not so:

 var optionsSelected = 0; if( opt1 ) optionsSelected++; if( opt2 ) optionsSelected++; if( opt3 ) optionsSelected++; if( optionsSelected !== 1 ) { throw new Error("Exactly one option must be set"); } 

Of course, I can play a smart game too:

  if( opts.filter(Boolean).length !== 1 ) { throw new Error("Exactly one option must be set"); } 
+1
source

You mentioned in your comment that this comes from the commander's parameter object.

You can do this more elegantly using Lodash :

 if (_(options).values().compact().size() === 1) 

If you only want to count a subset of options, you can insert

 .pick('a', 'b', 'c') 
+1
source
 if ([opt1, opt2, opt3].reduce(function(x, y) { return x + !!y }, 0) == 1) { // exactly one }; 

ECMAScript 5 reduce .

+1
source

@spudly is on the right track, but it might be a little more compact:

 if( [opt1,opt2,opt3].filter(function(x){return x}).length!==1 ) { throw new Error("Exactly one option must be set"); } 

See the ES5 filter method for details .

0
source

Source: https://habr.com/ru/post/948089/


All Articles