这段 if...else 有优雅的写法吗?

311 天前
 waiaan
    function onSortChange({ order, prop }) {
      let sortType = 0
      if (order === 'descending') {
        if (prop === 'thisYearIncome') {
          sortType = 1
        }
        if (prop === 'lastYearIncome') {
          sortType = 3
        }
        if (prop === 'rate') {
          sortType = 5
        }
      } else {
        if (prop === 'thisYearIncome') {
          sortType = 2
        }
        if (prop === 'lastYearIncome') {
          sortType = 4
        }
        if (prop === 'rate') {
          sortType = 6
        }
      }
      this.fetchData(sortType)
    }

谢谢。

9166 次点击
所在节点    JavaScript
76 条回复
hefish
311 天前
我怎么觉着 op 的代码挺顺眼的? 反而是各位大佬回复的代码,看着不够顺。。。
leconio
310 天前
const sortStrategies = {
descending: (prop) => (a, b) => b[prop] - a[prop],
ascending: (prop) => (a, b) => a[prop] - b[prop]
};

const sortCommands = {
thisYearIncome: {
descending: () => sortStrategies.descending('thisYearIncome'),
ascending: () => sortStrategies.ascending('thisYearIncome')
},
lastYearIncome: {
descending: () => sortStrategies.descending('lastYearIncome'),
ascending: () => sortStrategies.ascending('lastYearIncome')
},
rate: {
descending: () => sortStrategies.descending('rate'),
ascending: () => sortStrategies.ascending('rate')
}
};

function createSortCommand(order, prop) {
return sortCommands[prop][order]();
}

const data = [
{ thisYearIncome: 5000, lastYearIncome: 4000, rate: 0.25 },
{ thisYearIncome: 8000, lastYearIncome: 6000, rate: 0.33 },
{ thisYearIncome: 3000, lastYearIncome: 2000, rate: 0.5 },
{ thisYearIncome: 6000, lastYearIncome: 5000, rate: 0.2 }
];

function onSortChange(order, prop) {
const sortCommand = createSortCommand(order, prop);
fetchData(sortCommand);
}

function fetchData(sortCommand) {
const sortedData = data.sort(sortCommand);

console.log('Sorted Data:');
sortedData.forEach((item) => {
console.log(`This Year Income: ${item.thisYearIncome}, Last Year Income: ${item.lastYearIncome}, Rate: ${item.rate}`);
});
}

console.log('Sorting by This Year Income (Descending):');
onSortChange('descending', 'thisYearIncome');

console.log('\nSorting by Last Year Income (Ascending):');
onSortChange('ascending', 'lastYearIncome');

console.log('\nSorting by Rate (Descending):');
onSortChange('descending', 'rate');
AlexTCX
310 天前
function onSortChange({ order, prop }) {
const sortTypes = {
descending: {
thisYearIncome: 1,
lastYearIncome: 3,
rate: 5
},
ascending: {
thisYearIncome: 2,
lastYearIncome: 4,
rate: 6
}
};

const sortType = sortTypes[order][prop] || 0;
this.fetchData(sortType);
}
mingl0280
310 天前
const props=['thisYearIncome','lastYearIncome','rate']
function onSortChange({ order, prop })
{
let b=order=== 'descending'?-1:0;
return this.fetchData(props.IndexOf(prop)*2+b); //如果 JS 的 IndexOf 可以这么用的话
}
mingl0280
310 天前
上面打错了,修正
const props=['thisYearIncome','lastYearIncome','rate']
function onSortChange({ order, prop })
{
let b=order=== 'descending'?-1:0;
return this.fetchData((props.findIndex(prop)+1)*2+b); //查了,不是 indexof
}
nekochyan
310 天前
如果是业务代码,我可能就这么写了,简单清晰明了,后续修改也方便;如果是自己项目,可能会优化成 map 去实现
YuCH
310 天前
lalalalacc
310 天前
```
function onSortChange({ order, prop }) {
const propSortTypeMap = {
thisYearIncome: 0, // 基础值,用于计算排序类型
lastYearIncome: 2,
rate: 4
};

// 计算基础排序类型,如果属性不匹配,则默认为 0
let baseSortType = propSortTypeMap[prop] || 0;

// 根据排序顺序调整排序类型
let sortTypeAdjustment = order === 'descending' ? 1 : 2;

// 计算最终的排序类型
let sortType = baseSortType + sortTypeAdjustment;

// 调用 fetchData 函数
this.fetchData(sortType);
}
```
leonshaw
310 天前
function fetchData({ order, prop })
lalalalacc
310 天前
function onSortChange({ order, prop }) {
// 定义属性到排序类型映射的基础值
const baseSortTypes = {
thisYearIncome: 1,
lastYearIncome: 3,
rate: 5
};

// 使用数组处理升序和降序的逻辑,0 索引用于升序,1 索引用于降序
const orderAdjustments = { ascending: 1, descending: 0 };

// 计算最终的排序类型
let sortType = baseSortTypes[prop] + (orderAdjustments[order] || 0);

// 调用 fetchData 函数
this.fetchData(sortType);
}
lalalalacc
310 天前
// 定义排序策略接口
class SortStrategy {
getSortType(order, prop) {
throw new Error("This method should be implemented by subclasses");
}
}

