Skip to content

Instantly share code, notes, and snippets.

@dirkraft
Last active May 1, 2018 22:40
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 dirkraft/259d2ba7dfd416942656f4c2f56adb47 to your computer and use it in GitHub Desktop.
Save dirkraft/259d2ba7dfd416942656f4c2f56adb47 to your computer and use it in GitHub Desktop.
Formats data to a table format for humans with better-than-nothing column resizing.
/*
The MIT License (MIT)
Copyright (c) 2017 Jason Dunkelberger (aka "dirkraft")
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package jason
import scala.collection.TraversableOnce
import scala.util.Try
object ConsoleTable {
/** Default columns width which uses env COLUMNS (not exported by default in most environments).
* If that fails, uses a default width of 120. Can be modified though `format` also accepts
* an explicit `tableWidth` argument too.
*/
var columns: Int = Try {
sys.env.getOrElse("COLUMNS", "120").toInt
}.getOrElse(120)
/** Formats tabular data intended to be read by a human, usually printed to a console. Tries its best to make the best
* use of space possible.
*
* @param data Sequence of any type of data object. Its contents will be loaded entirely into memory.
* This function does not support any sort of streaming output.
* @param formatters Functions which take your data type and produce the contents of a cell in the table. Formatters
* can return any value which will turned toString. `null` will be translated to the empty string.
* @param headers Optional headers to print at the top. Its length must match the number of columns output
* by the formatters.
* @param tableWidth Maximum width of the table. If the largest cell values would push the table width beyond this
* limit, those cells are instead truncated until the table will fit completely into this width.
* If not given, uses value of [columns]
* @param separator Printed as the border between columns. Is accounted for in the table width. Defaults to '|'.
* @param out Where should I send the output, in case you want to go somewhere other than `println`.
* Defaults to `println`.
*/
def format[E](
data: TraversableOnce[E],
formatters: TraversableOnce[E => Any],
headers: TraversableOnce[String] = Seq(),
tableWidth: Int = columns,
separator: String = "|",
out: String => Any = println
): Unit = {
val numCols = formatters.size
val _data = data.toSeq
val _formatters = formatters.toSeq
val _headers = headers.toSeq
assert(_headers.isEmpty || _headers.size == numCols, "Headers length when given must equal formatters length.")
val widthUsedBySeparators = separator.length * (numCols - 1)
val availableWidth = tableWidth - widthUsedBySeparators
assert(availableWidth >= numCols, "Width is too small to even show one character per column.")
val dataRows = _data.map(data => _formatters.map { formatter =>
val formatted = formatter(data)
if (formatted == null) "" else formatted.toString.replace("\r", " ").replace("\n", "")
})
val formattedRows: Seq[Seq[String]] = if (_headers.nonEmpty) _headers +: dataRows else dataRows
val maxColWidths: Map[Int, Int] =
(0 until numCols).map(colIdx => colIdx -> formattedRows.map(row => row(colIdx).length).max).toMap
val resizedColWidths: Seq[Int] = distribute(availableWidth, maxColWidths).toList
.sortBy { case (idx, _) => idx }
.map { case (_, width) => width }
def formatRow(row: Seq[String]): String = {
val resized = row.zip(resizedColWidths).map {
case (cell, maxWidth) =>
val paddedLimitedFormat = s"%-$maxWidth.${maxWidth}s"
String.format(paddedLimitedFormat, cell)
}
resized.mkString(separator)
}
if (_headers.nonEmpty) {
out(formatRow(_headers))
out(resizedColWidths.map { width => "-" * width }.mkString(separator))
}
dataRows.map(formatRow).foreach(out)
}
def formatTuples(
data: TraversableOnce[Product],
headers: TraversableOnce[String] = Seq(),
tableWidth: Int = columns,
separator: String = "|",
out: String => Any = println
): Unit = {
val _data = data.map(_.productIterator.toSeq)
formatRows(_data, headers, tableWidth, separator, out)
}
def formatRows(
data: TraversableOnce[TraversableOnce[_]],
headers: TraversableOnce[String] = Seq(),
tableWidth: Int = columns,
separator: String = "|",
out: String => Any = println
): Unit = {
val _data = data.map(_.toSeq).toSeq
val formatters = _data.head.toIndexedSeq.indices
.map(idx => (row: Seq[_]) => row(idx))
format(_data, formatters, headers, tableWidth, separator, out)
}
def distribute(availableWidth: Int, maxColWidths: Map[Int, Int]): Map[Int, Int] = {
val fairShare = availableWidth / maxColWidths.size
val (fairCols: Map[Int, Int], unfairCols: Map[Int, Int]) =
maxColWidths.partition { case (_, width) => width <= fairShare }
if (fairCols.size == maxColWidths.size) {
// Everything is fair :)
assert(fairCols.nonEmpty && unfairCols.isEmpty)
maxColWidths
} else if (unfairCols.size == maxColWidths.size) {
// Nothing fits. Truncate them all.
assert(fairCols.isEmpty && unfairCols.nonEmpty)
// Recover widths lost to int division.
val truncateWidth = availableWidth / unfairCols.size
val lostToIntDiv = availableWidth - (truncateWidth * unfairCols.size)
unfairCols.map {
case (colIdx, _) =>
// Left most columns will receive the recovered widths.
val recoverOne = if (colIdx < lostToIntDiv) 1 else 0
colIdx -> (truncateWidth + recoverOne)
}
} else {
// Some cols fit in the current space fairly. Keep those and divide up the rest with the remaining space.
assert(fairCols.nonEmpty && unfairCols.nonEmpty)
val fairUsage = fairCols.values.sum
val remainingWidth = availableWidth - fairUsage
fairCols ++ distribute(remainingWidth, unfairCols)
}
}
def main(args: Array[String]): Unit = {
// Explicitly type each row and provide formatters.
format[(String, String, Int, String)](
headers = Seq("something", "something else", "how much", "heyhey"),
data = Seq(
("Antidisestablishmentarianism", "noun", 75, "Whatever you want it to be."),
("wayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy too long", "phrase", 1000000000, "haha")
),
formatters = Seq(_._1, _._2, _._3, _._4),
tableWidth = 100
)
println()
// or, give a TraversableOnce of TraversableOnce
formatRows(
headers = Seq("something", "something else", "how much", "heyhey"),
data = Seq(
Seq("Antidisestablishmentarianism", "noun", 75, "Whatever you want it to be."),
Seq("wayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy too long", "phrase", 1000000000, "haha")
),
tableWidth = 100
)
println()
// OR, give a TraversableOnce of Product (tuple types)
formatTuples(
headers = Seq("something", "something else", "how much", "heyhey"),
data = Seq(
("Antidisestablishmentarianism", "noun", 75, "Whatever you want it to be."),
("wayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy too long", "phrase", 1000000000, "haha")
),
tableWidth = 100
)
/* Produces output like this.
something |something else|how much |heyhey
----------------------------------------------|--------------|----------|---------------------------
Antidisestablishmentarianism |noun |75 |Whatever you want it to be.
wayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy|phrase |1000000000|haha
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment