如何简化数字输入范围校验的if/else判断逻辑?
重构方案及优化建议
先修复原代码的潜在问题
你原来的代码里用!!min/!!max判断属性是否存在,这会导致min/max为0时被误判为不存在(因为!!0 === false),这是个隐性bug。正确的判断应该是检查值是否为undefined(或结合null,根据你的实际场景),比如typeof min !== 'undefined'。
重构方案1:分离判断与消息构建
把违规判断和提示消息生成拆分开,逻辑更清晰,避免重复判断:
// 先判断是否触发了min/max违规 const isBelowMin = typeof min !== 'undefined' && val < min; const isAboveMax = typeof max !== 'undefined' && val > max; if (isBelowMin || isAboveMax) { let message = 'Enter a number'; if (isBelowMin && isAboveMax) { message += ` between ${min} and ${max}`; } else if (isBelowMin) { message += ` greater than ${min}`; } else { message += ` less than ${max}`; } print(message); }
重构方案2:紧凑的三元表达式写法
如果追求代码简洁,且可读性不受影响,可以用嵌套三元表达式直接生成消息:
const isBelowMin = typeof min !== 'undefined' && val < min; const isAboveMax = typeof max !== 'undefined' && val > max; if (isBelowMin || isAboveMax) { print(`Enter a number ${ isBelowMin && isAboveMax ? `between ${min} and ${max}` : isBelowMin ? `greater than ${min}` : `less than ${max}` }`); }
重构方案3:配置化映射(适合扩展更多规则)
如果后续可能增加更多输入校验规则,可以用配置对象来管理条件和对应消息,扩展性更强:
const validationRules = [ { condition: () => typeof min !== 'undefined' && typeof max !== 'undefined' && (val < min || val > max), message: `Enter a number between ${min} and ${max}` }, { condition: () => typeof min !== 'undefined' && val < min, message: `Enter a number greater than ${min}` }, { condition: () => typeof max !== 'undefined' && val > max, message: `Enter a number less than ${max}` } ]; // 找到第一个匹配的规则并打印消息 const matchedRule = validationRules.find(rule => rule.condition()); if (matchedRule) { print(matchedRule.message); }
内容的提问来源于stack exchange,提问作者Katie
相关产品推荐
相关产品推荐

