The https://www.sweetjs.org library allows to transform JavaScript code. I wonder if it would be possible to use it to extend native objects like Array, Object, String etc. in a safe way, without attaching anything to their prototype.
It seems like sweet.js should be able to transform this JS code
{ a: 1 }.isEmpty()
Into
Extensions.isEmpty({ a: 1 })
And the implementation could be
Extensions.isEmpty = (o) => {
if ('isEmpty' in o) return o.isEmpty()
for (const k in o) if (o.hasOwnProperty(k)) return false
return true
}
But I'm not sure what code should I write in Sweet.JS to make that work?
P.S.
And with TypeScript it should work even better. We can trick TypeScript into thinking that our objects are extended by giving it false declaration below, and then after TypeScript compilation apply Sweet.JS compilation.
declare global {
interface Object {
isEmpty(): boolean
}
}
So we get all the correct typings for extensions, and our native objects would stay perfectly clean.