Created
May 30, 2020 19:29
-
-
Save nhalstead/7678b60b40f085887c2f699a765ba390 to your computer and use it in GitHub Desktop.
Insert Fill
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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