How to resize an array
In terms of elegance, I would say you could trim down your original solution to:
function resize(arr, newSize, defaultValue) {
while(newSize > arr.length)
arr.push(defaultValue);
arr.length = newSize;
}
Or use prototype:
Array.prototype.resize = function(newSize, defaultValue) {
while(newSize > this.length)
this.push(defaultValue);
this.length = newSize;
}
Edit: ES2016 approach:
function resize(arr, newSize, defaultValue) {
return [ ...arr, ...Array(Math.max(newSize - arr.length, 0)).fill(defaultValue)];
}
function resize(arr, size, defval) {
while (arr.length > size) { arr.pop(); }
while (arr.length < size) { arr.push(defval); }
}
I think this would be more efficient though:
function resize(arr, size, defval) {
var delta = arr.length - size;
while (delta-- > 0) { arr.pop(); }
while (delta++ < 0) { arr.push(defval); }
}
And while not as elegant, this would probably me the most efficient:
function resize(arr, size, defval) {
var delta = arr.length - size;
if (delta > 0) {
arr.length = size;
}
else {
while (delta++ < 0) { arr.push(defval); }
}
}