First: If you're going to add properties to Array.prototype
, don't add them via simple assignment. Doing so creates enumerable properties, and code that relies on arrays not having any enumerable properties by default will break.
So use defineProperty
instead:
Object.defineProperty(Array.prototype, "uniq", {
value: function uniq() {
return Array.from(new Set(this));
}
});
To your questions:
Will it work if I just put it in server.js
which is run when I type npm start
?
I'm not sure what server.js
you're talking about, but if you're talking about modifying files that are built-in parts of Node or npm
rather than parts of your project, I strongly recommend not doing so.
It would be great if it also works on the client. Is it possible or should I consider server and client strictly separated from one another?
They're completely separate. If you want to do this on the client, you'll need to include script adding uniq
on the client.
Is it bad practice to extend Array.prototype
like this? I just think it seems stupid to write the code many times.
There are two camps of thought on that:
Yes, it's bad. You're likely to run into naming conflicts with someone else adding their own, different uniq
. Combining code from multiple sources is getting very, very common, increasing the odds of those problems. Future versions of the language may add uniq
. Since the committee steering the language (TC-39) tries to steer around potential conflicts, if your client-side library became popular, it would make their work harder. (MooTools has, more than once.)
No, it's not bad, it's what prototypes are for. Naming conflicts can be handled if and when. TC-39 can lump it.
You'll have to make your own decision about whether to do it.