Skip to content

Commit 9dc8233

Browse files
committed
First pass at delete
1 parent c18fff5 commit 9dc8233

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

‎radix.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,47 @@ func (t *Tree) Insert(s string, v interface{}) (interface{}, bool) {
227227
// Delete is used to delete a key, returning the previous
228228
// value and if it was deleted
229229
func (t *Tree) Delete(s string) (interface{}, bool) {
230+
n := t.root
231+
search := s
232+
for {
233+
// Check for key exhaution
234+
if len(search) == 0 {
235+
if !n.isLeaf() {
236+
break
237+
}
238+
goto DELETE
239+
}
240+
241+
// Look for an edge
242+
n = n.getEdge(search[0])
243+
if n == nil {
244+
break
245+
}
246+
247+
// Consume the search prefix
248+
if strings.HasPrefix(search, n.prefix) {
249+
search = search[len(n.prefix):]
250+
} else {
251+
break
252+
}
253+
}
230254
return nil, false
255+
256+
DELETE:
257+
// Delete the leaf
258+
leaf := n.leaf
259+
n.leaf = nil
260+
t.size--
261+
262+
// Check if we should merge this node
263+
if len(n.edges) == 1 {
264+
e := n.edges[0]
265+
child := e.node
266+
n.prefix = n.prefix + child.prefix
267+
n.leaf = child.leaf
268+
n.edges = child.edges
269+
}
270+
return leaf.val, true
231271
}
232272

233273
// Get is used to lookup a specific key, returning

‎radix_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88

99
func TestRadix(t *testing.T) {
1010
inp := make(map[string]interface{})
11-
for i := 0; i < 20; i++ {
11+
for i := 0; i < 1000; i++ {
1212
inp[generateUUID()] = i
1313
}
1414

0 commit comments

Comments
 (0)