I am currently working on a TypeScript API, which requires some additional features binding to the Object prototype (Object.prototype).
Consider the following code:<
I have extended the Array the same way and faced a big problem when s a party was using for i in ...
to loop over it. Now you can't control every third party code and these bugs could get really annoying so I suggest a better aprocach:
interface Array {
crandom(): T;
}
/** Retrieve a random element from the list */
Object.defineProperty(Array.prototype, 'crandom', { value: function() {
let index = Math.floor(Math.random() * this.length);
return this[index];
}
});
Now by using Object.defineProperty
your new property won't be enumerated over and it is safe. The above code pretty much gives a random element from the array. I made another one too which pops a random element from array:
Object.defineProperty(Array.prototype, 'popRandom', { value: function() {
let index = Math.floor(Math.random() * this.length);
let result = this[index];
this.splice(index, 1);
return result;
}
});
with Object.defineProperty
You get more control over this creation and you can add additional restrictions too.