Skip to content

Commit ca2abdd

Browse files
authored
feat(cluster): use tuple types for common size constants (#389)
1 parent 382d351 commit ca2abdd

File tree

3 files changed

+53
-3
lines changed

3 files changed

+53
-3
lines changed

.github/next-minor.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,6 @@ https://github.com/radashi-org/radashi/pull/388
1010

1111
## New Features
1212

13-
####
13+
#### Improve `cluster` type inference
14+
15+
https://github.com/radashi-org/radashi/pull/389

docs/array/cluster.mdx

+27
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,30 @@ _.cluster(gods, 3)
3434
// ['Athena']
3535
// ]
3636
```
37+
38+
### Type Inference
39+
40+
The `cluster` function provides precise type inference for common cluster sizes (1-8):
41+
42+
```ts
43+
// With explicit size parameter
44+
const result1 = _.cluster(['a', 'b', 'c'], 1)
45+
// ^? [string][]
46+
47+
const result2 = _.cluster(['a', 'b', 'c', 'd'], 2)
48+
// ^? [string, string][]
49+
50+
const result3 = _.cluster(['a', 'b', 'c', 'd', 'e', 'f'], 3)
51+
// ^? [string, string, string][]
52+
53+
// Using default size parameter (2)
54+
const defaultSize = _.cluster(['a', 'b', 'c', 'd'])
55+
// ^? [string, string][]
56+
57+
// For sizes > 8, falls back to string[][]
58+
const largeSize = _.cluster(['a', 'b', 'c', 'd'], 10)
59+
// ^? string[][]
60+
61+
const veryLargeSize = _.cluster(['a', 'b', 'c', 'd'], 10000)
62+
// ^? string[][]
63+
```

src/array/cluster.ts

+23-2
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,31 @@
99
* ```
1010
* @version 12.1.0
1111
*/
12-
export function cluster<T>(array: readonly T[], size = 2): T[][] {
12+
export function cluster<T, Size extends number = 2>(
13+
array: readonly T[],
14+
size: Size = 2 as Size,
15+
): Cluster<T, Size>[] {
1316
const clusters: T[][] = []
1417
for (let i = 0; i < array.length; i += size) {
1518
clusters.push(array.slice(i, i + size))
1619
}
17-
return clusters
20+
return clusters as Cluster<T, Size>[]
1821
}
22+
23+
type Cluster<T, Size extends number> = Size extends 1
24+
? [T]
25+
: Size extends 2
26+
? [T, T]
27+
: Size extends 3
28+
? [T, T, T]
29+
: Size extends 4
30+
? [T, T, T, T]
31+
: Size extends 5
32+
? [T, T, T, T, T]
33+
: Size extends 6
34+
? [T, T, T, T, T, T]
35+
: Size extends 7
36+
? [T, T, T, T, T, T, T]
37+
: Size extends 8
38+
? [T, T, T, T, T, T, T, T]
39+
: T[]

0 commit comments

Comments
 (0)