type-challenges-solutions icon indicating copy to clipboard operation
type-challenges-solutions copied to clipboard

type-challenges-solutions/en/medium-pop

Open utterances-bot opened this issue 4 years ago • 4 comments

Pop

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-pop.html

utterances-bot avatar Apr 26 '21 21:04 utterances-bot

Following the previous exercise that I did not understand (and I still don't), here's my solution and extras from the same challenge, that were optional.

type Pop<T extends unknown[]> = T extends [...infer L, unknown] ? L : never
type Push<T extends unknown[], V> = [...T, V]
type Shift<T extends unknown[]> = T extends [unknown, ...infer F] ? F : never
type Unshift<T extends unknown[], V> = [V, ...T]

Test cases:

type cases = [
  Expect<Equal<Pop<[3, 2, 1]>, [3, 2]>>,
  Expect<Equal<Pop<['a', 'b', 'c', 'd']>, ['a', 'b', 'c']>>,

  Expect<Equal<Push<[1, 2, 3], 4>, [1, 2, 3, 4]>>,
  Expect<Equal<Push<['a', 'b', 'c'], 'd'>, ['a', 'b', 'c', 'd']>>,

  Expect<Equal<Shift<[1, 2, 3]>, [2, 3]>>,
  Expect<Equal<Shift<['a', 'b', 'c', 'd']>, ['b', 'c', 'd']>>,

  Expect<Equal<Unshift<[1, 2, 3], 4>, [4, 1, 2, 3]>>,
  Expect<Equal<Unshift<['a', 'b', 'c', 'd'], 'e'>, ['e', 'a', 'b', 'c', 'd']>>,
]

nonwip avatar Apr 26 '21 21:04 nonwip

@dvlden you mean the explanation is unclear? Please, ask follow-up questions and we try to improve the content.

ghaiklor avatar Apr 28 '21 10:04 ghaiklor

Update for new test case.

Expect<Equal<Pop<[]>, []>>
type Pop<T extends any[]> = T["length"] extends 0 ? [] : T extends [...infer H, infer T] ? H : never

MajorLift avatar Dec 28 '22 20:12 MajorLift

Alternatively,

type Pop<T extends any[]> = T extends [...infer H, infer _] ? H : []

MajorLift avatar Dec 28 '22 21:12 MajorLift