[Typescript] 149 Medium - Triangular number

Given a number N, find the Nth triangular number, i.e. 1 + 2 + 3 + ... + N

/* _____________ Your Code Here _____________ */

export type NumberToArray<
  T extends number,
  R extends 1[] = []
> = R["length"] extends T ? R : NumberToArray<T, [...R, 1]>;

type Triangular<N extends number, R extends any[] = [], Count extends unknown[] = []> = Count['length'] extends N 
  ? R['length']
  : Triangular<N, [...NumberToArray<[...Count, ""]['length']>, ...R], [...Count, unknown]>
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<Triangular<0>, 0>>,
  Expect<Equal<Triangular<1>, 1>>,
  Expect<Equal<Triangular<3>, 6>>,
  Expect<Equal<Triangular<10>, 55>>,
  Expect<Equal<Triangular<20>, 210>>,
  Expect<Equal<Triangular<55>, 1540>>,
  Expect<Equal<Triangular<100>, 5050>>,
]

 

posted @ 2023-07-18 19:47  Zhentiw  阅读(2)  评论(0编辑  收藏  举报