Check exactly one boolean option set

后端 未结 6 523
后悔当初
后悔当初 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:15

    @spudly is on the right track, but it could 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 ES5's filter method for more information.

提交回复
热议问题