fix media item sort
This commit is contained in:
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user