Created
July 7, 2017 21:13
-
-
Save realityking/b2e5b7feb38b30fe7c29ef6086489032 to your computer and use it in GitHub Desktop.
Lyn posing weird questions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var table1 = [ | |
[{content: 'r0c0'}, {content: 'r0c1'}, {content: 'r0c2', colSpan: 2, rowSpan: 3}, {content: 'r0c4'}], | |
[{content: 'r1c0', colSpan: 2, rowSpan: 2}, {content: 'r1c4'}], | |
[{content: 'r2c4'}], | |
[{content: 'r3c0'}, {content: 'r3c1'}, {content: 'r3c2'}, {content: 'r3c3'}, {content: 'r3c4'}] | |
]; | |
var table2 = [ | |
[{rowSpan: 2, content: 'r0c0'}, {rowSpan: 2, content: 'r0c1'}, {content: 'r0c2'}, {content: 'r0c3'}], | |
[{content: 'r1c2'}, {content: 'r1c3'}] | |
]; | |
table1.push([{rowSpan: 2, content: 'r0c0'}, {rowSpan: 2, content: 'r0c1'}, 'r0c2', 'r0c3']); | |
table1.push(['r1c2', 'r1c3']); | |
function createCell(cell) { | |
return { | |
content: cell.content, | |
rowSpan: cell.rowSpan || 1, | |
colSpan: cell.colSpan || 1 | |
} | |
} | |
function hasConflict(outputTable, cell) { | |
for (var y = cell.y; y >= 0; y--) { | |
var row = outputTable[y]; | |
for (var x = 0; x < row.length; x++) { | |
var cmpCell = row[x]; | |
// Short circuit if they'd occupy the same space | |
if (cmpCell.x === cell.x && cmpCell.y === cell.y) { | |
return true; | |
} | |
// Test if they're withing the space of another cell | |
var inXRange = cmpCell.x <= cell.x && cmpCell.x + (cmpCell.colSpan - 1) >= cell.x; | |
var inYRange = cmpCell.y <= cell.y && cmpCell.y + (cmpCell.rowSpan - 1) >= cell.y; | |
if (inXRange && inYRange) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
function magic(table) { | |
var outputTable = []; | |
table.forEach(function (row, rowIndex) { | |
outputTable[rowIndex] = []; | |
var columnCount = 0; | |
row.forEach(function (origCell) { | |
var offset = 0; | |
var cell = createCell(origCell); | |
cell.x = columnCount; | |
cell.y = rowIndex; | |
while (hasConflict(outputTable, cell)) { | |
offset++; | |
cell.x++; | |
} | |
outputTable[rowIndex].push(cell); | |
columnCount += cell.colSpan + offset; | |
}) | |
}); | |
return outputTable; | |
} | |
console.log('table1'); | |
console.log(magic(table1)); | |
console.log('table2'); | |
console.log(magic(table2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment