Skip to content

Commit

Permalink
feat: let cluster accept any iterable
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jul 7, 2024
1 parent 17f197e commit adb7bb1
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/array/cluster.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { toIterable, type ToIterableItem } from 'radashi'

/**
* Splits a single list into many lists of the desired size.
*
Expand All @@ -6,10 +8,17 @@
* // [[1, 2], [3, 4], [5, 6]]
* ```
*/
export function cluster<T>(array: readonly T[], size = 2): T[][] {
const clusters: T[][] = []
for (let i = 0; i < array.length; i += size) {
clusters.push(array.slice(i, i + size))
export function cluster<T extends object>(
array: T,
size = 2,
): ToIterableItem<T>[][] {
const clusters: any[][] = []
let cluster = (clusters[0] = [] as any[])
for (const item of toIterable(array)) {
if (cluster.length === size) {
clusters.push((cluster = []))
}
cluster.push(item)
}
return clusters
}

0 comments on commit adb7bb1

Please sign in to comment.