Skip to content

Commit

Permalink
[style]: en/medium-checkrepeatedtuple.md
Browse files Browse the repository at this point in the history
  • Loading branch information
ghaiklor committed Aug 9, 2023
1 parent 498b679 commit 56ddd0d
Showing 1 changed file with 19 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,46 @@ tags: array

## Challenge

Implement type `CheckRepeatedChars<T>` which will return whether type `T` contains a duplicated member.
Implement type `CheckRepeatedChars<T>` which will return whether type `T`
contains a duplicated member.

```ts
type CheckRepeatedTuple<[1, 2, 3]> // false
type CheckRepeatedTuple<[1, 2, 1]> // true
type CheckRepeatedTuple<[1, 2, 3]> // false
type CheckRepeatedTuple<[1, 2, 1]> // true
```

## Solution

The idea behind this challenge is to check if the tuple contains repeated elements or not,
We have to take every single element and check if it is repeated. We will do this by inferring the first element and checking if it exists in the rest of the tuple.
We will infer the first element, `F` and check if it exists in the rest of the tuple by checking if the element extends the `Rest[number]` union.
The idea behind this challenge is to check if the tuple contains repeated
elements or not. We have to take every single element out of it and check if it
is repeated.

It can be done by inferring the first element and checking if it exists in the
rest of the tuple. So we will infer the first element, `F` and check if it
exists in the rest of the tuple by checking if the element extends the
`Rest[number]` union.

```ts
type CheckRepeatedTuple<T extends unknown[]> = T extends [
infer F,
...infer Rest
...infer Rest,
]
? F extends Rest[number]
? true
: false
: false;
```

If the first element exists in the `Rest[number]` that means the item is repeated, in the other case, if it does not exist, we will call the  `CheckRepeatedTuple` again with the rest of the tuple in a recursive way so it will repeat the process of inferring the first element of the passing array again and check if it exists in the remaining items.
If the first element `F` exists in the `Rest[number]` that means the item is
repeated, so we return `true`. Otherwise, if it does not exist, we will call the
`CheckRepeatedTuple` again with the rest of the tuple `Rest` in a recursive way
so it will repeat the process of inferring the first element of the passing
tuple again.

```ts
type CheckRepeatedTuple<T extends unknown[]> = T extends [
infer F,
...infer Rest
...infer Rest,
]
? F extends Rest[number]
? true
Expand Down

0 comments on commit 56ddd0d

Please sign in to comment.