// 实现具体的排序策略
class IncomeSortStrategy extends SortStrategy {
getSortType(order, prop) {
const baseSortType = prop === 'thisYearIncome' ? 1 : 3;
return order === 'descending' ? baseSortType : baseSortType + 1;
}
}

class RateSortStrategy extends SortStrategy {
getSortType(order) {
return order === 'descending' ? 5 : 6;
}
}

// 环境类,用于使用排序策略
class SortContext {
constructor(strategy) {
this.strategy = strategy;
}

setStrategy(strategy) {
this.strategy = strategy;
}

onSortChange({ order, prop }) {
const sortType = this.strategy.getSortType(order, prop);
this.fetchData(sortType); // 假设这是一个获取数据的方法
}
}

// 使用
const incomeStrategy = new IncomeSortStrategy();
const rateStrategy = new RateSortStrategy();

const sortContext = new SortContext(incomeStrategy); // 初始使用收入排序策略
sortContext.onSortChange({ order: 'descending', prop: 'thisYearIncome' });

sortContext.setStrategy(rateStrategy); // 切换到利率排序策略
sortContext.onSortChange({ order: 'ascending', prop: 'rate' });
foam
310 天前
@hefish 因为他们开始整活了。别搞那些花里胡哨的,用一个 map 做配置就行了。
fox0001
310 天前
@Ericcccccccc #1 我也是第一时间想到 map
fox0001
310 天前
这段代码最大问题是,第二层的 if ,居然没有写成 if…else if…else 的形式
DOLLOR
310 天前
@darkengine
这样写可能清晰一些
function toSortType({ order, prop }) {
const orderType = (order === 'descending') ? (1) : (2);
// 0,2,4 or -2
let sortType = ['thisYearIncome', 'lastYearIncome', 'rate'].indexOf(prop) * 2;
if (sortType < 0) {
return 0;
}
// 1,3,5 or 2,4,6
sortType = sortType + orderType;
return sortType;
}
weeei
310 天前
function onSortChange({ order, prop }) {
var map = new Map(
[
['descending-thisYearIncome', 1], ['descendinglastYearIncome', 3], ['descendingrate', 5],
['ascending-thisYearIncome', 2], ['ascending-lastYearIncome', 4], ['ascending-rate', 6]
])
var sortType = map.get('descending' + '-' + 'thisYearIncome')
this.fetchData(sortType)
}
weeei
310 天前
```js
function onSortChange({ order, prop }) {
var map = new Map(
[
['descending-thisYearIncome', 1], ['descending-lastYearIncome', 3], ['descending-rate', 5],
['ascending-thisYearIncome', 2], ['ascending-lastYearIncome', 4], ['ascending-rate', 6]
])
var sortType = map.get(order + '-' + prop)
this.fetchData(sortType)
}
```
anjingdexiaocai
310 天前
先解决最基本的魔数问题再说😂
libook
310 天前
我会选择用类 map 对象。
egoistttt
310 天前
function onSortChange({ order, prop }) {
const sortOrderMap = {
'thisYearIncome': { 'ascending': 2, 'descending': 1 },
'lastYearIncome': { 'ascending': 4, 'descending': 3 },
'rate': { 'ascending': 6, 'descending': 5 },
};

const sortType = sortOrderMap[prop][order];
if (sortType !== undefined) {
this.fetchData(sortType);
} else {
// 如果 prop 或 order 的组合不在预期中,可以处理错误情况或者默认行为
console.error('Invalid sorting property or order');
}
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1037129

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX