Skip to content

cluster

将列表分割为给定大小的多个列表

116 bytes
since v12.1.0

使用方法

给定一个项目数组和期望的集群大小(n),返回一个数组的数组。每个子数组包含 n(集群大小)个项目,尽可能均匀分割。

import * as _ from "radashi";
const gods = [
"Ra",
"Zeus",
"Loki",
"Vishnu",
"Icarus",
"Osiris",
"Thor",
"Apollo",
"Artemis",
"Athena",
];
_.cluster(gods, 3);
// => [
// [ 'Ra', 'Zeus', 'Loki' ],
// [ 'Vishnu', 'Icarus', 'Osiris' ],
// ['Thor', 'Apollo', 'Artemis'],
// ['Athena']
// ]

类型推断

cluster 函数为常见的集群大小(1-8)提供精确的类型推断:

// With explicit size parameter
const result1 = _.cluster(["a", "b", "c"], 1);
// ^? [string][]
const result2 = _.cluster(["a", "b", "c", "d"], 2);
// ^? [string, string][]
const result3 = _.cluster(["a", "b", "c", "d", "e", "f"], 3);
// ^? [string, string, string][]
// Using default size parameter (2)
const defaultSize = _.cluster(["a", "b", "c", "d"]);
// ^? [string, string][]
// For sizes > 8, falls back to string[][]
const largeSize = _.cluster(["a", "b", "c", "d"], 10);
// ^? string[][]
const veryLargeSize = _.cluster(["a", "b", "c", "d"], 10000);
// ^? string[][]