Skip to content

Commit

Permalink
improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Nov 10, 2024
1 parent 0835852 commit 3eccb8d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 17 deletions.
9 changes: 4 additions & 5 deletions src/random/draw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,12 @@ import { random } from 'radashi'
* ```
* @version 12.1.0
*/
export function draw<T>(array: readonly [T, ...T[]]): T
export function draw<T>(array: readonly T[]): T | null

export function draw<T>(array: readonly T[]): T | null {
export function draw<const T extends readonly any[]>(
array: T,
): T extends readonly [any, ...any[]] ? T[number] : T[number] | null {
const max = array.length
if (max === 0) {
return null
return null as any
}
const index = random(0, max - 1)
return array[index]
Expand Down
21 changes: 9 additions & 12 deletions tests/random/draw.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,27 @@ import * as _ from 'radashi'

describe('draw', () => {
test('variable with mutable array', () => {
const emptyList: number[] = []
const filledList = [1, 2, 3]
const array = [1, 2, 3]

expectTypeOf(_.draw(emptyList)).toEqualTypeOf<number | null>()
expectTypeOf(_.draw(filledList)).toEqualTypeOf<number | null>()
expectTypeOf(_.draw(array)).toEqualTypeOf<number | null>()
})

test('variable with empty array', () => {
const neverList: never[] = []
const emptyList = [] as const
const emptyArray = [] as never[]
const emptyTuple = [] as const

expectTypeOf(_.draw(neverList)).toEqualTypeOf<null>()
expectTypeOf(_.draw(emptyList)).toEqualTypeOf<null>()
expectTypeOf(_.draw(emptyArray)).toEqualTypeOf<null>()
expectTypeOf(_.draw(emptyTuple)).toEqualTypeOf<null>()
})

test('variable with tuple', () => {
const filledList = [1, 2, 3] as const
const tuple = [1, 2, 3] as const

expectTypeOf(_.draw(filledList)).toEqualTypeOf<1 | 2 | 3>()
expectTypeOf(_.draw(tuple)).toEqualTypeOf<1 | 2 | 3>()
})

test('inlined array', () => {
expectTypeOf(_.draw([])).toEqualTypeOf<null>()
expectTypeOf(_.draw([1, 2, 3])).toEqualTypeOf<number>()
expectTypeOf(_.draw([1, 2, 3] as const)).toEqualTypeOf<1 | 2 | 3>()
expectTypeOf(_.draw([1, 2, 3])).toEqualTypeOf<1 | 2 | 3>()
})
})

0 comments on commit 3eccb8d

Please sign in to comment.