Advertisement
Guest User

Untitled

a guest
Feb 5th, 2014
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.16 KB | None | 0 0
  1. implicit class SeqSeq2Table(table: Seq[Seq[Any]]) {
  2.   private def mkStringWithSpacing(seq: Seq[Any], c: String, spacing: Int) = {
  3.     val s = " " * spacing
  4.     seq.mkString(c + s, s + c + s, s + c)
  5.   }
  6.   def asTable(): String = asTable(1)
  7.   def asTable(spacing: Int): String = table match {
  8.     case Seq() => ""
  9.     case _ =>
  10.       val sizes = for (row <- table) yield (for (cell <- row) yield if (cell == null) 0 else cell.toString.length)
  11.       val colSizes = for (col <- sizes.transpose) yield col.max
  12.       val rows = for (row <- table) yield formatRow(row, colSizes, spacing)
  13.       formatRows(rowSeparator(colSizes, spacing), rows)
  14.   }
  15.  
  16.   def formatRows(rowSeparator: String, rows: Seq[String]): String =
  17.     (rowSeparator :: rows.head :: rowSeparator :: rows.tail.toList ::: rowSeparator :: List()).mkString("\n")
  18.  
  19.   def formatRow(row: Seq[Any], colSizes: Seq[Int], spacing: Int) = {
  20.     val cells = (for ((item, size) <- row.zip(colSizes)) yield if (size == 0) "" else ("%" + size + "s").format(item))
  21.     mkStringWithSpacing(cells, "|", spacing)
  22.   }
  23.  
  24.   def rowSeparator(colSizes: Seq[Int], spacing: Int) = colSizes map { "-" * _ } mkString("+ ", " + ", " +")
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement