Skip to content

Commit ac35225

Browse files
committed
Add examples/basic/cmpop/composite_sort_key.go
1 parent 268f7ed commit ac35225

File tree

3 files changed

+47
-4
lines changed

3 files changed

+47
-4
lines changed

examples/basic/cmpop/README.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
このディレクトリには以下のサンプルがあります。
44

5-
| file | example name | note |
6-
| ---------- | ------------- | ---------------------------------------------- |
7-
| or.go | cmpop_or | cmp.Or\[T comparable\]\(\) のサンプルです |
8-
| compare.go | cmpop_compare | cmp.Compare\[T cmp.Orderd\]\(\) のサンプルです |
5+
| file | example name | note |
6+
| --------------------- | ------------------------- | --------------------------------------------------------------------- |
7+
| or.go | cmpop_or | cmp.Or\[T comparable\]\(\) のサンプルです |
8+
| compare.go | cmpop_compare | cmp.Compare\[T cmp.Orderd\]\(\) のサンプルです |
9+
| composite_sort_key.go | cmpop_composite_sort_keys | cmp.Or, cmp.Compareを用いて複合キーのソート処理を実装するサンプルです |
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package cmpop
2+
3+
import (
4+
"cmp"
5+
"slices"
6+
7+
"github.com/devlights/gomy/output"
8+
)
9+
10+
// CompositeSortKeys は、cmp.Or, cmp.Compareを用いて複合キーのソート処理を実装するサンプルです。
11+
func CompositeSortKeys() error {
12+
type Person struct {
13+
Name string
14+
Age uint8
15+
}
16+
17+
var (
18+
people = []Person{
19+
{"Aikawa", 21},
20+
{"Tanaka", 22},
21+
{"Kato", 33},
22+
{"Suzuki", 44},
23+
{"Tanaka", 44},
24+
{"Aikawa", 66},
25+
}
26+
)
27+
28+
output.Stdoutl("[before]", people)
29+
30+
// 名前の昇順が第1キー、年齢の降順が第2キーとする
31+
slices.SortFunc(people, func(x, y Person) int {
32+
return cmp.Or(
33+
cmp.Compare(x.Name, y.Name),
34+
-cmp.Compare(x.Age, y.Age),
35+
)
36+
})
37+
38+
output.Stdoutl("[after ]", people)
39+
40+
return nil
41+
}

examples/basic/cmpop/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@ func NewRegister() mapping.Register {
1515
func (r *register) Regist(m mapping.ExampleMapping) {
1616
m["cmpop_or"] = Or
1717
m["cmpop_compare"] = Compare
18+
m["cmpop_composite_sort_keys"] = CompositeSortKeys
1819
}

0 commit comments

Comments
 (0)