FillLoading saved progress…

Fill

Implement fill(array, value, [start=0], [end=array.length]) — overwrite a stretch of an array with a single value. It mirrors Array.prototype.fill and Lodash's _.fill: every slot from start up to — but not including — end becomes value. The function changes the array in place and returns that same array, so the caller can keep using their original reference.

Signature

// array: T[]          — the array to overwrite (mutated in place).
// value: V            — the value written into every slot in range.
// start: number = 0   — first index to fill (inclusive). Negative counts from the end.
// end:   number = array.length — stop BEFORE this index (exclusive). Negative counts from the end.
// returns: the SAME array reference, now mutated.
function fill<T, V>(array: (T | V)[], value: V, start?: number, end?: number): (T | V)[];

Examples

// No start/end: the whole array becomes 'a'.
fill([1, 2, 3], 'a');
// → ['a', 'a', 'a']

// A middle range — end (3) is exclusive, so index 3 is untouched.
fill([4, 6, 8, 10], '*', 1, 3);
// → [4, '*', '*', 10]
// A negative start counts back from the end: -2 means "start two from the end".
fill([1, 2, 3, 4], 0, -2);
// → [1, 2, 0, 0]

Notes

  • end is exclusive. The filled range is [start, end) — index end itself is never written, exactly like slice.
  • Negative indices count from the end. -1 is the last index, -2 the one before it. Normalize by adding array.length.
  • Out-of-range indices clamp. A start/end past the array's bounds is pulled back to 0 or array.length; nothing is written outside the array.
  • start >= end writes nothing. After normalization, an empty or backwards range is a no-op — the array is returned unchanged.
  • Mutate in place, return the same reference. Don't build a new array. The returned value must be the very array that was passed in (fill(a, x) === a).
  • value is not copied. Filling with an object puts that same object reference in every slot.
Loading editor…