Adding a new method to Ember.Array

Is there a way I can somewhere in my code add a new method to the array prototype so that I can access that new method anywhere else in my code?

I have a function I created in one of my components that uses array.reduce to count the number of occurrences of objects in an array and then returns a new array with the quantities matching up to id’s of those objects.

It would be really nice if I could just add this as a method to the array prototype for instance, and then anywhere else in my code, even if I didn’t define the prototype there, could then just call something like let occurrences = arrayInstance.count and I wouldn’t have to import the function I’m using everywhere I wanted to use it. It’s not a huge overhead but I like the cleanliness of just adding it as a method and keeping imports clean.

Is this something that’s possible? (specifically doing it in one place and having that work across the whole app)

2 Likes

If you really wanted to do this, you could probably create an initializer and add to the array prototype there as this code will execute before any of your app code executes.

I think, however, that the community-at-large has moved away from adding to the default prototypes a bit in recent years (Ember itself does this; but I think there’s a good reason there). And because of that, if your code was handed to another developer, there probably isn’t a clear place for her/him to find where that code is in case they needed to fix or update it. There’s also nothing that prevents some other bit of code from overriding your count in the array prototype…and if that happens, it could be really hard to track down how.

So while it may seem convenient in the shorter term, I think that longer term it might be adding a bit of technical debt.

If you look to other libraries that extend array functionality (Lodash, Underscore, D3 Array, etc), they all take a more functional approach, rather than adding to the prototype, for this very reason.

Short of it: I’d recommend importing a method in all the places that you want to use this count. A little extra code, but easier to manage in the longer-term.

2 Likes