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

如何精简这段多条件分支代码的行数与复杂度?

代码精简方案

优化后的代码

// 建立筛选类型与日期范围的映射表
const filterDateMap = {
  Day: { gt: current_date },
  Week: { gte: startofweek_date, lte: endofweek_date },
  Month: { gte: startOfMonth_date, lte: endOfMonth_date },
  Year: { gte: startOfYear_date, lte: endOftheYear_date },
  custom: { gte: custom_start_date, lt: custom_end_date }
};

// 处理custom分支的特殊graph_data赋值(仅无location_id时生效)
if (filter_by === 'custom' && location_id === '') {
  graph_data = [1, 2, 3, 4, 5, 7, 3, 12, 4, 2, 5, 6];
}

// 构建基础查询对象
const query = {
  created_at: filterDateMap[filter_by],
  ref: headerData?.ref
};

// 存在location_id时追加该字段
if (location_id !== '') {
  query.location_id = location_id;
}

// 特殊处理custom分支:无location_id时移除ref字段(匹配原逻辑)
if (filter_by === 'custom' && location_id === '') {
  delete query.ref;
}

优化思路

  1. 映射表替代多分支判断:把filter_by对应的日期条件整理成对象映射,彻底消除重复的if-else嵌套,后续新增筛选类型只需在映射表中添加条目,维护成本更低。
  2. 提取公共逻辑:将所有分支中重复的ref、location_id字段提取出来统一处理,避免重复编写相同的对象结构。
  3. 剥离特殊逻辑:把custom分支中仅在无location_id时生效的逻辑单独抽离,让主逻辑更简洁线性。
  4. 降低复杂度:原代码的双层嵌套结构被拆解为线性逻辑,代码行数大幅减少,可读性和可维护性显著提升。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:55:16