Expanding on James solution:
Array.prototype.resize = function(newSize, defaultValue) {
while(newSize > this.length)
this.push(defaultValue);
this.length = newSize;
}
If you want to get even more efficient, you could do browser detection for Array.prototype.fill
and use that instead of the while loop.
if (Array.prototype.fill) {
Array.prototype.resize = function (size, defaultValue) {
var len = this.length;
this.length = size;
if (this.length - len > 0)
this.fill(defaultValue, len);
};
} else {
Array.prototype.resize = function (size, defaultValue) {
while (size > this.length)
this.push(defaultValue);
this.length = size;
};
}
If someone has included a polyfill for Array.prototype.fill
, then you want them to use your non-fill version instead. A polyfill would cause the fill method to be slower than the non-fill version.
This StackOverflow Q&A deals with how to detect if a function is natively implemented. You could work that into the initial condition, but that is just additional speed lost.
I'd probably only use this solution if you could ensure that no Array.prototype.fill
would exist.