• [Typescript] 78. Medium Unqiue


    Implement the type version of Lodash.uniq, Unique takes an Array T, returns the Array T without repeated values.

    type Res = Unique<[1, 1, 2, 2, 3, 3]>; // expected to be [1, 2, 3]
    type Res1 = Unique<[1, 2, 3, 4, 4, 5, 6, 7]>; // expected to be [1, 2, 3, 4, 5, 6, 7]
    type Res2 = Unique<[1, "a", 2, "b", 2, "a"]>; // expected to be [1, "a", 2, "b"]
    type Res3 = Unique<[string, number, 1, "a", 1, string, 2, "b", 2, number]>; // expected to be [string, number, 1, "a", 2, "b"]
    type Res4 = Unique<[unknown, unknown, any, any, never, never]>; // expected to be [unknown, any, never]
    /* _____________ Your Code Here _____________ */
    
    export type Equal<T, U> = 
      (<P>(x: P) => P extends T ? 1: 2) extends 
      (<P>(x: P) => P extends U ? 1: 2) 
        ? true
        : false;
    
    export type IndexOf<T extends any[], U, ACC extends unknown[] = []> = T extends [infer F, ...infer RT]
      ? Equal<F, U> extends true
        ? ACC['length']
        : IndexOf<RT, U, [...ACC, unknown]>
      : -1;
    
    export type Unique<T extends any[], ACC extends any[] = []> = T extends [infer F, ...infer RT]
      ? IndexOf<ACC, F> extends -1
        ? Unique<RT, [...ACC, F]>
        : Unique<RT, ACC>
      : ACC;
    
    /* _____________ Test Cases _____________ */
    import type { Equal, Expect } from '@type-challenges/utils'
    
    type cases = [
      Expect<Equal<Unique<[1, 1, 2, 2, 3, 3]>, [1, 2, 3]>>,
      Expect<Equal<Unique<[1, 2, 3, 4, 4, 5, 6, 7]>, [1, 2, 3, 4, 5, 6, 7]>>,
      Expect<Equal<Unique<[1, 'a', 2, 'b', 2, 'a']>, [1, 'a', 2, 'b']>>,
      Expect<Equal<Unique<[string, number, 1, 'a', 1, string, 2, 'b', 2, number]>, [string, number, 1, 'a', 2, 'b']>>,
      Expect<Equal<Unique<[unknown, unknown, any, any, never, never]>, [unknown, any, never]>>,
    ]
  • 相关阅读:
    软工结对第一次作业
    16061023-软件工程第1次作业
    OO最后一次总结
    OO第三次博客作业
    OO第二次博客作业
    OO第一次博客
    提问回顾与个人总结
    软件工程第一次阅读作业
    test个人博客
    软件工程结对作业
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16838974.html
Copyright © 2020-2023  润新知