Check exactly one boolean option set

后端 未结 6 516
后悔当初
后悔当初 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 18:57

    You mentioned in your comment that this is coming from a commander options object.

    You can do this more elegantly using Lodash:

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

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

    .pick('a', 'b', 'c')
    

提交回复
热议问题