Commit 28489790 authored by Kirill Smelkov's avatar Kirill Smelkov

go/internal/xmaps: New package that complements standard package maps

Currently with the only utility to retrieve map keys in sorted order.

We will need this in several tests in follow-up patches.
parent 8da1234e
// Copyright (C) 2024 Nexedi SA and Contributors.
// Kirill Smelkov <kirr@nexedi.com>
//
// This program is free software: you can Use, Study, Modify and Redistribute
// it under the terms of the GNU General Public License version 3, or (at your
// option) any later version, as published by the Free Software Foundation.
//
// You can also Link and Combine this program with other software covered by
// the terms of any of the Free Software licenses or any of the Open Source
// Initiative approved licenses and Convey the resulting work. Corresponding
// source of such a combination shall include the source code for all other
// software used.
//
// This program is distributed WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// See COPYING file for full licensing terms.
// See https://www.nexedi.com/licensing for rationale and options.
// Package xmaps complements standard package maps.
package xmaps
import (
"cmp"
"slices"
)
// SortedKeys returns all keys of map m in their ascending order.
func SortedKeys[M ~map[K]V, K cmp.Ordered, V any](m M) []K {
keyv := make([]K, 0, len(m))
for k := range m {
keyv = append(keyv, k)
}
slices.Sort(keyv)
return keyv
}
// Copyright (C) 2024 Nexedi SA and Contributors.
// Kirill Smelkov <kirr@nexedi.com>
//
// This program is free software: you can Use, Study, Modify and Redistribute
// it under the terms of the GNU General Public License version 3, or (at your
// option) any later version, as published by the Free Software Foundation.
//
// You can also Link and Combine this program with other software covered by
// the terms of any of the Free Software licenses or any of the Open Source
// Initiative approved licenses and Convey the resulting work. Corresponding
// source of such a combination shall include the source code for all other
// software used.
//
// This program is distributed WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// See COPYING file for full licensing terms.
// See https://www.nexedi.com/licensing for rationale and options.
package xmaps
import (
"slices"
"testing"
)
func TestSortedKeys(t *testing.T) {
m := map[string]int{
"c": 1,
"b": 2,
"a": 3,
"zzz": 4,
"rr": 5,
"p": 6,
"j": 7,
}
kok := []string{"a", "b", "c", "j", "p", "rr", "zzz"}
for i := 0; i < 100; i++ {
keyv := SortedKeys(m)
if !slices.Equal(keyv, kok) {
t.Fatalf("SortedKeys:\nhave: %s\nwant: %s", keyv, kok)
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment