テーブル駆動型プログラミング

コードが複数ある場合...他に...構造、テーブル駆動型プログラミングの最適化。
例えば:


优化前:
howManyDays(year, month){
    if(month === 1 ||
        month === 3 ||
        month === 5 ||
        month === 7 ||
        month === 8 ||
        month === 10 ||
        month === 12
    ){
        return 31
    }else if(month === 2){
        return isLeapYear(year) ? 29 : 28
    }else{
        return 30
    }
}

优化后:
howManyDays(year, month){
    const table = {
        1: 31, 3: 31, 5: 31, 7: 31, 8: 31, 10: 31, 12:31,
        4: 30, 6:30, 9: 30, 11: 30,
        2: isLeapYear(year) ? 29 : 28
    }
    return table[month]
}

优化前:
function calculateGrade(score){
    if(score>=90){
        return 'A'
    }else if(score >= 80){
        return 'B'
    }else if(score >= 70){
        return 'C'
    }else if(score >= 60){
        return 'D'
    }else {
        return 'E'
    }
}

优化后:
function calculateGrade(score){
    const table = {
        100: 'A', 
        90: 'A',
        80: 'B',
        70: 'C',
        60: 'D',
        others: 'E'
    }
    return table[Math.floor(score/10)*10] || table['others']
}

参考リンクします。https://www.zhihu.com/searchタイプ=コンテンツ& Q =%E9%A1%B9%E7%9B%AE%E5%89%8D%E7%AB%AF%E4%BB%A3%? E7%でA0の%81%E4%での BCの%98%E5%8C%96

公開された80元の記事 ウォン称賛82 ビュー10000 +

おすすめ

転載: blog.csdn.net/qq_42893625/article/details/103922079