Cluster
Split the given list into chunks of the given size.
๐ฌ Usage
<script>
import {cluster} from "@sveu/shared/lists"
let list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const clusters = cluster(list, , {size: 3}) // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
</script>
๐ฉโ๐ปAPI
๐ป Arguments
Name | Description | Type | Required |
---|---|---|---|
list | The list to cluster | T[] | Yes |
๐ Options
Name | Description | Type | Default |
---|---|---|---|
size | The size of each cluster | number | 2 |
โฉ๏ธ Returns
List of clusters.
๐งช Playground
Source Code ๐
Source Code
import type { ClusterOptions } from "../../utils"
/**
* Split a list into sublists.
*
* @param list - The list to split.
*
* @param options - The options to use.
* - `size` - The max size of each sublist. Default: `2`
*
* @returns List of sublists.
*/
export function cluster<T>(list: T[], options: ClusterOptions = {}): T[][] {
const { size = 2 } = options
if (size === 0) return []
const cluster_count = Math.ceil(list.length / size)
return new Array(cluster_count).fill(null).map((_c: null, i: number) => {
return list.slice(i * size, i * size + size)
})
}
Last update: 2023-02-14
Authors: Mohamed-Kaizen