refactor: use go 1.23 iterators

This commit is contained in:
ayn2op 2024-08-17 18:27:59 +05:30
parent b35aaf42f3
commit affce8159c
4 changed files with 45 additions and 14 deletions

View file

@ -3,9 +3,11 @@ package cmd
import (
"fmt"
"log"
"slices"
"sort"
"strings"
"github.com/ayn2op/discordo/pkg/itertools"
"github.com/diamondburned/arikawa/v3/discord"
"github.com/diamondburned/arikawa/v3/gateway"
"github.com/gdamore/tcell/v2"
@ -88,12 +90,11 @@ func (gt *GuildsTree) channelToString(c discord.Channel) string {
s = c.Name
// If the name of the channel is empty, use the recipients' tags
if s == "" {
rs := make([]string, len(c.DMRecipients))
for _, r := range c.DMRecipients {
rs = append(rs, r.Tag())
}
recipients := itertools.Map(slices.Values(c.DMRecipients), func(r discord.User) string {
return r.Tag()
})
s = strings.Join(rs, ", ")
s = strings.Join(slices.Collect(recipients), ", ")
}
case discord.GuildAnnouncement:
s = "a-" + c.Name
@ -128,10 +129,12 @@ func (gt *GuildsTree) createChannelNode(n *tview.TreeNode, c discord.Channel) *t
}
func (gt *GuildsTree) createChannelNodes(n *tview.TreeNode, cs []discord.Channel) {
for _, c := range cs {
if c.Type != discord.GuildCategory && !c.ParentID.IsValid() {
gt.createChannelNode(n, c)
}
orphanChannels := itertools.Filter(slices.Values(cs), func(c discord.Channel) bool {
return c.Type != discord.GuildCategory && !c.ParentID.IsValid()
})
for _, c := range slices.Collect(orphanChannels) {
gt.createChannelNode(n, c)
}
PARENT_CHANNELS:

View file

@ -5,6 +5,7 @@ import (
"fmt"
"io"
"log"
"slices"
"strings"
"time"
@ -59,8 +60,8 @@ func (mt *MessagesText) drawMsgs(cID discord.ChannelID) {
return
}
for i := len(ms) - 1; i >= 0; i-- {
mainFlex.messagesText.createMessage(ms[i])
for _, m := range slices.Backward(ms) {
mainFlex.messagesText.createMessage(m)
}
}
@ -337,8 +338,7 @@ func (mt *MessagesText) delete() {
mt.Clear()
for i := len(ms) - 1; i >= 0; i-- {
mainFlex.messagesText.createMessage(ms[i])
for _, m := range slices.Backward(ms) {
mainFlex.messagesText.createMessage(m)
}
}

15
pkg/itertools/filter.go Normal file
View file

@ -0,0 +1,15 @@
package itertools
import "iter"
func Filter[I any](in iter.Seq[I], predicate func(I) bool) iter.Seq[I] {
return func(yield func(I) bool) {
for i := range in {
if predicate(i) {
if !yield(i) {
return
}
}
}
}
}

13
pkg/itertools/map.go Normal file
View file

@ -0,0 +1,13 @@
package itertools
import "iter"
func Map[I, O any](in iter.Seq[I], f func(I) O) iter.Seq[O] {
return func(yield func(O) bool) {
for i := range in {
if !yield(f(i)) {
return
}
}
}
}