From 6eb12896e3295796321f4c7d490f743557b76ee5 Mon Sep 17 00:00:00 2001 From: Lee Sang Gyu Date: Mon, 9 Nov 2026 18:11:21 +0900 Subject: [PATCH] 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 --- maputil/map.go | 10 +++++++++- maputil/map_test.go | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/maputil/map.go b/maputil/map.go index c130792..ce99397 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -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) diff --git a/maputil/map_test.go b/maputil/map_test.go index 378d813..bd7bb4b 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -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) + } + } +}