AND multiple parameters
Use Array.prototype.every
on all the passed arguments to check if they all are true;
function andMultipleExpr(...a) {
if(a.length === 0) return false; // return false when no argument being passed
return a.every(Boolean);
}
console.log(andMultipleExpr(true, true, false)); // should return false
console.log(andMultipleExpr(true, true, true)); // should return true
Early returns should make the code both more efficient and shorter:
function andMultipleExpr() {
for (let i = 0; i < arguments.length; i++) {
if (!arguments[i]) {
return false;
}
}
return true;
}
You need to
Start out with
logicalAnd
set totrue
Use
logicalAnd
when updating it, rather than using two entries fromarguments
The minimal change is:
function andMultipleExpr(){
let logicalAnd = true; // ***
let i;
for (i = 0; i < arguments.length; i++){
logicalAnd = logicalAnd && arguments[i]; // ***
}
return logicalAnd;
}
console.log(andMultipleExpr(true, true, false, false));
But mbojko's solution has the advantage of short-circuiting (stopping the loop when it first finds a falsy value), which seems like a good idea.
Since you're using ES2015+, you should probably use a rest parameter rather than arguments
, and you can use a for-of
loop:
function andMultipleExpr(...flags) {
let logicalAnd = true;
for (const flag of flags) {
logicalAnd = logicalAnd && flag;
}
return logicalAnd;
}
console.log(andMultipleExpr(true, true, false, false));
You can also short-circuit that in keeping with mbojko's approach
function andMultipleExpr(...flags) {
for (const flag of flags) {
if (!flag) {
return false;
}
}
return true;
}
console.log(andMultipleExpr(true, true, false, false));
Some people might throw reduce
at this, but Archie's every
solution is much better. (But since your comparison isn't strict, I'd just make it .every(flag => flag)
.)