This particular challenge really had me scratching my head for a while. After struggling with it, I finally caved and resorted to looking up the solution online. The hint provided was quite cryptic, and dealing with "De Morgan's Laws" in JavaScript using &&, !, and || proved to be quite complex. While I'm starting to grasp the concept, I still have a ways to go before fully understanding it. It seems like I'll need plenty of practice and time to master these ideas completely. Here is the question from one of the exercises at the end of chapter 5:
Similar to the some method, arrays also come equipped with an every method. This function returns true only when the specified function evaluates to true for each element within the array. In essence, some behaves like the || operator for arrays, whereas every functions similarly to the && operator.
Your task is to implement the every function that takes an array and a predicate function as arguments. You are required to create two versions: one utilizing a loop and the other making use of the some method.
function every(array, test) {
// Your implementation 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 managed to successfully complete the first version by employing array.every; it wasn't too challenging. However, I'm still struggling to comprehend the solution involving the some method. Here's how the second part of the question should be tackled:
function every(array, test) {
return !array.some(element => !test(element));
}
I've been working through this in my mind, but I could really benefit from someone on Stack Overflow guiding me through the thought process. Can anybody provide some insight into what exactly is happening here?
Thanks in advance!
Jordan