[Easy] fill

March 4, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

Question Prompt

Implement a function fill(array, value, [start=0], [end=array.length]) that takes an array, a value to fill it with, and optional start and end indices. The function should fill the array with the given value from the start index (inclusive) up to, but not including, the end index.

If start is not provided, it should default to 0. If end is not provided, it should fill the entire array.

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

Solutions

This question seems to be easy, but there are edge cases to consider. For example, if start is negative, or if it’s out of bound. Same for the end. We can do some operation to ensure they are within bounds.

First for start

  • If start is less than 0, it's adjusted to a positive index by adding the array length. This allows you to start filling from the end of the array by providing a negative offset.

Then, we handle the end in the same way

  • If end is less than 0, it's also treated as an offset from the end and adjusted to a valid positive index.
  • If end is larger than the array.length, we keep it as the array.length

After the adjustment, we then loop through the designated section of the array, and replace each element with the value:

function fill(array, value, start = 0, end = array.length) {
  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;
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee