Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created February 20, 2018 10:57
Show Gist options
  • Select an option

  • Save jonurry/15015c95c2065fea9c2b0c4b744826e9 to your computer and use it in GitHub Desktop.

Select an option

Save jonurry/15015c95c2065fea9c2b0c4b744826e9 to your computer and use it in GitHub Desktop.
5.3 Everything (Eloquent JavaScript Solutions)
// 5.3 Everything
//every using a loop
function every(array, test) {
for (let element of array) {
if (test(element) === false) {
return false;
}
}
return true;
}
console.log(every([1, 3, 5], n => n < 10));
// → true
console.log(every([2, 4, 16], n => n < 10));
// → false
console.log(every([], n => n < 10));
// → true
// every using array.some
function every(array, test) {
return array.some(test);
}
console.log(every([1, 3, 5], n => n < 10));
// → true
console.log(every([2, 4, 16], n => n < 10));
// → false
console.log(every([], n => n < 10));
// → true
@cmatschiner
Copy link

Hi Jim,

just merely applying the some() method will not work, since latter returns true when one element in the array passes the test.

To test if ALL elements pass the test with the some() method, use De Morgan’s laws, which states that
!(A && B) === !A || !B

We can modify De Morgan’s laws by using a double negation:
(A && B) === ! (!A || !B)

Here the solution:

function every(array, test) {
    return !array.some(element => !test(element));
}

@hamzachenguiti
Copy link

hamzachenguiti commented Sep 26, 2022

Hi Jim,

just merely applying the some() method will not work, since latter returns true when one element in the array passes the test.

To test if ALL elements pass the test with the some() method, use De Morgan’s laws, which states that !(A && B) === !A || !B

We can modify De Morgan’s laws by using a double negation: (A && B) === ! (!A || !B)

Here the solution:

function every(array, test) {
    return !array.some(element => !test(element));
}

I used the some method with for/of loop, but now I understand how to use some to confirm that all the items of the list passed the test with the help of De Morgan's law.
Thanks, Christoph!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment