推荐关注
› Meteor
› JSLint - a JavaScript code quality tool
› jsFiddle
› D3.js
› WebStorm
推荐书目
› JavaScript 权威指南第 5 版
› Closure: The Definitive Guide
waiaan

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

  •  
  •   waiaan · Apr 30, 2024 · 12375 views
    This topic created in 918 days ago, the information mentioned may be changed or developed.
        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 replies  •  2024-05-03 19:22:15 +08:00
    Ericcccccccc
    Ericcccccccc
    Apr 30, 2024❤️2
    1
    我感觉最多搞个 map 套一下 prop 和 sortType

    外层的 if else 逻辑清晰不用改吧。
    adimn
    adimn
    Apr 30, 2024❤️1
    2
    简单 枚举套枚举
    ih8es9OIzne0959p
    ih8es9OIzne0959p
    Apr 30, 2024 via Android❤️2
    3
    没事,无伤大雅,大道至简,要是再多的话,switch case 走一个
    2kCS5c0b0ITXE5k2
    2kCS5c0b0ITXE5k2
    Apr 30, 2024❤️7
    4
    ```
    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);
    }

    ```
    povvoq
    povvoq
    Apr 30, 2024❤️1
    5
    map? 不会 js ,大概这个意思
    sortTypeMap[order][prop]=0-6
    fetchData(sortTypeMap[order][prop])
    povvoq
    povvoq
    Apr 30, 2024
    6
    另外,第二层的第 2/3 个 if 少了 else ,会多两次判断,js 应该也支持 else if
    tomatocici2333
    tomatocici2333
    Apr 30, 2024
    7
    switch case 呗 = =看着不累
    lingyi95
    lingyi95
    Apr 30, 2024
    8
    你去问 gpt ,它可以给你优化成 10 行代码
    mowen1992
    mowen1992
    Apr 30, 2024
    9
    通义灵码来了:
    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
    Kakaaa
    Apr 30, 2024
    10
    有
    xiangyuecn
    xiangyuecn
    Apr 30, 2024
    11
    var order="xxx",prop="rate"
    var sortType=(
    /**/ ({descending:
    /*----*/ {thisYearIncome:1,lastYearIncome:3,rate:5}
    /**/ })[order] ||
    /*----*/ {thisYearIncome:2,lastYearIncome:4,rate:6}
    )[prop]||0;
    davin
    davin
    Apr 30, 2024❤️3
    12
    先定义枚举吧,不然时间久了怎么解释这些 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
    yangg
    Apr 30, 2024
    13
    接口设计有问题,搞什么 1 ,2,3 ,4,5,6 的参数
    bertonzh
    bertonzh
    Apr 30, 2024
    14
    {
    'descending-thisYearIncome': 1,
    'descending-lastYearIncome': 3,
    }[`${order}-${prop}`]
    43n5Z6GyW39943pj
    43n5Z6GyW39943pj
    Apr 30, 2024
    15
    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
    yuzo555
    Apr 30, 2024
    16
    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);
    }
    foolenius
    foolenius
    Apr 30, 2024
    17
    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
    NessajCN
    Apr 30, 2024 via Android
    18
    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
    wysnxzm
    Apr 30, 2024
    19
    switch 或者 map
    各种设计模式最终也都是依赖 map 进行实现比如策略模式
    zh3256
    zh3256
    Apr 30, 2024
    20
    举手提问, 这里为啥需要转成数字传入 fetchData, 为什么不在这一层直接转为查询条件传入 fetchData.
    因为我觉得 sortType 在 fetchData 中又要被拆开解析, 看代码的人又要去记 sortType 的意思, 多一层开销
    foolenius
    foolenius
    Apr 30, 2024
    21
    @foolnius #17
    "thisYearIncome: 3, //注释" => "thisYearIncome: 2, //注释"
    makejohn2015
    makejohn2015
    Apr 30, 2024
    22
    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
    InkStone
    Apr 30, 2024
    23
    fetchData 的参数设计太烂了。这种设计字段一变动直接 gg 。排序这种场景就应该直接根据传入的字段动态生成 query 。
    bgm004
    bgm004
    Apr 30, 2024
    24
    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
    renmu
    Apr 30, 2024 via Android
    25
    我选择 switch
    ChefIsAwesome
    ChefIsAwesome
    Apr 30, 2024
    26
    不得不说,chatgpt 给的答案可读性强,易扩展,非常好。
    Pencillll
    Pencillll
    Apr 30, 2024
    27
    好像楼上都没有提到这种写法啊,感觉这样更清晰一些:

    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
    qinxs
    Apr 30, 2024
    28
    如果 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
    wildnode
    Apr 30, 2024
    29
    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
    ZnductR0MjHvjRQ3
    Apr 30, 2024
    30
    能否改成这样呢?
    ```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
    z1154505909
    Apr 30, 2024
    31
    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
    sima675
    Apr 30, 2024
    32
    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
    darkengine
    Apr 30, 2024❤️3
    33
    const arr = ['thisYearIncome', 'lastYearIncome', "rate']

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


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

    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
    cookii
    Apr 30, 2024 via Android
    38
    @darkengine 这么多答案我还是喜欢你这个
    bidongliang
    bidongliang
    Apr 30, 2024 via Android
    39
    @darkengine 果然找到了心目中的答案
    lanlanye
    lanlanye
    Apr 30, 2024
    40
    ```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
    hefish
    Apr 30, 2024
    41
    我怎么觉着 op 的代码挺顺眼的? 反而是各位大佬回复的代码,看着不够顺。。。
    leconio
    leconio
    Apr 30, 2024 via iPhone
    42
    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
    AlexTCX
    Apr 30, 2024
    43
    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
    mingl0280
    May 1, 2024 via Android
    44
    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
    mingl0280
    May 1, 2024 via Android
    45
    上面打错了,修正
    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
    nekochyan
    May 1, 2024
    46
    如果是业务代码,我可能就这么写了,简单清晰明了,后续修改也方便;如果是自己项目,可能会优化成 map 去实现
    YuCH
    YuCH
    May 1, 2024
    47
    lalalalacc
    lalalalacc
    May 1, 2024
    48
    ```
    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
    leonshaw
    May 1, 2024 via Android
    49
    function fetchData({ order, prop })
    lalalalacc
    lalalalacc
    May 1, 2024
    50
    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
    lalalalacc
    May 1, 2024
    51
    // 定义排序策略接口
    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
    foam
    May 1, 2024 via Android
    52
    @hefish 因为他们开始整活了。别搞那些花里胡哨的,用一个 map 做配置就行了。
    fox0001
    fox0001
    May 1, 2024 via Android
    53
    @Ericcccccccc #1 我也是第一时间想到 map
    fox0001
    fox0001
    May 1, 2024 via Android
    54
    这段代码最大问题是,第二层的 if ,居然没有写成 if…else if…else 的形式
    AV1
    AV1
    May 1, 2024
    55
    @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
    weeei
    May 1, 2024
    56
    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
    weeei
    May 1, 2024
    57
    ```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
    anjingdexiaocai
    May 1, 2024 via Android
    58
    先解决最基本的魔数问题再说😂
    libook
    libook
    May 1, 2024 via Android
    59
    我会选择用类 map 对象。
    Ho1iday
    Ho1iday
    May 1, 2024
    60
    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
    kinge
    May 1, 2024
    61
    优雅的代码不易于阅读,这样就很好
    ntedshen
    ntedshen
    May 1, 2024
    62
    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
    lDqe4OE6iOEUQNM7
    May 1, 2024
    63
    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
    incubus
    May 1, 2024
    64
    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
    FYFX
    May 1, 2024
    65
    你是 order2 种值,prop 3 种值组合总共 6 种,我是觉得把 6 种可能枚举出来比较好,先判断 order 再判断 prop 感觉没那么清晰
    mrytsr
    mrytsr
    May 1, 2024 via Android
    66
    没搞懂为什么要把 prop 和 order 转成 sorttype ,建议直接存储或传输 prop,order
    pennai
    pennai
    May 1, 2024 via Android
    67
    1.可以配在 db 里,这样一行查 db 然后一行赋值 sort type 就行
    2.策略模式实现
    3.上规则引擎
    nuk
    nuk
    May 2, 2024
    68
    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
    shyangs
    May 2, 2024
    69
    @z1829909

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

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

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

    ```
    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
    bv
    May 2, 2024
    75
    下面这样,有点为了优化而优化,让人难以理解了:
    function onSortChange(order, prop) {
    let props = new Map([
    ["thisYearIncome", 1],
    ["lastYearIncome", 3],
    ["rate", 5],
    ]);

    this.fetchData((order === "descending" ? 0 : 1) + props.get(prop))
    }
    netabare
    netabare
    May 3, 2024
    76
    表驱动。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5020 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 199ms · UTC 07:10 · PVG 15:10 · LAX 23:10 · JFK 02:10
    ♥ Do have faith in what you're doing.