Skip to content

Instantly share code, notes, and snippets.

@lancegatlin
Created April 29, 2016 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lancegatlin/cd77c5994e85ea89c50de995c5f009e6 to your computer and use it in GitHub Desktop.
Save lancegatlin/cd77c5994e85ea89c50de995c5f009e6 to your computer and use it in GitHub Desktop.
package s_mach.string.impl
import s_mach.string._
object GridOps {
def grid_rowCount[T](self: Grid[T]) : Int =
self.size
def grid_columnCount[T](self: Grid[T]) : Int =
self.iterator.map(_.size).max
def grid_get[T](self: Grid[T])(row: Int, col: Int): Option[T] = {
if(row < self.size && col < self(row).size) {
Some(self(row)(col))
} else {
None
}
}
def grid_rows[T](self: Grid[T]) : Iterator[Seq[Option[T]]] =
self.iterator.map(_.map(Some(_)))
def grid_columns[T](self: Grid[T]) : Iterator[Seq[Option[T]]] = {
val _colCount = self.columnCount
val _rowCount = self.rowCount
(0 until _colCount).iterator.map { col =>
(0 until _rowCount).map { row =>
self.get(row, col)
}
}
}
def grid_appendColumns[T](self: Grid[T])(that: Grid[T]) : Grid[T] = {
self.indices.iterator.map { row =>
self(row) ++ that(row)
}.toSeq
}
def grid_toStringGrid[T](self: Grid[T]) : Grid[String] = {
for (row <- self) yield for (item <- row) yield item.toString
}
def stringGrid_printGrid(
self: Grid[String]
)(
columnSep : String,
rowSep: String
) : String = {
val rowCount = self.rowCount
val columnCount = self.columnCount
val lastColumnIndex = columnCount - 1
val maxColWidths : Seq[Int] =
self.columns.map { col =>
col.map { opt =>
opt.map(_.length).getOrElse(0)
}.max
}.toSeq
(0 until rowCount).map { row =>
(0 until columnCount).map { col =>
val value =
self.get(row,col) match {
case Some(v) => v
case None => ""
}
if(maxColWidths(col) > 0) {
if(col != lastColumnIndex) {
f"$value%-${maxColWidths(col)}s"
} else {
// Don't widen the last column
value
}
} else {
// Column width is 0 (empty spacer column)
""
}
}.mkString(columnSep)
}.mkString(rowSep)
}
}
type Grid[T] = Seq[Seq[T]]
implicit class GridPML_[T](val self: Grid[T]) extends AnyVal {
@inline def rowCount: Int =
GridOps.grid_rowCount(self)
@inline def columnCount: Int =
GridOps.grid_columnCount(self)
@inline def get(row: Int, col: Int): Option[T] =
GridOps.grid_get(self)(row, col)
@inline def rows: Iterator[Seq[Option[T]]] =
GridOps.grid_rows(self)
@inline def columns: Iterator[Seq[Option[T]]] =
GridOps.grid_columns(self)
@inline def appendColumns(that: Grid[T]): Grid[T] =
GridOps.grid_appendColumns(self)(that)
@inline def toStringGrid: Grid[String] =
GridOps.grid_toStringGrid(self)
}
implicit class StringGridPML_(val self: Grid[String]) extends AnyVal {
@inline def printGrid(columnSep : String, rowSep: String) : String =
GridOps.stringGrid_printGrid(self)(columnSep,rowSep)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment