settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Array extension (task with JavaScript object composition)

+2 votes

Extend the build-in Array object with additional functionality. Implement the following functionality:

  • last() – returns the last element of the array
  • skip(n) – returns a new array which includes all original elements, except the first n elements; n is a Number parameter
  • take(n) – returns a new array containing the first n elements from the original array; n is a Number parameter
  • sum() – returns a sum of all array elements
  • average() – returns the average of all array elements

Input / Output:
Input for functions that expect it will be passed as valid parameters. Output from functions should be their return value.

Structure your code as an IIFE.

asked in JavaScript category by user hues

1 Answer

+1 vote

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;
    };
}());

 

answered by user ak47seo
...