Check exactly one boolean option set

后端 未结 6 522
后悔当初
后悔当初 2021-01-17 18:21

Well, this is kind of hacky:

function b2n(boo) {
    return boo ? 1 : 0;
}

if(b2n(opt1) + b2n(opt2) + b2n(opt3) !== 1) {
    throw new Error(\"Exactly one o         


        
6条回答
  •  花落未央
    2021-01-17 19:07

    I think you are being too clever, what's wrong with:

    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 the clever game too:

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

提交回复
热议问题