我有一系列要改变为一系列行的点。使用javascript数组减少给定的n个输入产生m个输出
这是我想要的代码示例不
[p1, p2, p3] -> [line1, line2]
每次循环:
(p1, p2) -> line
(p2, p3) -> line
做到这一点的标准方法是:
const triangle = [[0,0], [0,1], [1,2]]
const lines = []
for (let i = 1; i < triangle.length; ++i) {
const slope = findSlopeFromPoints(...triangle[i - 1], ...triangle[i])
const yIntercept = findYIntercept(...triangle[i], slope)
lines.push({
slope,
yIntercept
})
}
这是关闭我可以使用Array.prototype.reduce
。但感觉更难推理
const initial = {
array: [], // actual returned array we care about
lastPoint: null // "triangle[i - 1]"
}
const linesR = triangle.reduce((lines, point) => {
if (lines.lastPoint === null)
return {
...lines,
lastPoint: point
}
else {
const slope = findSlopeFromPoints(...lines.lastPoint, ...point)
const yIntercept = findYIntercept(...point, slope)
lines.array.push({
slope,
yIntercept
})
lines.lastPoint = point
return lines
}
}, initial)
总之,是有办法使用减少N
投入组合成N - 1
产出更好的办法?
你的问题是什么? –
请添加一个想要的结果和数据结构。 –
道歉,我更新了问题 – andykais