lodashのfillメゾッドを作ってみた
const fill = (array = [], value, start = 0, end = array.length) => {
const fillArray = []
for (let i = 0; i < array.length; i++) {
if (start <= i && i < end) {
fillArray.push(value)
} else {
fillArray.push(array[i])
}
}
return fillArray
}
console.log(fill([1, 2, 3], "a"))
// => [ 'a', 'a', 'a' ]
console.log(fill(Array(3), 2))
// => [ 2, 2, 2 ]
console.log(fill([4, 6, 8, 10], "*", 1, 3))
// => [ 4, '*', '*', 10 ]
もう少し省略できた
const fill = (array = [], value, start = 0, end = array.length) => {
for (let i = 0; i < array.length; i++) {
if (start <= i && i < end) {
array[i] = value
}
return array
}