0

for of loop isn't "looping".

function containsOnlyBooleans(array){ for(i of array) { if (typeof i === "boolean" && typeof i !== "string" && typeof i !== "number"){ return true; } } return false; } actual = containsOnlyBooleans([true, false, true, false, 5]); expected = true; if (actual === expected) { console.log("Test PASSED."); } else { console.error("Test FAILED. Keep trying!"); console.group("Result:"); console.log(" actual:", actual); console.log("expected:", expected); console.groupEnd(); } actual = containsOnlyBooleans([true, true, true, "not a boolean"]); expected = false; if (actual === expected) { console.log("Test PASSED."); } else { console.error("Test FAILED. Keep trying!"); console.group("Result:"); console.log(" actual:", actual); console.log("expected:", expected); console.groupEnd(); }

19th Apr 2021, 8:36 PM
tristach605
tristach605 - avatar
3 Answers
+ 3
This seem to work function containsOnlyBooleans( array ) { const booleanAlike = [ "boolean", "number" ]; for( i of array ) { if ( !booleanAlike.includes( typeof i ) ) { return false; } } return true; }
19th Apr 2021, 9:47 PM
Ipang
+ 3
Same here CamelBeatsSnake, I was at first confused at the condition inside the for...of loop, and wasn't sure what is actually expected. I just then decided to change it a bit to follow the function's name, which I'm guessing was supposed to return `true` when all elements of <array> was "boolean alike" (made that one up though). The thing with JS is, how it evaluate things as boolean in funny way. I've seen someone here wrote a code explaining how odd it can come about doing just that (evaluating things as boolean). Actually, I'm not all too sure how JS actually evaluates things as boolean,.
20th Apr 2021, 1:21 AM
Ipang
+ 2
tristach605 Here's my ES6 version which uses the every() function. This can be done with some(). It'll be a tiny bit more difficult to read in this case but it'll perform better with big datasets. Ipang I thought about something similar but I wasn't sure if the OP wanted only booleans because of the original logic (!== "number") but I don't know if that was a mistake by him. const containsOnlyBooleans = values => values.every(val => typeof val === "boolean") // test cases console.log("true expected, actual is: ", containsOnlyBooleans([true, false, true])) console.log("false expected, actual is: ", containsOnlyBooleans([true, "not a boolean"])) Anyway, it can be modified easily to include numbers too.
19th Apr 2021, 10:09 PM
CamelBeatsSnake
CamelBeatsSnake - avatar