lintel 0.2.0
Loading...
Searching...
No Matches
TableBuilder.h
Go to the documentation of this file.
1#ifndef LINTEL_TABLEBUILDER_H
2#define LINTEL_TABLEBUILDER_H
3
4#include <algorithm>
5#include <array>
6#include <numeric>
7#include <string>
8#include <vector>
9
10namespace lintel {
12struct Column
13{
15 std::vector<std::string> m_rows;
16};
17
19template<std::size_t N> class TableBuilder
20{
21private:
22 std::array<Column, N> m_columns;
23
24public:
27 void add(std::array<std::string, N> line)
28 {
29 std::size_t i = 0;
30 for (const auto &iter : line) {
31 m_columns[i].m_rows.push_back(iter);
32 i++;
33 }
34 }
35
38 std::string build()
39 {
40 // 1. calc max length
41 std::array<std::size_t, N> maxLengthPerCol;
42 std::size_t i = 0;
43 for (const auto &iter : m_columns) {
44 auto maxLengthStr = std::max_element(
45 iter.m_rows.begin(), iter.m_rows.end(), [](const auto &a, const auto &b) { return a.length() < b.length(); });
46 maxLengthPerCol[i] = maxLengthStr->length();
47 i++;
48 }
49 // 2. sum max length
50 std::size_t sumMaxLength = std::accumulate(maxLengthPerCol.begin(), maxLengthPerCol.end(), std::size_t{ 0 });
51 sumMaxLength += 4 * N + 1;
52 // 3. start printing separator
53 std::string separator;
54 for (i; i < sumMaxLength; i++) { separator += "-"; }
55 separator += "\n";
56 // 4 depth of columns
57 const std::size_t m = N > 0 ? m_columns[0].m_rows.size() : 0;
58 // 5 start printing content
59 std::string temp;
60 temp += separator;
61 bool headerLine = true;
62 for (std::size_t j = 0; j < m; j++) {
63 std::string lineTemp = "|";
64 for (i = 0; i < N; i++) {
65 lineTemp += " ";
66 std::string val = m_columns[i].m_rows[j];
67 lineTemp += val;
68 for (std::size_t k = val.length(); k < maxLengthPerCol[i] + 1; k++) { lineTemp += " "; }
69 lineTemp += "|";
70 }
71 lineTemp += "\n";
72 temp += lineTemp;
73 if (headerLine) {
74 headerLine = false;
75 temp += separator;
76 }
77 }
78 temp += separator;
79 return temp;
80 }
81};
82
83}// namespace lintel
84#endif// LINTEL_TABLEBUILDER_H
Definition TableBuilder.h:20
std::string build()
Definition TableBuilder.h:38
void add(std::array< std::string, N > line)
Definition TableBuilder.h:27
Definition BaseFeature.h:6
constexpr std::string_view type_name()
Definition TypeName.h:9
Definition TableBuilder.h:13
std::vector< std::string > m_rows
Definition TableBuilder.h:15