DEV Community

Extending Javascript array with an event handler

I recently had to write a classifier algorithm that classified an array of items based on certain attributes. It was a pretty complicated dataset with an even more complicated set of constraints, but for the sake of this article i will keep it a simple.

Say we have the following dataset

    [
        {id:1, age:32},
        {id:2, age:4},
        {id:3, age:20},
        {id:4, age:30}
    ]
Enter fullscreen mode Exit fullscreen mode

Now, say we wish to find the oldest age and the sum of all ages. This can easily be done using a loop and some variables, but for the sake of this article I will use an event listener attached to the traditional javascript array to pull this off.

First Let's extend the array object

    const MyArray = function (){
        // this events object will be explained shortly
        this.events = {}
    }
Enter fullscreen mode Exit fullscreen mode

So, simply I just created a function and called it my array then gave it an events object(or hashtable) that will hold all our events and callbacks in this form:

    {eventName:callback_function}
Enter fullscreen mode Exit fullscreen mode

Let's continue with creating the extended array

    MyArray.prototype = []

    MyArray.prototype.on = function (event, callback){
        this.events[event] = callback
    }    

    MyArray.prototype.push = function(args){
        Array.prototype.push.call(this, args)
        const eventName = 'push'
        if(this.events[eventName]){
            this.events[eventName](args)
        }
    }

Enter fullscreen mode Exit fullscreen mode

In the snippet above we let our function inherit the properties of the array object using prototype inheritance.

The second block implements our event listener function. We call the function on, so we can do things like on('filter') etc. All this function does is take in the event (or event name) and a callback to execute once that event occurs. The function stores the event name as the key and the callback as the value in our events hashtable.

Lastly we make our own push method to put new items into our object. The next line uses the push method of the parent Array object, but by using call, we call push in the context of the current object. This works because our object has inherited from Array. That's all.

Testing our new object

So let's test this and see how it will work using the stated example data above.

const Arr = new MyArray()
let sum = 0;
let oldest = 0;
Arr.on('push', function (e){
    sum += e.age
    oldest = (e.age > oldest ? e.age:oldest)
})

for (let data of dataSet){
    Arr.push(data)
}

console.log(sum, oldest)
Enter fullscreen mode Exit fullscreen mode

And that's it.

Top comments (0)