If we have an instance of and array, since we know it’s an object, adding new properties to it is pretty straightforward.
This however, only adds our new function to this instance. To add all functions just one time and have them work on all arrays is not much more complicated, we just have to attach them to Array’s prototype instead.
With such a declaration, we gain access to the context of the calling instance via this. We can then easily access indexes and other existing properties. Don’t forget we don’t want to modify the exiting array, but to create a new one.
Note these functions do not have any error checking – if n is negative or outside the bounds of the array, and exception will be thrown, so take care when using them, or add your own validation. The last two functions require a little bit of arithmetic to be performed.
Here is my solution:
(function () {
Array.prototype.last = function () {
return this[this.length - 1];
};
Array.prototype.skip = function (n) {
let result = [];
for (let i = n; i < this.length; i++) {
result.push(this[i]);
}
return result;
};
Array.prototype.take = function (n) {
let result = [];
for (let i = 0; i < n; i++) {
result.push(this[i]);
}
return result;
};
Array.prototype.sum = function () {
let result = 0;
for (let i = 0; i < this.length; i++) {
result += this[i];
}
return result;
};
Array.prototype.average = function () {
let sum = this.sum();
return sum / this.length;
};
}());