Skip to content

Instantly share code, notes, and snippets.

@lokedhs
Created February 1, 2022 12:08
Show Gist options
  • Save lokedhs/5b71a8f3874429bb3ec434106396fca0 to your computer and use it in GitHub Desktop.
Save lokedhs/5b71a8f3874429bb3ec434106396fca0 to your computer and use it in GitHub Desktop.
data class SelectedArea(val x: Int, val y: Int, val width: Int, val height: Int) {
companion object {
fun computeSelectedArea(selectedCells: ObservableList<TablePosition<*, *>>): SelectedArea? {
if (selectedCells.size == 0) {
return null
}
val cols = selectedCells.groupBy { p -> p.column }.entries.sortedBy { e -> e.key }.map { e -> e.value }
val rows = selectedCells.groupBy { p -> p.row }.entries.sortedBy { e -> e.key }.map { e -> e.value }
val numCols = cols.size
val numRows = rows.size
val firstCol = cols.first().first().column
var currCol = firstCol
// Ensure that the columns are increasing
cols.drop(1).forEach { col ->
currCol++
if(col.size != numRows || currCol != col.first().column) {
return null
}
}
// Check the same thing for all the rows
val firstRow = rows.first().first().row
var currRow = firstRow
rows.drop(1).forEach { row ->
currRow++
if(row.size != numCols || currRow != row.first().row) {
return null
}
}
return SelectedArea(firstCol, firstRow, numCols, numRows)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment