Skip to content

Commit c5abdae

Browse files
committed
Added Insert method
1 parent 0c6911a commit c5abdae

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

stringbuilder.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,26 @@ func (s *StringBuilder) Remove(start int, length int) error {
8585
return nil
8686
}
8787

88+
func (s *StringBuilder) Insert(index int, text string) error {
89+
if index < 0 {
90+
return fmt.Errorf("index can't be negative")
91+
}
92+
93+
if index > s.position {
94+
return fmt.Errorf("can't write outside the buffer")
95+
}
96+
97+
newLen := s.position + len(text)
98+
if newLen >= cap(s.data) {
99+
s.grow(newLen)
100+
}
101+
102+
s.data = append(s.data[:index], append([]rune(text), s.data[index:]...)...)
103+
s.position = newLen
104+
105+
return nil
106+
}
107+
88108
func (s *StringBuilder) grow(lenToAdd int) {
89109
// Grow times 2 until lenToAdd fits
90110
newLen := cap(s.data)

stringbuilder_test.go

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package Text
22

3-
import "testing"
3+
import (
4+
"testing"
5+
)
46

57
func TestAppend(t *testing.T) {
68
const expected string = "Hello World"
@@ -120,3 +122,32 @@ func TestRemoveWhenLengthZero(t *testing.T) {
120122
t.Errorf("Actual %q, Expected: %q", result, expected)
121123
}
122124
}
125+
126+
func TestInsertAtIndex(t *testing.T) {
127+
const expected string = "Hello my dear and beautiful World"
128+
sb := NewFromString("Hello World")
129+
130+
if err := sb.Insert(5, " my dear and beautiful"); err != nil {
131+
t.Errorf("Insert threw an error: %v", err)
132+
}
133+
134+
if result := sb.ToString(); result != expected {
135+
t.Errorf("Actual %q, Expected: %q", result, expected)
136+
}
137+
}
138+
139+
func TestInsertShouldThrowIfNegativeIndex(t *testing.T) {
140+
sb := StringBuilder{}
141+
142+
if err := sb.Insert(-1, "Test"); err == nil {
143+
t.Error("Should throw error but did not")
144+
}
145+
}
146+
147+
func TestInsertShouldThrowErrirIfOutOfRange(t *testing.T) {
148+
sb := StringBuilder{}
149+
150+
if err := sb.Insert(1, "Test"); err == nil {
151+
t.Error("Should throw error but did not")
152+
}
153+
}

0 commit comments

Comments
 (0)