Skip to content

Commit

Permalink
fix: allow readonly arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Dec 1, 2024
1 parent 9fb0370 commit d99dd3b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/array/cartesianProduct.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
type ReadonlyArray2D<T> = readonly (readonly T[])[]

/**
* Create an [n-ary Cartesian product](https://en.wikipedia.org/wiki/Cartesian_product#n-ary_Cartesian_product)
* from the given arrays.
Expand All @@ -22,11 +24,13 @@
* // ]
* ```
*/
export function cartesianProduct<const T extends any[][]>(
export function cartesianProduct<const T extends ReadonlyArray2D<any>>(
...arrays: [...T]
): Array<{ [K in keyof T]: T[K][number] }>

export function cartesianProduct<T extends any[][]>(...arrays: T): T[][] {
export function cartesianProduct<T extends ReadonlyArray2D<any>>(
...arrays: T
): T[][] {
let out: T[][] = [[]]
for (const array of arrays) {
const result = []
Expand Down
8 changes: 8 additions & 0 deletions tests/array/cartesianProduct.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,12 @@ describe('cartesianProduct return type', () => {
expectTypeOf(v2).toEqualTypeOf<1 | 2>()
expectTypeOf(v3).toEqualTypeOf<boolean>()
})
test('with readonly arrays', () => {
const colors = ['red', 'blue'] as const
const sizes = [1, 2] as const
const result = _.cartesianProduct(colors, sizes)
expectTypeOf(result).toEqualTypeOf<
[(typeof colors)[number], (typeof sizes)[number]][]
>()
})
})

0 comments on commit d99dd3b

Please sign in to comment.