yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

00013-medium-pop #13

Open yunliuyan opened 1 year ago

yunliuyan commented 1 year ago

出堆 中等 #array

by Anthony Fu @antfu

接受挑战    English 日本語

由谷歌自动翻译,欢迎 PR 改进翻译质量。

在此挑战中建议使用TypeScript 4.0

实现一个通用Pop<T>,它接受一个数组T并返回一个没有最后一个元素的数组。

例如

type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]

type re1 = Pop<arr1> // expected to be ['a', 'b', 'c']
type re2 = Pop<arr2> // expected to be [3, 2]

测试案例:

import type { Equal, Expect } from '@type-challenges/utils'

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

额外:同样,您也可以实现ShiftPushUnshift吗?


返回首页 分享你的解答 查看解答

相关挑战

14・第一个元素 15・最后一个元素
yunliuyan commented 1 year ago

思路

出堆思想

代码实现

type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]

type Pop<T extends any[]> = T extends [...infer args, infer U] ? args : never;

type re1 = Pop<arr1> // expected to be ['a', 'b', 'c']
type re2 = Pop<arr2> // expected to be [3, 2]
liangchengv commented 1 year ago

pop

type Pop<T extends unknown[]> = T extends [...infer U, infer P] ? U : never;

type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]

type tail1 = Pop<arr1> // expected to be ['a', 'b', 'c']
type tail2 = Pop<arr2> // expected to be [3, 2]

Shift

type Shift<T extends unknown[]> = T extends [infer U, ...infer P] ? U : never;

type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]

type tail1 = Shift<arr1> // expected to be ['a']
type tail2 = Shift<arr2> // expected to be [3]

push

type Push<T extends unknown[], U> = [...T, U];

type arr1 = ['a', 'b', 'c'];
type arr2 = [3, 2, 1];

type tail1 = Push<arr1, 0>; // expected to be ['a', 'b', 'c', 0]
type tail2 = Push<arr2, 0>; // expected to be [3, 2, 1, 0]

Unshift

type Unshift<T extends unknown[], U> = [U, ...T];

type arr1 = ['a', 'b', 'c'];
type arr2 = [3, 2, 1];

type tail1 = Unshift<arr1, 0>; // expected to be [0, 'a', 'b', 'c']
type tail2 = Unshift<arr2, 4>; // expected to be [4, 3, 2, 1]
Janice-Fan commented 1 year ago
type Pop<T extends unknown[]> = T extends [...infer args, infer P] ? args : never;

type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]

type re1 = Pop<arr1> // expected to be ['a', 'b', 'c']
type re2 = Pop<arr2> // expected to be [3, 2]
Naparte commented 1 year ago

// 实现一个通用Pop<T>,它接受一个数组T并返回一个没有最后一个元素的数组。

type Pop<T> = T extends [... infer P, infer last] ? P : never;

type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]

type re1 = Pop<arr1> // expected to be ['a', 'b', 'c']
type re2 = Pop<arr2> // expected to be [3, 2]
wudu8 commented 1 year ago
type popArr1 = ['a', 'b', 'c', 'd']
type popArr2 = [3, 'a', 1]

type MyPop<T extends any[]> = T extends [...infer args, infer U] ? args : never;

type popRe1 = MyPop<popArr1> // expected to be ['a', 'b', 'c']
type popRe2 = MyPop<popArr2> // expected to be [3, 'a']