我有一系列要改變爲一系列行的點。使用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