mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
fix(package): [maputil] keep ToMarkdownTable column order stable (#418)
* fix(package): [maputil] keep ToMarkdownTable column order stable * test(package): [maputil] cover ToMarkdownTable default column order
This commit is contained in:
1 parent
0112b99cd9
commit
6eb12896e3
2 files changed
+29
-1
No files matched your search
+9
-1
@@ -706,10 +706,18 @@ func ToMarkdownTable(data []map[string]interface{}, headerMap map[string]string,
|
||||
headers = make([]string, len(columnOrder))
|
||||
copy(headers, columnOrder)
|
||||
} else {
|
||||
// 否则按自然顺序提取headers
|
||||
// 否则按每行键的字典序提取headers
|
||||
seen := make(map[string]bool)
|
||||
for _, row := range data {
|
||||
// Map iteration order is random, so visit the keys of each row in sorted
|
||||
// order to get the same columns in the same order on every call.
|
||||
keys := make([]string, 0, len(row))
|
||||
for k := range row {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
for _, k := range keys {
|
||||
if !seen[k] {
|
||||
seen[k] = true
|
||||
headers = append(headers, k)
|
||||
|
||||
@@ -997,3 +997,23 @@ func TestToMarkdownTableWithHeaderMap(t *testing.T) {
|
||||
fmt.Printf("%s", result)
|
||||
// 验证中文表头是否正确显示
|
||||
}
|
||||
|
||||
func TestToMarkdownTableDefaultColumnOrder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
data := []map[string]interface{}{
|
||||
{"name": "Alice", "age": 25, "salary": 50000, "city": "Seoul"},
|
||||
{"name": "Bob", "zip": "04524", "age": 30},
|
||||
}
|
||||
|
||||
expected := "| age | city | name | salary | zip |\n" +
|
||||
"|---|---|---|---|---|\n" +
|
||||
"| 25 | Seoul | Alice | 50,000 | |\n" +
|
||||
"| 30 | | Bob | | 04524 |\n"
|
||||
|
||||
for i := 0; i < 50; i++ {
|
||||
if result := ToMarkdownTable(data, nil, nil); result != expected {
|
||||
t.Fatalf("call %d: expected:\n%s\ngot:\n%s", i, expected, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user