有没有办法简化这个或我可以使用的更简洁的形式?包含的逻辑都是正确的。它看起来好像很多return
和else if
。
mode = (function(mode, current, proposed, origins, destinations) {
if (mode === 'none') {
return 'project';
} else if (proposed.count === 0) {
return 'unseated';
} else if (current.count > proposed.count && proposed.count > 0) {
return 'reducing';
} else if (proposed.count === destinations.count && destinations.count > 1 && current.count === 0) {
return 'newplus';
} else if (proposed.count === destinations.count && current.count === 0) {
return 'new';
} else if (proposed.count > destinations.count) {
return 'increasing';
} else if (proposed.count === destinations.count && destinations.count > origins.count) {
return 'moveplus';
} else {
return 'move';
}
}(moves.register[staff].move, {count: mode.currentDesks}, {count: mode.proposedDesks}, {count: mode.origins}, {count: mode.destinations})));
我之前使用过嵌套的三元缩写,但是我认为更容易出错并且难以阅读(由于代码演变而导致的结果略有不同): p>
mode =
(moves.register[staff].move === 'none') ? 'project' :
(mode.proposedDesks === 0) ? 'unseated' :
(mode.currentDesks > mode.proposedDesks && mode.proposedDesks > 0) ? 'reducing' :
(mode.proposedDesks === mode.destinations && mode.destinations > 1 && mode.currentDesks === 0) ? 'newplus' :
(mode.proposedDesks === mode.destinations && mode.currentDesks === 0) ? 'new' :
(mode.proposedDesks > mode.destinations) ? 'additional' :
(mode.proposedDesks === mode.destinations && mode.destinations === mode.origins) ? 'move' :
(mode.proposedDesks === mode.destinations && mode.destinations > mode.origins) ? 'moveplus' :
'other';
因此,虽然我喜欢if…then…elseif
堆栈的易读性,但感觉它比它更加冗长。由于比较变量的数量,我不认为我正在寻找switch…case
版本并没有完全削减它,并且在if
内嵌套switch…case
语句感觉不对或if…then…else
内的三元运算符。
我本能地想,我想要一种矩阵形式,其中返回值在网格中,并且以某种方式对各种按位条件的矩阵计算返回正确的结果。我怀疑这将是一个紧凑的代码胜过易读性的胜利。
有什么建议吗?
NB。为了易读性,选择变量名称,包括向每个变量添加count属性,而不是指定变量,或者不指示它是计数。
答案 0 :(得分:0)
您可以使用var存储您的选择并在最后返回
mode = (function(mode, current, proposed, origins, destinations) {
var varName='move';
if (mode === 'none') {
varName='project';
} else if (proposed.count === 0) {
varName='unseated';
} else if (current.count > proposed.count && proposed.count > 0) {
varName= 'reducing';
} else if (proposed.count === destinations.count && destinations.count > 1 && current.count === 0) {
varName= 'newplus';
} else if (proposed.count === destinations.count && current.count === 0) {
varName='new';
} else if (proposed.count > destinations.count) {
varName= 'increasing';
} else if (proposed.count === destinations.count && destinations.count > origins.count) {
varName= 'moveplus';
}
}(moves.register[staff].move, {count: mode.currentDesks}, {count: mode.proposedDesks}, {count: mode.origins}, {count: mode.destinations})));