-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.go
36 lines (27 loc) · 945 Bytes
/
message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package tgo
import (
"unicode/utf8"
"github.com/samber/lo"
)
func SplitMessagesAgainstLengthLimitIntoMessageGroups(originalSlice []string) [][]string {
count := 0
tempSlice := make([]string, 0)
batchSlice := make([][]string, 0)
for _, s := range originalSlice {
tempSlice = append(tempSlice, s)
count += utf8.RuneCountInString(s) + 20
if count >= 4096 {
tempSlice = lo.DropRight(tempSlice, 1) // rollback the last append
batchSlice = append(batchSlice, tempSlice) // commit the batch
tempSlice = make([]string, 0) // reset the temp slice
count = 0 // reset the count
tempSlice = append(tempSlice, s) // re-append the last element
count += utf8.RuneCountInString(s) + 20 // re-calculating the count
}
}
// if there are still elements in the temp slice, append them to the batch
if len(tempSlice) > 0 {
batchSlice = append(batchSlice, tempSlice)
}
return batchSlice
}