Skip to content

Instantly share code, notes, and snippets.

@nhalstead
Created May 30, 2020 19:29
Show Gist options
  • Save nhalstead/7678b60b40f085887c2f699a765ba390 to your computer and use it in GitHub Desktop.
Save nhalstead/7678b60b40f085887c2f699a765ba390 to your computer and use it in GitHub Desktop.
Insert Fill
const insertFill = function (arr, index, item, fillValue = 0) {
if (arr.length === 0 && index === 0) return [item];
if (arr.length < index) {
// Index is not found, Fill in the length needed.
const missing = index - arr.length;
const fill = Array(missing - 1).fill(fillValue);
arr = arr.concat(fill);
return arr.concat([item]);
}
// The Index exists, insert at that point.
arr.splice(index, 0, item);
return arr;
}
let _ = {};
_.insertFill = function (arr, index, item, fillValue = 0) {
if (arr.length === 0 && index === 0) return [item];
if (arr.length < index) {
// Index is not found, Fill in the length needed.
const missing = index - arr.length;
const fill = Array(missing - 1).fill(fillValue);
arr = arr.concat(fill);
return arr.concat([item]);
}
// The Index exists, insert at that point.
arr.splice(index, 0, item);
return arr;
}
let months = ['Jan', 'March', 'April', 'June'];
months = _.insertFill(months, 1, 'Feb');
months = _.insertFill(months, 4, 'May');
months = _.insertFill(months, 12, 'Dec');
console.log(months);
// Array ["Jan", "Feb", "March", "April", "May", "June", 0, 0, 0, 0, 0, "Dec"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment