2017-03-07 65 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

相關問題