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

JavaScript实现数值范围重叠检测及重叠占比计算需求

数值范围重叠检测并返回重叠占比

原代码仅能判断两个数值区间是否重叠,要实现重叠时返回0-100%的重叠占比,可按以下思路修改:

核心逻辑

  1. 先判断区间是否重叠(沿用原代码的重叠判断逻辑)
  2. 若重叠,计算重叠区间长度:取两个区间起始值的较大值作为重叠起点,取两个区间结束值的较小值作为重叠终点,两者差值即为重叠长度
  3. 计算占比:用重叠长度除以目标区间的总长度,再乘以100得到百分比(可选择相对于前一个区间、当前区间,或同时返回两者)

修改后的完整代码

function checkOverlapWithPercentage(prevHighLow, currentHighLow) {
  const [a, b] = prevHighLow; // 前一个区间的起止值
  const [c, d] = currentHighLow; // 当前区间的起止值

  // 计算重叠区间的起止边界
  const overlapStart = Math.max(a, c);
  const overlapEnd = Math.min(b, d);

  // 判断是否存在重叠
  if (overlapStart < overlapEnd) {
    const overlapLength = overlapEnd - overlapStart;
    // 计算相对于前一个区间的重叠占比(保留两位小数)
    const percentagePrev = ((overlapLength / (b - a)) * 100).toFixed(2);
    // 计算相对于当前区间的重叠占比(保留两位小数)
    const percentageCurrent = ((overlapLength / (d - c)) * 100).toFixed(2);
    
    return {
      isOverlapping: true,
      overlapPercentageAgainstPrev: `${percentagePrev}%`,
      overlapPercentageAgainstCurrent: `${percentageCurrent}%`
    };
  }

  return { isOverlapping: false, overlapPercentage: '0%' };
}

// 测试示例
const prevHighLow = [12350, 12900];
const currentHighLow = [12100, 12800];

console.log(checkOverlapWithPercentage(prevHighLow, currentHighLow));
// 输出结果:
// {
//   isOverlapping: true,
//   overlapPercentageAgainstPrev: "81.82%",
//   overlapPercentageAgainstCurrent: "64.29%"
// }

代码说明

  • 用解构赋值简化变量获取,提升代码可读性
  • overlapStart和overlapEnd确保准确锁定重叠区间范围
  • toFixed(2)用于格式化百分比,保留两位小数(可根据需求调整位数)
  • 返回对象包含明确的状态和占比信息,便于后续业务处理

如果仅需返回相对于单个区间的占比,可简化代码:

function checkOverlapWithPercentage(prevHighLow, currentHighLow) {
  const [a, b] = prevHighLow;
  const [c, d] = currentHighLow;

  const overlapStart = Math.max(a, c);
  const overlapEnd = Math.min(b, d);

  if (overlapStart < overlapEnd) {
    const overlapLength = overlapEnd - overlapStart;
    const percentage = ((overlapLength / (b - a)) * 100).toFixed(2);
    return { isOverlapping: true, overlapPercentage: `${percentage}%` };
  }

  return { isOverlapping: false, overlapPercentage: '0%' };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:00:24