Extend The Array
by Andrew Corliss
JavaScript
Array.prototype.square = function() {
// make copy of an array
var arrCopy = this.map(function(num) {
return num * num;
});
return arrCopy;
}
Array.prototype.cube = function() {
var arrCopy = this.map(function(num) {
return num * num * num;
});
return arrCopy;
}
Array.prototype.average = function() {
if (this.length <= 0) {
return NaN;
} else {
var reduced = (this.reduce(function(previous, current, index, array) {
return previous + current;
}) / this.length);
return reduced;
}
}
Array.prototype.sum = function() {
return this.reduce(function(previous, current) { return previous + current; });
}
Array.prototype.even = function() {
var arrCopy = this.filter(function(num) { return num % 2 === 0 });
return arrCopy;
}
Array.prototype.odd = function() {
var arrCopy = this.filter(function(num) { if (num % 2 !== 0) { return num; } });
return arrCopy;
}
var numbers = [1, 2, 3, 4, 5];
numbers.square();
numbers.cube();
numbers.average();