#4518Medium

Fill

`Fill`, a common JavaScript function, now let us implement it with types. Learn tuple manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement the type-level version of JavaScript's Array.prototype.fill. Given a tuple T, a fill value N, and optional Start and End indices, you need to produce a new tuple where elements between Start and End are replaced with N.

Challenge Instructions: Fill

Medium

Fill, a common JavaScript function, now let us implement it with types. Fill<T, N, Start?, End?>, as you can see,Fill accepts four types of parameters, of which T and N are required parameters, and Start and End are optional parameters. The requirements for these parameters are: T must be a tuple, N can be any type of value, Start and End must be integers greater than or equal to 0.

[object Object]

In order to simulate the real function, the test may contain some boundary conditions, I hope you can enjoy it :)

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<Fill<[], 0>, []>>,
  Expect<Equal<Fill<[], 0, 0, 3>, []>>,
  Expect<Equal<Fill<[1, 2, 3], 0, 0, 0>, [1, 2, 3]>>,
  Expect<Equal<Fill<[1, 2, 3], 0, 2, 2>, [1, 2, 3]>>,
  Expect<Equal<Fill<[1, 2, 3], 0>, [0, 0, 0]>>,
  Expect<Equal<Fill<[1, 2, 3], true>, [true, true, true]>>,
  Expect<Equal<Fill<[1, 2, 3], true, 0, 1>, [true, 2, 3]>>,
  Expect<Equal<Fill<[1, 2, 3], true, 1, 3>, [1, true, true]>>,
  Expect<Equal<Fill<[1, 2, 3], true, 10, 0>, [1, 2, 3]>>,
  Expect<Equal<Fill<[1, 2, 3], true, 10, 20>, [1, 2, 3]>>,
  Expect<Equal<Fill<[1, 2, 3], true, 0, 10>, [true, tru

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

The key insight is to use a counter tuple to track the current index and a flag to determine whether we are within the fill range. We toggle the flag on when the counter reaches Start and off when it reaches End.

type Fill<
  T extends unknown[],
  N,
  Start extends number = 0,
  End extends number = T['length'],
  Count extends any[] = [],
  Flag extends boolean = Count['length'] extends Start ? true : false
> = T extends [infer First, ...infer Rest]
  ? Flag extends true
    ? Count['length'] extends End
      ? [First, ...Fill<Rest, N, Start, End, [...Count, 1], false>]
      : [N, ...Fill<Rest, N, Start, End, [...Count, 1], true>]
    : [First, ...Fill<Rest, N, Start, End, [...Count, 1], false>]
  : []

How it works:

This challenge helps you understand tuple manipulation with index tracking and how to apply this concept in real-world scenarios.

This challenge is originally from here.

Share this challenge