-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselectors.go
118 lines (107 loc) · 2.45 KB
/
selectors.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package blume
import (
"regexp"
"strings"
)
func Pre(prefixes ...string) Selector[string] {
return func(s string) (res [][]int) {
for _, prefix := range prefixes {
if strings.HasPrefix(s, prefix) {
return [][]int{{0, len(prefix)}}
}
}
return
}
}
func Suf(suffixes ...string) Selector[string] {
return func(s string) (res [][]int) {
for _, suffix := range suffixes {
if strings.HasSuffix(s, suffix) {
return [][]int{{len(s) - len(suffix), len(s)}}
}
}
return
}
}
func Rgx(pattern string) Selector[string] {
re := regexp.MustCompile(pattern)
return func(s string) (res [][]int) {
return re.FindAllStringIndex(s, -1)
}
}
func Has[A any](selectors ...Selector[A]) func(input A) bool {
return func(input A) bool {
for _, fn := range selectors {
if len(fn(input)) > 0 {
return true
}
}
return false
}
}
func Del[A ~string](selectors ...Selector[A]) func(input A) A {
return func(input A) A {
for _, fn := range selectors {
ranges := fn(input)
if len(ranges) == 0 {
continue
}
input = ReplaceRanges(input, "", ranges)
}
return input
}
}
func Rep[A ~string](pairs ...any) func(input A) A {
replacers := []struct {
sel Selector[A]
rep A
}{}
if len(pairs)%2 != 0 {
panic("typeless generic function [Rep] needs to be given pairs of [`Selector[A]`, `A`].")
}
for i := 0; i < len(pairs); i += 2 {
sel, ok := pairs[i].(Selector[A])
if !ok {
panic("typeless generic function [Rep] given invalid selector type.")
}
rep, ok := pairs[i+1].(A)
if !ok {
panic("typeless generic function [Rep] given invalid replacement type.")
}
replacers = append(replacers, struct {
sel Selector[A]
rep A
}{sel, rep})
}
return func(input A) A {
for _, r := range replacers {
input = ReplaceRanges(input, r.rep, r.sel(input))
}
return input
}
}
func ReplaceRanges[S ~string](tar S, rep S, ranges [][]int) S {
if len(ranges) == 0 {
return tar
}
sortedRanges := make([][]int, len(ranges))
for i, r := range ranges {
sortedRanges[i] = make([]int, len(r))
copy(sortedRanges[i], r)
}
for i := 0; i < len(sortedRanges); i++ {
for j := i + 1; j < len(sortedRanges); j++ {
if sortedRanges[i][0] < sortedRanges[j][0] {
sortedRanges[i], sortedRanges[j] = sortedRanges[j], sortedRanges[i]
}
}
}
for _, r := range sortedRanges {
start, end := r[0], r[1]
if start < 0 || end > len(tar) || start > end {
continue
}
tar = tar[:start] + rep + tar[end:]
}
return tar
}