mstf-kit
Version:
一个现代化的 JavaScript/TypeScript 工具库,提供了丰富的常用工具函数
41 lines (40 loc) • 971 B
JavaScript
function unique(arr) {
return Array.from(new Set(arr));
}
function groupBy(arr, key) {
return arr.reduce((groups, item) => {
const groupKey = typeof key === "function" ? key(item) : item[key];
(groups[groupKey] = groups[groupKey] || []).push(item);
return groups;
}, {});
}
function flatten(arr, depth = Infinity) {
return arr.flat(depth);
}
function sample(arr, count = 1) {
if (count === 1) {
return arr[Math.floor(Math.random() * arr.length)];
}
return shuffle(arr.slice()).slice(0, count);
}
function shuffle(arr) {
const result = [...arr];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
function closest(arr, target) {
return arr.reduce(
(prev, curr) => Math.abs(curr - target) < Math.abs(prev - target) ? curr : prev
);
}
export {
closest,
flatten,
groupBy,
sample,
shuffle,
unique
};