const fillTableCells = (array, totalColumn) => {
let result = [];
let tableCells = [];
let tableRow = 0;
function cellCoordinates(rowspan, colspan, index) {
if (!tableCells[tableRow]) {
// 判断当前行是否存在,不存在则插入新行
insertRow();
}
let row = tableCells[tableRow]; // 当前行
// 获取起始列
let startCol = getStartCol(row, colspan);
// 起始列存在说明可以填充
if (startCol != null) {
// 填充数据
if (rowspan > 1) {
for (let i = 0; i < rowspan; i++) {
if (!tableCells[tableRow + i + 1]) {
insertRow();
}
}
}
// 循环行
for (let r = tableRow; r < tableRow + rowspan; r++) {
// 循环列
for (let c = startCol; c < startCol + colspan; c++) {
tableCells[r][c] = index;
}
}
return { startRow: tableRow, endRow: tableRow + rowspan, startCol: startCol, endCol: startCol + colspan };
} else {
// 移入下一行查找
tableRow++;
return cellCoordinates(rowspan, colspan, index);
}
}
function getStartCol(row, colspan) {
let count = 0;
for (let i = 0; i < row.length; i++) {
if (!row[i]) {
// 不存在说明还未填充
count++;
} else {
// 重置
count = 0;
}
if (count == colspan) {
return i - colspan + 1;
}
}
return null;
}
// 插入新行
function insertRow() {
let row = new Array(totalColumn).fill(0);
tableCells.push(row);
}
for (let i = 0; i < array.length; i++) {
const { rowspan, colspan } = array[i];
// 所占列数不能大于总列数;大于默认重置为1
if (colspan > totalColumn) {
colspan = 1;
}
const { startRow, startCol, endRow, endCol } = cellCoordinates(rowspan, colspan, i + 1);
result.push({
startRow: startRow + 1,
startCol: startCol + 1,
endRow: endRow + 1,
endCol: endCol + 1,
});
}
console.log(tableCells);
return result;
};
// 一维数组
let oneDimensionalArray = [
{ rowspan: 2, colspan: 2 },
{ rowspan: 1, colspan: 3 },
{ rowspan: 1, colspan: 1 },
{ rowspan: 3, colspan: 1 },
];
// 总列数
let totalColumns = 5;
let cellCoordinates = fillTableCells (oneDimensionalArray, totalColumns);
console.log(cellCoordinates )