Skip to content

Commit

Permalink
Merge pull request #797 from devlights/add-composite-sort-keys-example
Browse files Browse the repository at this point in the history
  • Loading branch information
devlights authored Apr 30, 2024
2 parents 268f7ed + ac35225 commit 50e1cf2
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 4 deletions.
9 changes: 5 additions & 4 deletions examples/basic/cmpop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

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

| file | example name | note |
| ---------- | ------------- | ---------------------------------------------- |
| or.go | cmpop_or | cmp.Or\[T comparable\]\(\) のサンプルです |
| compare.go | cmpop_compare | cmp.Compare\[T cmp.Orderd\]\(\) のサンプルです |
| file | example name | note |
| --------------------- | ------------------------- | --------------------------------------------------------------------- |
| or.go | cmpop_or | cmp.Or\[T comparable\]\(\) のサンプルです |
| compare.go | cmpop_compare | cmp.Compare\[T cmp.Orderd\]\(\) のサンプルです |
| composite_sort_key.go | cmpop_composite_sort_keys | cmp.Or, cmp.Compareを用いて複合キーのソート処理を実装するサンプルです |
41 changes: 41 additions & 0 deletions examples/basic/cmpop/composite_sort_key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package cmpop

import (
"cmp"
"slices"

"github.com/devlights/gomy/output"
)

// CompositeSortKeys は、cmp.Or, cmp.Compareを用いて複合キーのソート処理を実装するサンプルです。
func CompositeSortKeys() error {
type Person struct {
Name string
Age uint8
}

var (
people = []Person{
{"Aikawa", 21},
{"Tanaka", 22},
{"Kato", 33},
{"Suzuki", 44},
{"Tanaka", 44},
{"Aikawa", 66},
}
)

output.Stdoutl("[before]", people)

// 名前の昇順が第1キー、年齢の降順が第2キーとする
slices.SortFunc(people, func(x, y Person) int {
return cmp.Or(
cmp.Compare(x.Name, y.Name),
-cmp.Compare(x.Age, y.Age),
)
})

output.Stdoutl("[after ]", people)

return nil
}
1 change: 1 addition & 0 deletions examples/basic/cmpop/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ func NewRegister() mapping.Register {
func (r *register) Regist(m mapping.ExampleMapping) {
m["cmpop_or"] = Or
m["cmpop_compare"] = Compare
m["cmpop_composite_sort_keys"] = CompositeSortKeys
}

0 comments on commit 50e1cf2

Please sign in to comment.