This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
174. CSS Grid Layout auto-placement algorithm - sparse
Here's one possible solution to the problem:
type Grid = Array<Array<number>>
type Item = {
id: number,
style?: {
gridRowStart?: number | string,
gridRowEnd?: number | string,
gridColumnStart?: number | string
gridColumnEnd?: number | string
}
}
function layout(rows: number, columns: number, items: Array<Item>): Grid {
const grid: Grid = Array.from({ length: rows }, () => Array.from({ length: columns }, () => 0))
let row = 1
let col = 1
for (const item of items) {
if (item.style?.gridRowStart && typeof item.style.gridRowStart === 'number') {
row = item.style.gridRowStart
}
if (item.style?.gridColumnStart && typeof item.style.gridColumnStart === 'number') {
col = item.style.gridColumnStart
}
const width = item.style?.gridColumnEnd
? getSpan(item.style.gridColumnEnd) - col + 1
: 1
const height = item.style?.gridRowEnd
? getSpan(item.style.gridRowEnd) - row + 1
: 1
for (let r = row; r < row + height; r++) {
for (let c = col; c < col + width; c++) {
grid[r-1][c-1] = item.id
}
}
col += width
if (col > columns) {
col = 1
row++
}
}
return grid
}
function getSpan(span: string): number {
const parts = span.split(' ')
if (parts.length !== 2 || parts[1] !== 'span') {
throw new Error(`Invalid grid span value: ${span}`)
}
const value = parseInt(parts[0], 10)
if (isNaN(value)) {
throw new Error(`Invalid grid span value: ${span}`)
}
return value
}
Here's how it works:
- The
layout
function initializes an empty grid of the specified size and iterates through the list of items to place them in the grid. - For each item, it extracts the
gridRowStart
,gridRowEnd
,gridColumnStart
, andgridColumnEnd
values from itsstyle
field (if present), and uses them to compute the item's position and size in the grid. - The item is then added to the grid by setting the corresponding cells to its id value.
- Finally, the function returns the completed grid.
Note that the function assumes that all items have valid, non-overlapping positions within the grid. If this is not the case, the results may be incorrect.