悠悠楠杉
网站页面
正文:
在JavaScript开发中,排序是高频操作之一。无论是表格数据、商品列表还是搜索结果,我们经常需要根据不同的条件(如价格、日期、评分)进行排序。然而,当项目中存在多处类似的排序逻辑时,重复代码会显著增加维护成本。如何将这些逻辑抽象为通用方法?以下是逐步优化的实践方案。
假设有一个电商项目,需对商品列表按价格、销量、评分多次排序,原始代码可能长这样:
// 按价格排序
products.sort((a, b) => a.price - b.price);
// 按销量排序
products.sort((a, b) => a.sales - b.sales);
// 按评分排序(降序)
products.sort((a, b) => b.rating - a.rating);
每新增一个排序条件,就需要重复编写类似的代码,且难以统一处理复杂排序规则(如多级排序)。
通过高阶函数动态生成排序函数,将排序逻辑与业务解耦:
function createSorter(key, order = 'asc') {
return (a, b) => {
const valueA = a[key];
const valueB = b[key];
if (order === 'asc') return valueA - valueB;
return valueB - valueA;
};
}
// 使用示例
products.sort(createSorter('price')); // 价格升序
products.sort(createSorter('sales', 'desc')); // 销量降序
若需排序非数字字段(如字符串日期),可扩展为策略模式:
const sortStrategies = {
number: (a, b, order) => order === 'asc' ? a - b : b - a,
date: (a, b, order) => order === 'asc'
? new Date(a) - new Date(b)
: new Date(b) - new Date(a),
};
function createSmartSorter(key, order = 'asc', type = 'number') {
return (a, b) => sortStrategies[type](a[key], b[key], order);
}
// 按发布日期降序
products.sort(createSmartSorter('publishDate', 'desc', 'date'));
const multiSort = (...sorters) => (a, b) => {
for (const sorter of sorters) {
const result = sorter(a, b);
if (result !== 0) return result;
}
return 0;
};
// 先按评分降序,再按价格升序
products.sort(multiSort(
createSorter('rating', 'desc'),
createSorter('price')
));
通过抽象排序逻辑,代码可维护性和扩展性显著提升。这种模式也适用于其他需要动态策略的场景,如过滤、分组等操作。