• 欢迎光临~

[Typescript] 74. Medium - LastIndexOf

开发技术 开发技术 2022-10-28 次浏览

Implement the type version of Array.lastIndexOfLastIndexOf<T, U> takes an Array T, any U and returns the index of the last U in Array T

For example:

type Res1 = LastIndexOf<[1, 2, 3, 2, 1], 2> // 3
type Res2 = LastIndexOf<[0, 0, 0], 2> // -1

 

/* _____________ Your Code Here _____________ */

type LastIndexOf<T extends any[], U> = T extends [...infer RT, infer L]
  ? Equal<L, U> extends true
    ? RT['length']
    : LastIndexOf<RT, U>
  : -1;

type z = LastIndexOf<[string, any, 1, number, 'a', any, 1], any>
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<LastIndexOf<[1, 2, 3, 2, 1], 2>, 3>>,
  Expect<Equal<LastIndexOf<[2, 6, 3, 8, 4, 1, 7, 3, 9], 3>, 7>>,
  Expect<Equal<LastIndexOf<[0, 0, 0], 2>, -1>>,
  Expect<Equal<LastIndexOf<[string, 2, number, 'a', number, 1], number>, 4>>,
  Expect<Equal<LastIndexOf<[string, any, 1, number, 'a', any, 1], any>, 5>>,
]

 

程序员灯塔
转载请注明原文链接:[Typescript] 74. Medium - LastIndexOf
喜欢 (0)
违法和不良信息举报电话:022-22558618 举报邮箱:dljd@tidljd.com