Skip to content

Commit

Permalink
perf(cluster): avoid an array allocation
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jul 2, 2024
1 parent c061f2f commit 39122cf
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/array/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
* ```
*/
export function cluster<T>(array: readonly T[], size = 2): T[][] {
const clusterCount = Math.ceil(array.length / size)
return new Array(clusterCount).fill(null).map((_c: null, i: number) => {
return array.slice(i * size, i * size + size)
})
const clusters: T[][] = []
for (let i = 0; i < array.length; i += size) {
clusters.push(array.slice(i, i + size))
}
return clusters
}

0 comments on commit 39122cf

Please sign in to comment.