Plain-text CLI table renderer for Elixir
Elixir
defmodule CliTable do
def render(headers, rows) do
widths = widths([headers | rows])
sep = Enum.map_join(widths, "+", &String.duplicate("-", &1 + 2))
[format_row(headers, widths), sep | Enum.map(rows, &format_row(&1, widths))]
|> Enum.join("\n")
end
defp widths(rows) do
rows
|> Enum.zip()
|> Enum.map(fn col -> col |> Tuple.to_list() |> Enum.map(&String.length/1) |> Enum.max() end)
end
defp format_row(row, widths) do
cells = row |> Enum.zip(widths) |> Enum.map(fn {cell, w} -> String.pad_trailing(cell, w) end)
"| " <> Enum.join(cells, " | ") <> " |"
end
end