Topic Description

Create a fill function that takes four parameters:

The fill function should replace the elements of the input array with the specified value from the start index to the end index, effectively filling the specified range with the given value.

console.log(fill([1, 2, 3], '*')); // ['*', '*', '*']

console.log(fill([1, 2], '*', 2, 3)); // [1, 2]

console.log(fill([1, 2, 3, 4, 5], '*', 1, -1)); // [1, '*', '*', '*', 5]

Answer


function fill(array, value, start=0, end){
	if(start < 0){
		start = array.length + start
	}
	if(end < 0){
		end = array.length + end
	}
	if(end > array.length){
		end = array.length
	}
	
	for(let i=start; i<end; i++){
		array[i]=value
	}
	return array;
}