Skip to content

Instantly share code, notes, and snippets.

@nickovchinnikov
Last active June 20, 2018 11:02
Show Gist options
  • Save nickovchinnikov/e4969cf9754448a4b5561195b77e46e2 to your computer and use it in GitHub Desktop.
Save nickovchinnikov/e4969cf9754448a4b5561195b77e46e2 to your computer and use it in GitHub Desktop.
const MockData = require('./MockData')
const formatColumns = (data, columnLength = 6) => {
const pushItem = ({ boardMatrix = [], columnCursor = 0, rowCursor = 0, currentItem }) => {
const currentArrayItem = boardMatrix[columnCursor]
if (!currentArrayItem) {
boardMatrix[columnCursor] = [currentItem]
} else {
boardMatrix[columnCursor][rowCursor] = currentItem
}
return {
columnCursor,
rowCursor: ++rowCursor,
boardMatrix
}
}
const pushTailItem = (boardMatrix, columnCursor, rowCursor, tailItem) => {
const arrayColumn = boardMatrix[columnCursor]
if (!arrayColumn) {
boardMatrix[columnCursor] = []
}
const arrayItem = boardMatrix[columnCursor][rowCursor]
if (!arrayItem) {
boardMatrix[columnCursor][rowCursor] = tailItem
return boardMatrix
}
return pushTailItem(boardMatrix, columnCursor + 1, rowCursor, tailItem)
}
const { boardMatrix: result } = data.reduce((resultObject, currentItem) => {
const { columnCursor = 0, rowCursor = 0, boardMatrix = []} = resultObject
const columnExists = boardMatrix[columnCursor]
const boardMatrixPrevItem = columnExists && boardMatrix[columnCursor][rowCursor - 1]
const boardMatrixCurrentItem = columnExists && boardMatrix[columnCursor][rowCursor]
const winningHandIsChanged = boardMatrixPrevItem && boardMatrixPrevItem.WinningHand !== currentItem.WinningHand
if (winningHandIsChanged || !boardMatrixPrevItem) {
return pushItem({
...resultObject,
columnCursor: winningHandIsChanged ? columnCursor + 1 : columnCursor,
rowCursor: winningHandIsChanged ? 0 : rowCursor,
currentItem
})
}
if (rowCursor === columnLength - 1 || boardMatrixCurrentItem) {
return {
columnCursor,
rowCursor,
boardMatrix: pushTailItem(
boardMatrix,
columnCursor + 1,
boardMatrixCurrentItem ? rowCursor - 1 : rowCursor,
currentItem
)
}
}
return pushItem({
...resultObject,
currentItem
})
}, {})
return result
}
const result = formatColumns(MockData, 6)
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment