As practice, I want to write a function all() that works similar to the Array.prototype.every() method. This function returns true only if the predicate supplied returns true for all the items in the array.
Array.prototype.all = function (p) {
this.forEach(function (elem) {
if (!p(elem))
return false;
});
return true;
};
function isGreaterThanZero (num) {
return num > 0;
}
console.log([-1, 0, 2].all(isGreaterThanZero)); // should return false because -1 and 0 are not greater than 0
Somehow this doesn't work and returns true
. What's wrong with my code? Is there a better way to write this?