Skip to content

Instantly share code, notes, and snippets.

@rumblefrog
Created February 18, 2019 08:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rumblefrog/c9ebd9fb84a8955495d4fb7983345530 to your computer and use it in GitHub Desktop.
Save rumblefrog/c9ebd9fb84a8955495d4fb7983345530 to your computer and use it in GitHub Desktop.
Sort Discord channels (category, text, voice) in an one dimension array
package channelsorter
import (
"sort"
"github.com/rumblefrog/discordgo"
)
type ChannelGeneric struct {
Underlying *discordgo.Channel
Children []*discordgo.Channel
}
func SortChannels(cs []*discordgo.Channel) (out []*discordgo.Channel) {
p := make(map[int64]*ChannelGeneric)
for _, c := range cs {
if c.Type != discordgo.ChannelTypeGuildCategory && c.ParentID != 0 {
v, ok := p[c.ParentID]
if ok {
v.Children = append(v.Children, c)
} else {
p[c.ParentID] = &ChannelGeneric{
Children: []*discordgo.Channel{c},
}
}
continue
}
if c.Type == discordgo.ChannelTypeGuildCategory {
v, ok := p[c.ID]
if ok {
v.Underlying = c
} else {
p[c.ID] = &ChannelGeneric{
Underlying: c,
}
}
continue
}
p[c.ID] = &ChannelGeneric{
Underlying: c,
}
}
a := make([]*ChannelGeneric, 0, len(p))
for _, v := range p {
if v.Children != nil {
sort.Slice(v.Children, func(i, j int) bool {
return v.Children[i].Position < v.Children[j].Position
})
}
a = append(a, v)
}
sort.Slice(a, func(i, j int) bool {
return a[i].Underlying.Position < a[j].Underlying.Position
})
for _, v := range a {
out = append(out, v.Underlying)
if v.Children != nil {
for _, k := range v.Children {
out = append(out, k)
}
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment