如何实现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
相关产品推荐
相关产品推荐

