I have a series of points that I want to change into a series of lines.
this is an example of what I want to the code do
[p1, p2, p3] -> [line1, line2]
each loop:
(p1, p2) -> line
(p2, p3) -> line
The standard way to do this is:
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
})
}
This is the closes I can get using Array.prototype.reduce
. But it feels much harder to reason about
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 )
In short, is there a better way to use reduce to combine N
inputs into N - 1
outputs?
Sure, use the currentIndex
argument to apply an offset. Your callback function receives several more arguments1 than you're using:
[{x:0, y:0}, {x:0, y:1}, {x:1, y:2}].reduce((lines, point, currentIndex, source) => {
currentIndex < source.length -1 && lines.push({
from: point,
to: source[currentIndex + 1]
});
return lines;
}, []);
1See Array.prototype.reduce()
for more info.