#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.

type exp = Fill<[1, 2, 3], 0> // expected to be [0, 0, 0]

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).

Loading...

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

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount