Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

type-challenges-solutions/en/medium-zip #281

Open
utterances-bot opened this issue Nov 2, 2022 · 4 comments
Open

type-challenges-solutions/en/medium-zip #281

utterances-bot opened this issue Nov 2, 2022 · 4 comments

Comments

@utterances-bot
Copy link

Zip

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/en/medium-zip.html

Copy link

marked42 commented Nov 2, 2022

Use composed tuple of two elements for a single type pattern matching with extends keyword.

type Zip<T extends unknown[], U extends unknown[]> = [T, U] extends [[infer T1, ...infer R1], [infer U1, ...infer R2]] ? [[T1, U1], ...Zip<R1, R2>] : []

Copy link
Owner

ghaiklor commented Nov 3, 2022

@marked42 sweet, I didn't think about compound here, thanks for the solution!

Copy link

Followed @marked42 approach and optimized it to use tail recursion

type Zip<
  T extends unknown[],
  U extends unknown[],
  Acc extends [unknown, unknown][] = []
> = [T, U] extends [
  [infer HeadT, ...infer TailT],
  [infer HeadU, ...infer TailU]
]
  ? Zip<TailT, TailU, [...Acc, [HeadT, HeadU]]>
  : Acc;

Copy link

The compound solution is really smart! @marked42

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants