Write a function that returns true
or false
if exactly one of its parameter is true
.
const a = true;
const b = false;
const c = false;
...
onlyOne(a, b, b); // true
onlyOne(a, b, b, b); // true
onlyOne(b, b, c, c); // false
onlyOne(a, b, b, c); //false
onlyOne(a, a, b); // false
const onlyOne() => {
let sum = 0;
arguments.forEach((argument) => {
if (argument) {
sum += Number(!!argument);
}
});
return sum === 1;
}
Similarly, we can extend implementations for onlyTwo
and onlyFive
etc by changing the last return check, i.e. sum === n
;