-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathexpander.go
34 lines (30 loc) · 881 Bytes
/
expander.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
package anno
import "sort"
// Expander holds a map of note kinds to expander functions that will be
// used to replace the text in the original string.
type Expander map[string]func(b string) string
// Expand generates a new string by calling the expander function
// for each note depending on its kind.
func (e Expander) Expand(s string, notes Notes) string {
// put the notes in the order in which they appear
// in the string
sort.Sort(notes)
for i, note := range notes {
fn, present := e[note.Kind]
if !present {
continue
}
insert := fn(string(note.Val))
s = s[0:note.Start] + insert + s[note.End():]
// log.Printf("----- s after: %v", s)
if i < len(notes)-1 {
// update the offset of remaining notes
offset := len(insert) - len(note.Val)
for j := range notes[i+1:] {
jj := j + i + 1
notes[jj].Start += offset
}
}
}
return s
}