Open utterances-bot opened 3 years ago
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']>>,
]
@dvlden you mean the explanation is unclear? Please, ask follow-up questions and we try to improve the content.
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
Alternatively,
type Pop<T extends any[]> = T extends [...infer H, infer _] ? H : []
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