表驱动模式应用场景
如果你的代码有很多 if … else …结构,你不知道怎么优化,你就应该使用表驱动编程。
善用map哈希表的数据结构,js对象也就是字典,设置obj={key:value},通过obj[key]取出值,代替if…else…或者switch…case…等逻辑
数组中单层判断的应用
优化前:
howManyDays(month,days){
if(month === 1 ||
month === 3 ||
month === 5 ||
month === 7 ||
month === 8 ||
month === 10 ||
month === 12
){
return 31
}else if(month === 2){
return isLeapYear(month) ? 29 : 28
}else{
return 30
}
}
优化后
howManyDays(month,days){
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(month) ? 29 : 28
}
return table[days]
}
优化前:
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']
}
优化前
function iGetMonthDays(iMonth) {
let iDays;
if(1 == iMonth) {iDays = 31;}
else if(2 == iMonth) {iDays = 28;}
else if(3 == iMonth) {iDays = 31;}
else if(4 == iMonth) {iDays = 30;}
else if(5 == iMonth) {iDays = 31;}
else if(6 == iMonth) {iDays = 30;}
else if(7 == iMonth) {iDays = 31;}
else if(8 == iMonth) {iDays = 31;}
else if(9 == iMonth) {iDays = 30;}
else if(10 == iMonth) {iDays = 31;}
else if(11 == iMonth) {iDays = 30;}
else if(12 == iMonth) {iDays = 31;}
return iDays;
}
优化后
const monthDays = [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
]
function getMonthDays(month, year) {
let isLeapYear = (year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0) ? 1 : 0
return monthDays[isLeapYear][(month - 1)];
}
console.log(getMonthDays(2, 2000))
数组中多层判断的应用
优化前
if (a == 1) {
if (b == 20) {
return true;
} else if (b == 30) {
return true;
}
} else if ((a == 3)) {
if (b == 10) {
return true;
} else if (b == 40) {
return true;
}
}
优化后
1.创建表
const terms = {
1: { 20: true, 30: true, },
3: { 10: true, 40: true, },
};
2.返回值
return terms[a][b] ? true: false
对象中使用
优化前
if (key = "Key A")
{
处理 Key A 相关的数据。
执行 Key A 相关的行为。
}
else if (key = "Key B")
{
处理 Key B 相关的数据。
执行 Key A 相关的行为。
}
优化后
let table = {
A: {
data: "数据1",
action () {
console.log('action 1')
}
},
B: {
data: "数据2",
action () {
console.log('action 2')
}
}
}
function handleTable(key) {
return table[key]
}
handleTable('A').action()
总结:我理解的表编程思想的核心就是利用变量自身的属性,存储所需内容,然后通过相关操作得到所需的内容。