174. CSS Grid Layout auto-placement algorithm - sparse
Share
few challengers - accepted / - tried
Are you familiar with CSS Grid Layout ?
grid-auto-flow controls how the auto-placement algorithm works.
Default packing mode is sparse
, please create a function to illustrate how it works.
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 {
// your code here
}
- it should return a grid of item id, use 0 if the cell is no occupied.
- implement the logic based on
grid-auto-flow: row
. - all inputs are valid, in which there is no overlapping between the items, and all items stay fully inside of the grid.
- you can refer to the office algorithm explanation
Here are some examples you can understand it better.
layout(3, 3, [
{
id: 1,
style: {
gridColumnStart: 'span 2'
}
},
{
id: 2,
style: {
gridColumnStart: 'span 2'
}
},
{
id: 3
},
{
id: 4
},
{
id: 5
}
])
/**
[
[1, 1, 0],
[2, 2, 3],
[4, 5, 0]
]
*/
In the above example, all items are auto placed.
layout(3, 3, [
{
id: 1,
style: {
gridColumnStart: 'span 2',
gridRowStart: 2
}
},
{
id: 2,
style: {
gridColumnStart: 2,
gridColumnEnd: 'span 2'
}
},
{
id: 3
},
{
id: 4
},
{
id: 5
}
])
/**
[
[0, 2, 2],
[1, 1, 3],
[4, 5, 0]
]
*/
Now in above example first two items have more specific positions.