This one stumped me for a while, and I eventually just looked at the solution online. The hint was fairly cryptic, and manipulating "De Morgan's Laws" in JS with &&, ,. || is pretty complicating still, I'm starting to grasp it. but not quite there yet. I imagine I will need a fair bit of practice and time to understand these concepts thoroughly, Anyway: here is the question for one of the exercises at the end of chapter 5:
Analogous to the some method, arrays also have an every method. This one returns true when the given function returns true for every element in the array. In a way, some is a version of the || operator that acts on arrays, and every is like the && operator.
Implement every as a function that takes an array and a predicate function as parameters. Write two versions, one using a loop and one using the some method.
function every(array, test) {
// Your code here.
}
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
I was able to get the first version using array.every; it wasn't too hard. But the solution for using the some method I still don't understand. Here's the solution to the second part of the question:
function every(array, test) {
return !array.some(element => !test(element));
}
I'm trying to work this out in my head, and thought that maybe a SO member could help me understand what's happening. Can someone talk me through this?
Thanks in advance!
Jordan
You could build a table of truth and have a look which value yields which result.
This example take the second example and shows for the first two elements an intermediate result, pretending here would stop the loop and the final result.
n < 10 !(n < 10)
value compare1 every compare2 some !some comment
--------- --------- --------- --------- --------- --------- -------------------
2 true false
4 true false
true false true intermediate result
16 false true
false true false final result
^^^^^ ^^^^^
By mentioning De Morgan's laws , a term can be expressed by changing the operator from logical AND &&
to logical OR ||
or vice versa by taking negated values and finally negate the whole expression.
a && b && c
!(!a || !b || !c)
Both expressions are equal (for boolean values).
Array#every
acts like using &&
and Array#some
like ||
.
To negate some
, take every
and vice versa. This replacement need to negate the condition inside of the callback and a negation of the the result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.