0
Hours
0
Minutes
0
Seconds

How to implement Array.prototype.fill? JavaScript Interview Question | Problem Solving | JavaScript Polyfills
@Devtools Tech

491

In this question, the candidate needs to implement a function customFill that mimics the behaviour of Array.prototype.fill method.

More about Array.prototype.fill

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

Examples

const array = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4
console.log(array.fill(0, 2, 4));
// expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1
console.log(array.fill(5, 1));
// expected output: Array [1, 5, 5, 5]

console.log(array.fill(6));
// expected output: Array [6, 6, 6, 6]

Syntax

fill(value)
fill(value, start)
fill(value, start, end)

Parameters

  1. value

Value to fill the array with.

Note: all elements in the array will be this exact value: if value is an object, each slot in the array will reference that object.

  1. start (Optional)

Zero-based index at which to start filling, converted to an integer.

  • Negative index counts back from the end of the array — if start < 0, start + array.length is used.
  • If start < -array.length or start is omitted, 0 is used.
  • If start >= array.length, no index is filled.
  1. end (Optional)

Zero-based index at which to end filling, converted to an integer. fill() fills up to but not including end.

  • Negative index counts back from the end of the array — if end < 0, end + array.length is used.
  • If end < -array.length, 0 is used.
  • If end >= array.length or end is omitted, array.length is used, causing all indices until the end to be filled.
  • If end is positioned before or at start after normalization, no index is filled.

Return value

The modified array, filled with value.

Submission

Start the timer, complete your solution, and test it against the test cases provided by the platform. Ideally, you should finish this question within 30 mins. Share your solution with us -- https://twitter.com/devtoolstech

Loading IDE...