Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
All, None & Any - Functional Programming
1/10/2016
Description:
As a part of this Kata, you need to create three functions that one needs to be able to call upon an array:
1.all
This function returns true only if the predicate supplied returns true for all the items in the array
[1, 2, 3].all(isGreaterThanZero) => true
[-1, 0, 2].all(isGreaterThanZero) => false
2.none
This function returns true only if the predicate supplied returns false for all the items in the array
[-1, 2, 3].none(isLessThanZero) => false
[-1, -2, -3].none(isGreaterThanZero) => true
3.any
This function returns true if at least one of the items in the array returns true for the predicate supplied
[-1, 2, 3].any(isGreaterThanZero) => true
[-1, -2, -3].any(isGreaterThanZero) => false
// p is the callbacks function here.
// function isGreaterThanZero(num) {
return num > 0
}
My Solution:
Array.prototype.all = function (p) {
for (var i=0; i<this.length; i++) {
if (!p(this[i]))
return false;
}
return true;
};
Array.prototype.none = function (p) {
for (var i=0; i<this.length; i++) {
if (p(this[i]))
return false;
}
return true;
};
Array.prototype.any = function (p) {
for (var i=0; i<this.length; i++) {
if (p(this[i]))
return true;
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.