`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.
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).
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:
Count is an accumulator tuple whose length represents the current index in the arrayFlag is a boolean that starts as true when Count['length'] equals Start, indicating we are in the fill rangeFlag is true and the current index has not yet reached End, the current element is replaced with NFlag is true but the current index equals End, we stop filling and keep the original element, setting Flag to falseFlag is false, we keep the original element untouchedThis 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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount