我首先声明一下我的函数全部为函数式 我注重返回值
以下部分技巧是实践中得来,还有从 [《JavaScript设计模式与开发实践》]- 作者:曾探学习到
// 技巧一 提前中止
const getEvaluate = (score) => {
if (score >= 3) {
return 'A'
} else {
return 'B'
}
}
// 我对代码就一个评价 直观 代码非常直观
// 当跟提前中止组合代码就成了
const getEvaluate = (score) => {
if (score >= 3) {
return 'A'
}
return 'B'
}
// 技巧二 用对象中键值对作为映射 适用场景多个if else
const getEvaluate = (score) => {
if (score === 5) {
return 'A'
} else if (score === 4) {
return 'B'
} else if (score === 3) {
return 'C'
} else if (score === 2) {
return 'D'
}
return 'E'
}
// 问题1 无法应该扩展
// 问题2 应对扩展需要更改运算逻辑
const scoreToEvaluteMap = {
1: 'E',
2: 'D',
3: 'C',
4: 'B',
5: 'A'
}
const getEvaluate = (score) => {
return scoreToEvaluteMap[score]
}
// 那天多了一个6 对应 A+
const scoreToEvaluteMap = {
1: 'E',
2: 'D',
3: 'C',
4: 'B',
5: 'A',
6: 'A+'
}
// 现在应对的只是简单的映射 函数逻辑映射呢
// 假设有几种优惠,怎么算出最优惠的
// 1.满1000直减200
// 2.满1000打0.85折
// 3.满300减60
const getDiscount = (money) => {
let discount = 0
// 1.满1000直减200
// 2.满1000打0.85折
if (money >= 1000) {
discount = Math.max(money*(1-0.85), Math.trunc(money / 1000) * 200)
// 3.满300减60
} else if (money >= 300) {
discount = money - 60
}
return discount
}
// 代码看起来还行 但是某一天又有一种优惠策略完蛋
把if else 变成策略
const getDiscountByStrategy1 = (money) => {
if (money < 1000) {
return 0
}
return Math.trunc(money / 1000) * 200
}
const getDiscountByStrategy2 = (money) => {
if (money < 1000) {
return 0
}
return money*(1-0.85)
}
const getDiscountByStrategy3 = (money) => {
if (money < 300) {
return 0
}
return money - 60
}
const getDiscount = (money) => {
return Math.max.call(null, getDiscountByStrategy1(money), ...)
}
暂时只想到这么多if else的 如果有代码希望一起学习 可以发出来