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
everyis the same as a negatedsomewith a negated condition. Reason through it verbally: if x is true for every item y, that just means that there is not some item y where x is false. Easy to see the relationship with a concrete example: "Every sparrow is a bird" --> "There is not some sparrow which is not a bird". Another way: "Every item passes my test" --> "There is not some item which fails my test". And so on...