fix media item sort

This commit is contained in:
Timi
2025-12-11 19:21:41 +08:00
parent f837c4d4d9
commit c0a0242a02
10 changed files with 201 additions and 101 deletions

View File

@ -220,10 +220,58 @@ export default class Toolkit {
public static symmetricDiff(arr1: any[], arr2: any[]) {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
return [
...arr1.filter(item => !set2.has(item)),
...arr2.filter(item => !set1.has(item))
];
}
/**
* 将数组元素分配到指定数量的列中
*
* - 如果提供 getHeight 函数:使用贪心算法,每次将元素放到当前高度最小的列(适合瀑布流布局)
* - 如果不提供 getHeight使用轮询方式分配第 1、4、7... 个到列 1第 2、5、8... 个到列 2
*
* @param items 原始数组
* @param columnCount 列数,默认 3
* @param getHeight 可选的高度获取函数,用于计算每个元素的高度
* @returns 分列后的二维数组
*
* @example
* // 简单轮询分配
* splitItemsIntoColumns([1, 2, 3, 4, 5, 6], 3)
* // => [[1, 4], [2, 5], [3, 6]]
*
* @example
* // 基于高度的贪心分配
* const items = [{ h: 100 }, { h: 200 }, { h: 150 }]
* splitItemsIntoColumns(items, 2, item => item.h)
* // => [[ { h: 100 }, { h: 150 }], [{ h: 200 }]]
*/
public static splitItemsIntoColumns<T>(
items: T[],
columnCount = 3,
getHeight?: (item: T) => number
): T[][] {
const columns: T[][] = Array.from({ length: columnCount }, () => []);
if (!getHeight) {
// 降级为轮询分配
items.forEach((item, index) => {
columns[index % columnCount].push(item);
});
} else {
// 使用贪心算法:总是放到当前高度最小的列
const columnHeights = Array(columnCount).fill(0);
items.forEach((item) => {
// 找到高度最小的列
const minHeightIndex = columnHeights.indexOf(Math.min(...columnHeights));
columns[minHeightIndex].push(item);
columnHeights[minHeightIndex] += getHeight(item);
});
}
return columns;
}
}