Skip to content

Instantly share code, notes, and snippets.

@dmmulroy
Last active August 25, 2020 23:06
Show Gist options
  • Save dmmulroy/831b4bbfed468b9a2cc81de0d320da71 to your computer and use it in GitHub Desktop.
Save dmmulroy/831b4bbfed468b9a2cc81de0d320da71 to your computer and use it in GitHub Desktop.
function getGridColumnAndRowCount(grid, pageCount) {
let columns = 0;
let prevX;
for (const el of grid.children) {
const { x } = el.getBoundingClientRect();
if (prevX != null && x < prevX) {
break;
}
prevX = x;
columns++;
}
const rows = Math.ceil(pageCount / columns);
return { rows, columns };
}
// will return a 1 based index
function getRow(index, numColumns) {
return Math.ceil((index + 1) / numColumns);
}
// will return a 1 based index
function getColumn(index, numColumns) {
return (index % numColumns) + 1;
}
// will return a 0 based index
function getIndex({ row, column, numRows, numColumns, numItems }) {
const isOutOfBounds =
row > numRows || row <= 0 || column > numColumns || column <= 0;
if (isOutOfBounds) {
return -1;
}
const index = numColumns * (row - 1) + (column - 1);
// If the index is greater than or equal to numItems default to the last index.
// This handles the case when we press ArrowDown and there is another row, but
// the column below is empty. It will default to the last item in the list.
return index >= numItems ? numItems - 1 : index;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment