Add iterator for strings

This commit is contained in:
Hamcha 2018-11-16 11:39:48 +01:00
parent 11c9d9498b
commit bcb643ee78
Signed by: hamcha
GPG key ID: A40413D21021EAEE

43
iterator.go Normal file
View file

@ -0,0 +1,43 @@
package emoji
// Fragment is either a rune or an emoji
type Fragment struct {
Offset int
IsEmoji bool
Emoji Emoji
Rune rune
}
// Iterate iterates through a string and returns its runes (for characters) and emojis
func (em Table) Iterate(str string) <-chan Fragment {
c := make(chan Fragment)
go func() {
nextchar := 0
for index, r := range str {
// Check if we need to skip entries
if nextchar > index {
continue
}
// Check if rune is an emoji
if em.IsEmoji(r) {
icon := em.Find(str[index:])
if icon != nil {
nextchar = index + icon.Length() - 1
c <- Fragment{
IsEmoji: true,
Offset: index,
Emoji: *icon,
}
continue
}
}
c <- Fragment{
IsEmoji: false,
Offset: index,
Rune: r,
}
}
}()
return c
}