Edit
If you want to log every time, you could try adding another control variable. You would need the current result and the final result. This would not short-circuit and it would check every value within the array. I would not recommend doing this, so consider what I originally responded with below.
function every(array, predicat) {
let finalVal = true, currentVal;
for (let elt of array) {
currentVal = predicat(elt);
console.log(elt, currentVal);
if (finalVal && !currentVal) {
finalVal = false;
}
}
return finalVal;
}
every([1, 2, 3, 4, 5], n => n > 0)
Original response
You should be short-circuiting if the predicate fails at any point since you are checking every. There is no point to storing the result, you should just return.
function every(array, predicat) {
for (let elt of array) {
if (!predicat(elt)) {
return false; // short-circuit
}
}
return true;
}
console.log(every([1, 2, 3, 4, 5], n => n > 0));
Here is a version of some
, that checks for a truth and then breaks out. You just flip the condition and the return values.
function some(array, predicat) {
for (let elt of array) {
if (predicat(elt)) {
return true; // short-circuit
}
}
return false;
}
console.log(some([1, 2, 3, 4, 5], n => n > 0));
CLICK HERE to find out more related problems solutions.