You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

冗余告警状态判断JS代码如何通过映射等方式精简重构

优化建议

你的判断是对的,用映射表抽离重复逻辑是最优解法。这段代码的重复点在于3种告警级别的取值、图标匹配逻辑完全一致,仅级别名称、对应图标名有差异,我们可以把差异化参数抽成配置映射,统一遍历生成所有状态变量。

优化步骤

  • 第一步:定义告警级别配置映射,集中存放所有差异化参数
  • 第二步:统一遍历映射生成所有状态,避免重复写R.path取值、三元判断逻辑
  • 第三步:如果需要保留原变量名,直接从生成的对象中解构即可

重构后代码示例

// 1. 定义级别映射配置,后续新增告警级别仅需在此处添加条目
const ALERT_LEVEL_CONFIG = {
  CRITICAL: {
    outlineIcon: allIcons.LMAlertSeverityCriticalOutline20Px,
    filledIcon: allIcons.LMAlertsCritical20Px
  },
  ERROR: {
    outlineIcon: allIcons.LMAlertSeverityErrorOutline20Px,
    filledIcon: allIcons.LMAlertsError20Px
  },
  WARNING: {
    outlineIcon: allIcons.LMAlertSeverityWarningOutline20Px,
    filledIcon: allIcons.LMAlertsWarning20Px
  }
}

// 2. 遍历配置生成所有状态
const alertStatus = Object.entries(ALERT_LEVEL_CONFIG).reduce((res, [level, config]) => {
  // 统一取isAlertingEnabled状态,兼容原有CRITICAL的特殊取值逻辑
  const isAlertingEnabled = level === 'CRITICAL' 
    ? isCriticalAlertingEnabled
    : R.path(['children', level, 'isAlertingEnabled'], props)
  // 统一取isStaticAlertSuppressed状态
  const isStaticAlertSuppressed = R.path(['children', level, 'isStaticAlertSuppressed'], props)
  
  // 生成对应状态
  res[`${level}AlertStatus`] = isAlertingEnabled ? config.outlineIcon : Disabled
  res[`${level}StaticAlertStatus`] = isStaticAlertSuppressed ? config.filledIcon : Disabled
  return res
}, {})

// 3. 解构得到和原来完全一致的变量,不影响原有代码调用
const {
  CRITICALAlertStatus: CriticalAlertStatus,
  CRITICALStaticAlertStatus: CriticalStaticAlertStatus,
  ERRORAlertStatus: ErrorAlertStatus,
  ERRORStaticAlertStatus: ErrorStaticAlertStatus,
  WARNINGAlertStatus: WarningAlertStatus,
  WARNINGStaticAlertStatus: WarningStaticAlertStatus
} = alertStatus

补充说明:如果你原有代码里的isCriticalAlertingEnabled实际也是从props.children.CRITICAL.isAlertingEnabled取值的,可删除reduce中的三元判断,统一用R.path(['children', level, 'isAlertingEnabled'], props)取值即可,逻辑会更统一。

优化收益

  • 代码量减少60%以上,无重复冗余逻辑
  • 后续新增告警级别仅需在ALERT_LEVEL_CONFIG中添加1条配置,无需复制粘贴重复逻辑,避免人为失误
  • 所有公共逻辑收敛到一处,后续调整规则(比如图标规则、取值路径)仅需修改一次即可全局生效

内容的提问来源于stack exchange,提问作者arpartch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:15:04