Skip to content

Instantly share code, notes, and snippets.

@MikeDigitize
Last active April 28, 2017 21:07
Show Gist options
  • Save MikeDigitize/a9e3027f14c9b4b88d390761a982ee5d to your computer and use it in GitHub Desktop.
Save MikeDigitize/a9e3027f14c9b4b88d390761a982ee5d to your computer and use it in GitHub Desktop.
/* Array.prototype.fill
Can only modify an array that has a length of at least 1
It changes ALL the values of an array to a single value.
Make a betterFill method that fills an empty array
And takes a first argument which is the length of the array
And a second which is the values to insert
The second should be either a single value or an array of values
*/
Array.prototype.betterFill = function(length = 1, values = 0) {
let arr = this;
let content = values instanceof Array ? values : [values];
for(let i = 0; i < length; i++) {
for(let j = 0; j < content.length; j++) {
arr.push(content[j]);
}
}
arr.length = length;
return arr;
};
console.log([].betterFill(12, [1,2,3,4,5])); // [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment