【问题标题】:Angular1/JavaScript - Improve algo conditionAngular1/JavaScript - 改进算法条件
【发布时间】:2017-10-12 08:54:00
【问题描述】:
我有这个条件,它验证对象projectType 的相同属性labelKey 并根据属性的值返回不同的值
checkProjectType () {
if (this.projectType.labelKey === 'project_type.rent') {
return 'geographical_area'
} else if (this.projectType.labelKey === 'project_type.buying') {
return 'geographical_area'
} else {
return 'address'
}
}
由于条件过于相似,我如何使用 Lodash 或 ECMAScript 2015 简化写入来重构/优化条件?
【问题讨论】:
标签:
javascript
angularjs
ecmascript-6
lodash
【解决方案1】:
您可以根据您的代码将其减少到更少的条件。
checkProjectType () {
var labelKey = this.projectType.labelKey;
if (labelKey === 'project_type.rent' || labelKey === 'project_type.buying') {
return 'geographical_area';
}
return 'address';
}
不确定你想在这里用 lodash 做什么
【解决方案2】:
我也不喜欢if-else-if… 链,所以更喜欢更易读的变体。
function checkProjectType() {
const defaultType = 'address';
const key = this.projectType.labelKey;
let map = {
'project_type.rent': 'geographical_area',
'project_type.buying': 'geographical_area'
};
return map[key] || defaultType;
}
map 可以在其他地方定义。
【解决方案3】:
设置 if do X else if do X else do Y 对我来说是错误的,您可以将其简化为一行: if (this.projectType.labelKey === 'project_type.rent' || this.projectType. labelKey === 'project_type.buying') 已经更容易阅读了。
【解决方案4】:
另一种写法是使用switch 语句:
switch (this.projectType.labelKey) {
case 'project_type.rent':
case 'project_type.buying':
return 'geographical_area';
default:
return 'address';
}
但有人可能会争辩说,在这种情况下这有点矫枉过正。 Lodash 或 ECMAScript 2015 在这里不会为您做任何事情。
【解决方案5】:
您可以检查项目类型是否包含在类型数组中,并使用三元来选择响应:
checkProjectType() {
return ['project_type.rent', 'project_type.buying'].includes(this.projectType) ? 'geographical_area' : 'address';
}
如果产生geographical_area的类型,您可以将它们重构出方法(和对象/类):
const geoTypes = ['project_type.rent', 'project_type.buying'];
checkProjectType() {
return geoTypes.includes(this.projectType) ? 'geographical_area' : 'address';
}