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

如何实现colorFence函数计算栅栏剩余未涂色长度并理解其返回函数入参逻辑

问题解答

为什么colorIntervals可以接收两个入参

colorFence是JavaScript中的高阶函数,它的返回值本身就是一个预先定义为接收left、right两个入参的函数。将返回的函数赋值给colorIntervals变量后,调用colorIntervals本质就是调用这个被返回的函数,自然支持传入两个参数。

完整实现代码

function colorFence(length) {
  // 内部维护未涂色的白色区间列表,初始为整个栅栏范围
  let whiteIntervals = [[0, length - 1]]
  // 记录剩余白色栅栏总长度
  let remainingLength = length

  // 返回接收left、right参数的涂色函数
  return function (left, right) {
    const updatedWhite = []
    // 本次需要扣除的涂色长度
    let deducted = 0

    for (const [start, end] of whiteIntervals) {
      // 区间完全不重叠,直接保留原白色区间
      if (end < left || start > right) {
        updatedWhite.push([start, end])
        continue
      }
      // 计算重叠部分长度
      const overlapStart = Math.max(start, left)
      const overlapEnd = Math.min(end, right)
      deducted += overlapEnd - overlapStart + 1

      // 保留重叠区域左侧剩余的白色部分
      if (start < overlapStart) {
        updatedWhite.push([start, overlapStart - 1])
      }
      // 保留重叠区域右侧剩余的白色部分
      if (end > overlapEnd) {
        updatedWhite.push([overlapEnd + 1, end])
      }
    }

    // 更新白色区间和剩余长度
    whiteIntervals = updatedWhite
    remainingLength -= deducted
    return remainingLength
  }
}

调用测试

和给出的示例运行结果完全一致:

const colorIntervals = colorFence(20);

colorIntervals(18, 18); // 返回19
colorIntervals(0, 3); // 返回15
colorIntervals(17, 19); // 返回13
colorIntervals(0, 19); // 返回0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:24:07