V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
waiaan
V2EX  ›  JavaScript

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

  •  
  •   waiaan · 2024-04-30 17:22:51 +08:00 · 9608 次点击
    这是一个创建于 393 天前的主题,其中的信息可能已经有所发展或是发生改变。
        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)
        }
    

    谢谢。

    76 条回复    2024-05-03 19:22:15 +08:00
    Ericcccccccc
        1
    Ericcccccccc  
       2024-04-30 17:24:36 +08:00   ❤️ 2
    我感觉最多搞个 map 套一下 prop 和 sortType

    外层的 if else 逻辑清晰不用改吧。
    ma836323493
        2
    ma836323493  
       2024-04-30 17:25:46 +08:00   ❤️ 1
    简单 枚举套枚举
    ih8es9OIzne0959p
        3
    ih8es9OIzne0959p  
       2024-04-30 17:25:46 +08:00 via Android   ❤️ 2
    没事,无伤大雅,大道至简,要是再多的话,switch case 走一个
    2kCS5c0b0ITXE5k2
        4
    2kCS5c0b0ITXE5k2  
       2024-04-30 17:26:10 +08:00   ❤️ 7
    ```
    function onSortChange({ order, prop }) {
    const sortMapping = {
    descending: {
    thisYearIncome: 1,
    lastYearIncome: 3,
    rate: 5
    },
    ascending: {
    thisYearIncome: 2,
    lastYearIncome: 4,
    rate: 6
    }
    };

    // Get the sort type from the mapping based on the order and property
    const sortType = sortMapping[order][prop] || 0; // Default to 0 if not found

    this.fetchData(sortType);
    }

    ```
    pkokp8
        5
    pkokp8  
       2024-04-30 17:27:58 +08:00   ❤️ 1
    map? 不会 js ,大概这个意思
    sortTypeMap[order][prop]=0-6
    fetchData(sortTypeMap[order][prop])
    pkokp8
        6
    pkokp8  
       2024-04-30 17:29:23 +08:00
    另外,第二层的第 2/3 个 if 少了 else ,会多两次判断,js 应该也支持 else if
    tomatocici2333
        7
    tomatocici2333  
       2024-04-30 17:31:43 +08:00
    switch case 呗 = =看着不累
    lingyi95
        8
    lingyi95  
       2024-04-30 17:31:45 +08:00
    你去问 gpt ,它可以给你优化成 10 行代码
    mowen1992
        9
    mowen1992  
       2024-04-30 17:33:30 +08:00
    通义灵码来了:
    function onSortChange({ order, prop }) {
    // 使用映射对象来简化条件判断逻辑
    const sortOrders = {
    'thisYearIncome': { descending: 1, ascending: 2 },
    'lastYearIncome': { descending: 3, ascending: 4 },
    'rate': { descending: 5, ascending: 6 },
    };

    try {
    // 检查 prop 是否存在于映射对象中
    if (!sortOrders.hasOwnProperty(prop)) {
    throw new Error(`Invalid property: ${prop}`);
    }

    // 检查 order 是否有效
    if (!sortOrders[prop].hasOwnProperty(order)) {
    throw new Error(`Invalid order: ${order}`);
    }

    // 直接通过映射对象获取 sortType
    const sortType = sortOrders[prop][order];

    // 调用 fetchData 方法更新数据
    this.fetchData(sortType);
    } catch (error) {
    console.error('Error in onSortChange:', error.message);
    // 可以在这里添加额外的错误处理,例如通知用户或记录日志
    }
    }
    Kakaaa
        10
    Kakaaa  
       2024-04-30 17:33:59 +08:00
    xiangyuecn
        11
    xiangyuecn  
       2024-04-30 17:34:14 +08:00
    var order="xxx",prop="rate"
    var sortType=(
    /**/ ({descending:
    /*----*/ {thisYearIncome:1,lastYearIncome:3,rate:5}
    /**/ })[order] ||
    /*----*/ {thisYearIncome:2,lastYearIncome:4,rate:6}
    )[prop]||0;
    davin
        12
    davin  
       2024-04-30 17:34:15 +08:00   ❤️ 3
    先定义枚举吧,不然时间久了怎么解释这些 1 到 6
    ···
    enum SortType {
    THIS_YEAR_INCOME_DESC = 1,
    THIS_YEAR_INCOME_ASC = 2,
    LAST_YEAR_INCOME_DESC = 3,
    LAST_YEAR_INCOME_ASC = 4,
    RATE_DESC = 5,
    RATE_ASC = 6
    }
    ···
    yangg
        13
    yangg  
       2024-04-30 17:35:00 +08:00
    接口设计有问题,搞什么 1 ,2,3 ,4,5,6 的参数
    bertonzh
        14
    bertonzh  
       2024-04-30 17:35:08 +08:00
    {
    'descending-thisYearIncome': 1,
    'descending-lastYearIncome': 3,
    }[`${order}-${prop}`]
    43n5Z6GyW39943pj
        15
    43n5Z6GyW39943pj  
       2024-04-30 17:36:00 +08:00
    function onSortChange({ order, prop }) {
    const sortMap = {
    'descending': { 'thisYearIncome': 1, 'lastYearIncome': 3, 'rate': 5 },
    'ascending': { 'thisYearIncome': 2, 'lastYearIncome': 4, 'rate': 6 }
    };

    const sortType = sortMap[order]?.[prop] || 0;

    this.fetchData(sortType);
    }
    yuzo555
        16
    yuzo555  
       2024-04-30 17:37:36 +08:00
    function onSortChange({ order, prop }) {
    const sortTypes = {
    thisYearIncome: order === 'descending' ? 1 : 2,
    lastYearIncome: order === 'descending' ? 3 : 4,
    rate: order === 'descending' ? 5 : 6,
    };
    this.fetchData(sortTypes[prop] || 0);
    }
    foolnius
        17
    foolnius  
       2024-04-30 17:40:41 +08:00
    const defineObject = {
    descending_thisYearIncome: 1, //注释
    thisYearIncome: 3, //注释
    descending_lastYearIncome: 3, //注释
    lastYearIncome: 4, //注释
    descending_rate: 5, //注释
    rate: 6, //注释
    };

    function onSortChange({ order, prop }) {
    const key = `${order === "descending" ? `${order}_` : ""}${prop}`;
    this.fetchData(defineObject[key] ?? 0);
    }
    NessajCN
        18
    NessajCN  
       2024-04-30 17:40:42 +08:00 via Android
    function onSortChange({ order, prop }) {
    const l=["thisYearIncome", "lastYearIncome", "rate"];
    const sortType = order === "descending" ? l.indexOf(prop)*2+1 : l.indexOf(prop)*2+2;
    this.fetchData(sortType)
    }
    wysnxzm
        19
    wysnxzm  
       2024-04-30 17:40:50 +08:00
    switch 或者 map
    各种设计模式最终也都是依赖 map 进行实现比如策略模式
    z1829909
        20
    z1829909  
       2024-04-30 17:50:19 +08:00
    举手提问, 这里为啥需要转成数字传入 fetchData, 为什么不在这一层直接转为查询条件传入 fetchData.
    因为我觉得 sortType 在 fetchData 中又要被拆开解析, 看代码的人又要去记 sortType 的意思, 多一层开销
    foolnius
        21
    foolnius  
       2024-04-30 17:52:13 +08:00
    @foolnius #17
    "thisYearIncome: 3, //注释" => "thisYearIncome: 2, //注释"
    makejohn2015
        22
    makejohn2015  
       2024-04-30 17:54:00 +08:00
    function onSortChange({ order, prop }) {
    const sortMap = {
    thisYearIncome: { ascending: 2, descending: 1 },
    lastYearIncome: { ascending: 4, descending: 3 },
    rate: { ascending: 6, descending: 5 }
    };

    const sortType = sortMap[prop] ? sortMap[prop][order] : 0;
    this.fetchData(sortType);
    }
    InkStone
        23
    InkStone  
       2024-04-30 18:00:55 +08:00
    fetchData 的参数设计太烂了。这种设计字段一变动直接 gg 。排序这种场景就应该直接根据传入的字段动态生成 query 。
    Track13
        24
    Track13  
       2024-04-30 18:03:18 +08:00
    function onSortChange({ order, prop }) {
    const sortTypes = {
    'thisYearIncome': {
    ascending: 2,
    descending: 1,
    },
    'lastYearIncome': {
    ascending: 4,
    descending: 3,
    },
    'rate': {
    ascending: 6,
    descending: 5,
    },
    };

    const sortType = sortTypes[prop][order];
    this.fetchData(sortType);
    }
    renmu
        25
    renmu  
       2024-04-30 18:03:50 +08:00 via Android
    我选择 switch
    ChefIsAwesome
        26
    ChefIsAwesome  
       2024-04-30 18:14:41 +08:00
    不得不说,chatgpt 给的答案可读性强,易扩展,非常好。
    Pencillll
        27
    Pencillll  
       2024-04-30 18:16:18 +08:00
    好像楼上都没有提到这种写法啊,感觉这样更清晰一些:

    const sortTypes = {
    1: { prop: "thisYearIncome", order: "descending" },
    2: { prop: "thisYearIncome", order: "ascending" },
    3: { prop: "lastYearIncome", order: "descending" },
    4: { prop: "lastYearIncome", order: "ascending" },
    5: { prop: "rate", order: "descending" },
    6: { prop: "rate", order: "ascending" },
    }

    function getSortType({ order, prop }) {
    for (const [sortType, condition] of Object.entries(sortTypes)) {
    if (condition.order === order && condition.prop === prop) {
    return sortType
    }
    }

    return 0
    }
    qinxs
        28
    qinxs  
       2024-04-30 18:16:40 +08:00
    如果 135 246 是固定的值

    function onSortChange({ order, prop }) {
    let sortType = 0
    const sortMap = {
    thisYearIncome: 1,
    lastYearIncome: 3,
    rate: 5,
    }

    sortType = sortMap[prop] || sortType
    if (order !== 'descending' && sortMap.hasOwnProperty(prop)) {
    sortType++
    }
    console.log(sortType)
    // this.fetchData(sortType)
    }
    wildnode
        29
    wildnode  
       2024-04-30 18:17:50 +08:00
    const sortTypeMap = {
    descending: {
    thisYearIncome: 1,
    lastYearIncome: 3,
    rate: 5
    },
    ascending: {
    thisYearIncome: 2,
    lastYearIncome: 4,
    rate: 6
    }
    }

    function onSortChange({ order, prop }) {
    const sortType = sortTypeMap?.[order]?.[prop] ?? 0
    this.fetchData(sortType)
    }
    ZnductR0MjHvjRQ3
        30
    ZnductR0MjHvjRQ3  
       2024-04-30 18:18:12 +08:00
    能否改成这样呢?
    ```js
    function onSortChange({ order, prop }) {
    let sortType = 0;
    const data = {
    descending: {
    thisYearIncome: 1,
    lastYearIncome: 3,
    rate: 5,
    },
    default: {
    thisYearIncome: 2,
    lastYearIncome: 4,
    rate: 6,
    },
    };
    if (!data[order]) order = "default";
    this.fetchData(data[order][prop]);
    }

    ```
    z1154505909
        31
    z1154505909  
       2024-04-30 19:09:50 +08:00
    def test(order,prop):
    arr={
    'descending':{
    "thisYearIncome":1,
    "lastYearIncome":3,
    "rate":5
    },
    "thisYearIncome":2,
    "lastYearIncome":4,
    "rate":6
    }

    try:
    return arr[order][prop]
    except:
    return arr[prop]
    python 写法
    sima675
        32
    sima675  
       2024-04-30 19:21:13 +08:00
    function onSortChange({ order, prop }) {
    const sortMap = {
    'thisYearIncome': {
    'descending': 1,
    'ascending': 2
    },
    'lastYearIncome': {
    'descending': 3,
    'ascending': 4
    },
    'rate': {
    'descending': 5,
    'ascending': 6
    }
    };

    const sortType = sortMap[prop][order];
    this.fetchData(sortType);
    }
    gpt 给的答案,看着还行
    darkengine
        33
    darkengine  
       2024-04-30 19:28:29 +08:00   ❤️ 3
    const arr = ['thisYearIncome', 'lastYearIncome', "rate']

    return (arr.indexOf(prop) + 1) * 2 - (order==='descending'?1:0)


    你这样写,看同事揍不揍就完了 😂
    maigebaoer
        34
    maigebaoer  
       2024-04-30 19:29:23 +08:00 via Android
    扔给 gpt 吧
    wuyiccc
        35
    wuyiccc  
       2024-04-30 19:58:46 +08:00
    order_prop 组成 map 的 key ,value 存放 sortType, 然后需要的时候根据 order_prop 这个 key 直接去 get 就可以了
    secondwtq
        36
    secondwtq  
       2024-04-30 20:19:51 +08:00
    我怎么感觉如果这是 C/C++ 的代码的话,主楼原本的写法就挺好的 ...
    Lax
        37
    Lax  
       2024-04-30 21:35:00 +08:00
    怀疑紧接着还有一段对应的代码:

    function fetchData(sortType) {
    let prop = null;
    let order = null;

    if(sortType === 1) {
    prop = "thisYearIncome";
    order = "descending";
    }
    if(sortType === 2) {
    prop = "...";
    order = "...";
    }
    if(sortType === 3) {
    prop = "...";
    order = "...";
    }
    if(sortType === 4) {
    prop = "...";
    order = "...";
    }
    if(sortType === 5) {
    prop = "...";
    order = "...";
    }
    if(sortType === 6) {
    prop = "...";
    order = "...";
    }

    // do something
    }
    cookii
        38
    cookii  
       2024-04-30 21:44:42 +08:00 via Android
    @darkengine 这么多答案我还是喜欢你这个
    bidongliang
        39
    bidongliang  
       2024-04-30 22:03:04 +08:00 via Android
    @darkengine 果然找到了心目中的答案
    lanlanye
        40
    lanlanye  
       2024-04-30 22:49:44 +08:00
    ```javascript
    class SortService {
    getSortType(sort) {
    const mapping = {
    thisYearIncome: {
    ascending: 2,
    descending: 1,
    },
    lastYearIncome: {
    ascending: 4,
    descending: 3,
    },
    rate: {
    ascending: 6,
    descending: 5,
    },
    };
    return mapping[sort.sortBy][sort.sortOrder];
    }
    }


    function onSortChange({ order, prop }) {
    const sort = new Sort(prop, order);
    const sortType = new SortService().getSortType(sort);
    this.fetchData(sortType);
    }
    ```
    hefish
        41
    hefish  
       2024-04-30 23:00:31 +08:00
    我怎么觉着 op 的代码挺顺眼的? 反而是各位大佬回复的代码,看着不够顺。。。
    leconio
        42
    leconio  
       2024-04-30 23:26:59 +08:00 via iPhone
    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
        43
    AlexTCX  
       2024-04-30 23:49:26 +08:00
    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
        44
    mingl0280  
       2024-05-01 06:47:08 +08:00 via Android
    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
        45
    mingl0280  
       2024-05-01 06:50:12 +08:00 via Android
    上面打错了,修正
    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
        46
    nekochyan  
       2024-05-01 09:50:52 +08:00
    如果是业务代码,我可能就这么写了,简单清晰明了,后续修改也方便;如果是自己项目,可能会优化成 map 去实现
    YuCH
        47
    YuCH  
       2024-05-01 10:50:35 +08:00
    lalalalacc
        48
    lalalalacc  
       2024-05-01 11:13:11 +08:00
    ```
    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
        49
    leonshaw  
       2024-05-01 11:13:43 +08:00 via Android
    function fetchData({ order, prop })
    lalalalacc
        50
    lalalalacc  
       2024-05-01 11:18:00 +08:00
    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
        51
    lalalalacc  
       2024-05-01 11:20:37 +08:00
    // 定义排序策略接口
    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
        52
    foam  
       2024-05-01 11:32:26 +08:00 via Android
    @hefish 因为他们开始整活了。别搞那些花里胡哨的,用一个 map 做配置就行了。
    fox0001
        53
    fox0001  
       2024-05-01 11:41:03 +08:00 via Android
    @Ericcccccccc #1 我也是第一时间想到 map
    fox0001
        54
    fox0001  
       2024-05-01 11:43:00 +08:00 via Android
    这段代码最大问题是,第二层的 if ,居然没有写成 if…else if…else 的形式
    DOLLOR
        55
    DOLLOR  
       2024-05-01 11:50:35 +08:00
    @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
        56
    weeei  
       2024-05-01 12:04:36 +08:00
    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
        57
    weeei  
       2024-05-01 12:06:35 +08:00
    ```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
        58
    anjingdexiaocai  
       2024-05-01 12:09:45 +08:00 via Android
    先解决最基本的魔数问题再说😂
    libook
        59
    libook  
       2024-05-01 12:16:18 +08:00 via Android
    我会选择用类 map 对象。
    egoistttt
        60
    egoistttt  
       2024-05-01 12:51:57 +08:00
    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');
    }
    }
    kinge
        61
    kinge  
       2024-05-01 15:58:09 +08:00
    优雅的代码不易于阅读,这样就很好
    ntedshen
        62
    ntedshen  
       2024-05-01 16:28:30 +08:00
    map=new map([
    ['desc_tyi',1],
    ['desc_lyi',3],
    ['desc_r',5],
    ])

    function onSortChange({ order, prop })
    key=[order,pop].join('_')
    type=map.get(key)??0
    this.fetchData(sortType)
    lDqe4OE6iOEUQNM7
        63
    lDqe4OE6iOEUQNM7  
       2024-05-01 16:41:46 +08:00
    function onSortChange({ order, prop }) {
    const sortMap = {
    descending: {
    thisYearIncome: 1,
    lastYearIncome: 3,
    rate: 5
    },
    ascending: {
    thisYearIncome: 2,
    lastYearIncome: 4,
    rate: 6
    }
    };

    const sortType = sortMap[order][prop] || 0; // 如果没有匹配到,则默认为 0
    this.fetchData(sortType);
    }
    incubus
        64
    incubus  
       2024-05-01 16:43:31 +08:00
    function onSortChange({ order, prop }) {
    const sortTypeMap = {
    'thisYearIncome': { 'descending': 1, 'ascending': 2 },
    'lastYearIncome': { 'descending': 3, 'ascending': 4 },
    'rate': { 'descending': 5, 'ascending': 6 }
    };

    const sortType = sortTypeMap[prop][order];
    this.fetchData(sortType);
    }
    FYFX
        65
    FYFX  
       2024-05-01 19:27:30 +08:00
    你是 order2 种值,prop 3 种值组合总共 6 种,我是觉得把 6 种可能枚举出来比较好,先判断 order 再判断 prop 感觉没那么清晰
    mrytsr
        66
    mrytsr  
       2024-05-01 19:37:01 +08:00 via Android
    没搞懂为什么要把 prop 和 order 转成 sorttype ,建议直接存储或传输 prop,order
    pennai
        67
    pennai  
       2024-05-01 22:34:53 +08:00 via Android
    1.可以配在 db 里,这样一行查 db 然后一行赋值 sort type 就行
    2.策略模式实现
    3.上规则引擎
    nuk
        68
    nuk  
       2024-05-02 00:07:04 +08:00
    let sortType = order === 'descending'?prop === 'thisYearIncome'?1:prop === 'lastYearIncome'? 3:prop === 'rate'?5:0:prop === 'thisYearIncome'?2:prop === 'lastYearIncome'?4:prop === 'rate'?6:0
    shyangs
        69
    shyangs  
       2024-05-02 00:33:45 +08:00
    @z1829909

    '''
    > 举手提问, 这里为啥需要转成数字传入 fetchData, 为什么不在这一层直接转为查询条件传入 fetchData.
    因为我觉得 sortType 在 fetchData 中又要被拆开解析, 看代码的人又要去记 sortType 的意思, 多一层开销
    '''

    z1829909 說的對,原本 order, prop 不是魔法數字 (magic number),經過 onSortChange 反而變成魔術數字了.

    onSortChange 根本就是多餘的,fetchData 直接傳入 order, prop 即可. 呼叫者直接調用 fetchData 即可.
    walkerliu
        70
    walkerliu  
       2024-05-02 09:20:11 +08:00
    评论里的反向优化看醉了..........。OP 的代码逻辑清晰, 可读性强,也没性能问题。 评论里面又是匿名函数又是三目运算符的.. 这不妥妥的反向优化嘛
    cpstar
        71
    cpstar  
       2024-05-02 09:21:52 +08:00
    全都是优雅 order 和 prop 的,窃以为问题的根源在 0123456
    如果真的要优雅,应该多态到头,连带 fetchData 做到多态
    amlee
        72
    amlee  
       2024-05-02 10:25:58 +08:00
    我不懂为什么接口要单独定义一个 sortType ,直接 fetchData(order, prop)不就好了?后端也简单前端也简单。
    zcm3579
        73
    zcm3579  
       2024-05-02 11:38:43 +08:00
    你这边前端转成数字 , 后端接口拿到后是不是又转回字段和 order
    pytth
        74
    pytth  
       2024-05-02 12:22:46 +08:00 via Android
    使用对象映射法:

    ```
    function onSortChange({ order, prop }) {
    const propMap = {
    thisYearIncome: {
    descending: 1,
    ascending: 2
    },
    lastYearIncome: {
    descending: 3,
    ascending: 4
    },
    rate: {
    descending: 5,
    ascending: 6
    }
    };

    const sortType = propMap[prop][order];
    this.fetchData(sortType);
    }
    ```
    bv
        75
    bv  
       2024-05-02 20:09:09 +08:00
    下面这样,有点为了优化而优化,让人难以理解了:
    function onSortChange(order, prop) {
    let props = new Map([
    ["thisYearIncome", 1],
    ["lastYearIncome", 3],
    ["rate", 5],
    ]);

    this.fetchData((order === "descending" ? 0 : 1) + props.get(prop))
    }
    netabare
        76
    netabare  
       2024-05-03 19:22:15 +08:00
    表驱动。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3140 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 12:10 · PVG 20:10 · LAX 05:10 · JFK 08:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.