2017-03-07 64 views
4

我有一系列要改变为一系列行的点。使用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产出更好的办法?

+0

你的问题是什么? –

+0

请添加一个想要的结果和数据结构。 –

+0

道歉,我更新了问题 – andykais

回答

1

当然,使用currentIndex参数来应用偏移量。比您正在使用你的回调函数接收几个参数:

[{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;  
}, []); 

更多信息,请参见Array.prototype. reduce()

+0

如果点被定义在数组之外,我可能更喜欢https://jsfiddle.net/qxdsgddu/ – seveibar

+1

@seveibar肯定,但如果我们走得那么远,我会说完全跳过数组方法,然后循环。我们并没有从'reduce()'中获得任何提升...更不用说复制数组的一个子集进行处理了。无论如何,这只是一个概念演示。 – canon

相关问题