I'm not understanding why this doesn't work
function every(arr, callback) {
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i]) === true) {
return true
}else return false
}
}
can someone help me understand how the every() method works. I need to write the source code itself for the method in relation to the following 2 questions.
describe('every', function () {
it('returns true when the callback returns true for all elements', function () {
const original = ['ace', 'cat', 'dog', 'pit']
const result = every(original, (el) => el.length === 3)
expect(result).to.be.true
})
it("returns false when the callback doesn't return true for all elements", function () {
const original = ['ace', 'cat', 'parrot', 'dog']
const result = every(original, (el) => el.length === 3)
expect(result).to.be.false
})
})
You're only testing the first element of the array, because you return either true or false inside the loop.
You should return false immediately if the test fails. Otherwise, you need to keep looping. If you get through the entire loop, then you can return true.
function every(arr, callback) {
for (let i = 0; i < arr.length; i++) {
if (!callback(arr[i])) {
return false;
}
}
return true;
}