Reputation: 1902
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?
Upvotes: 0
Views: 1031
Reputation: 1902
You can only stop a forEach()
loop by throwing an exception. Just use a normal for
loop instead.
Array.prototype.all = function (p) {
for(var i = 0; i < this.length; i++) {
if(!p(this[i])) {
return false;
}
}
return true;
};
If any method other than Array.prototype.every()
is allowed to be used, then you can:
Array.prototype.all = function (p) {
return this.filter(p).length == this.length;
};
Upvotes: 0
Reputation: 191976
You can't break out of an Array#forEach loop by returning. Use a for loop instead.
Note: This is a partial implementation of Array#every to demonstrate the return issue.
Array.prototype.all = function (p) {
for(var i = 0; i < this.length; i++) {
if(!p(this[i])) {
return false;
}
}
return true;
};
function isGreaterThanZero (num) {
return num > 0;
}
console.log([-1, 0, 2].all(isGreaterThanZero));
Upvotes: 2
Reputation: 789
The other answers are slightly wrong. The callback you pass in should be called with 3 arguments: the current item, the index, and the entire array. This is how the native Array.every
, and indeed most native array functions, work. Your callback can choose to use these arguments but most of the time it doesn't.
Array.prototype.all = function (p) {
for(var i = 0; i < this.length; i++) {
if (!p(this[i], i, this)) {
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
Upvotes: 0
Reputation: 646
return in foreach function is not returning value from your function. You can code like this.
Array.prototype.all = function (p) {
for(var i = 0; i < this.length; i++){
if (!p(this[i]))
return false;
}
return true;
};
function isGreaterThanZero (num) {
return num > 0;
}
var result = [2, 3, 4].all(isGreaterThanZero);
console.log("result", result);
Upvotes: 0