Created
October 19, 2021 23:59
-
-
Save theverything/439271149c5be3aa1dce2ebed35f64f6 to your computer and use it in GitHub Desktop.
Golang Key Value Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package kvtable | |
import ( | |
"fmt" | |
"strings" | |
) | |
type Row struct { | |
Key string | |
Value string | |
} | |
func Create(data []Row) string { | |
magic := 5 | |
var keyPadding int | |
var valPadding int | |
for _, row := range data { | |
if len(row.Key) > keyPadding { | |
keyPadding = len(row.Key) | |
} | |
if len(row.Value) > valPadding { | |
valPadding = len(row.Value) | |
} | |
} | |
line := fmt.Sprintf("+%s+", strings.Repeat("-", magic+keyPadding+valPadding)) | |
var table strings.Builder | |
fmt.Fprint(&table, line) | |
for _, row := range data { | |
fmt.Fprintf(&table, "\n| %-*s | %-*s |\n%s", keyPadding, row.Key, valPadding, row.Value, line) | |
} | |
return table.String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment