Skip to content

Commit

Permalink
improve prependTreeNode
Browse files Browse the repository at this point in the history
  • Loading branch information
iOliverNguyen committed Aug 2, 2021
1 parent 81d10a6 commit d6d904e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 42 deletions.
28 changes: 7 additions & 21 deletions pkg/storage/tree/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,31 +81,17 @@ func (t *Tree) Merge(srcTrieI merge.Merger) {

for _, srcChildNode := range st.ChildrenNodes {
dstChildNode := dt.insert(srcChildNode.Name)
srcNodes = prepend(srcNodes, srcChildNode)
dstNodes = prepend(dstNodes, dstChildNode)
srcNodes = prependTreeNode(srcNodes, srcChildNode)
dstNodes = prependTreeNode(dstNodes, dstChildNode)
}
}
}

func prepend(s []*treeNode, x *treeNode) []*treeNode {
if len(s) != 0 && s[0] == x {
return s
}
prev := x
for i, elem := range s {
switch {
case i == 0:
s[0] = x
prev = elem
case elem == x:
s[i] = prev
return s
default:
s[i] = prev
prev = elem
}
}
return append(s, prev)
func prependTreeNode(s []*treeNode, x *treeNode) []*treeNode {
s = append(s, nil)
copy(s[1:], s)
s[0] = x
return s
}

func prependBytes(s [][]byte, x []byte) [][]byte {
Expand Down
25 changes: 4 additions & 21 deletions pkg/storage/tree/tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,34 +110,17 @@ func treeStr(s string) string {
}

var _ = Describe("prepend", func() {
Context("prepend (treeNode)", func() {
A, B, C, X := &treeNode{}, &treeNode{}, &treeNode{}, &treeNode{}

It("prepend to slice with single elem", func() {
s := []*treeNode{A}
s = prepend(s, A)
Expect(s).To(HaveLen(1))
Expect(s[0]).To(Equal(A))
})

It("prepend slice with new elem", func() {
Context("prependTreeNode)", func() {
It("prepend elem", func() {
A, B, C, X := &treeNode{}, &treeNode{}, &treeNode{}, &treeNode{}
s := []*treeNode{A, B, C}
s = prepend(s, X)
s = prependTreeNode(s, X)
Expect(s).To(HaveLen(4))
Expect(s[0]).To(Equal(X))
Expect(s[1]).To(Equal(A))
Expect(s[2]).To(Equal(B))
Expect(s[3]).To(Equal(C))
})

It("prepend slice with existing elem", func() {
s := []*treeNode{A, B, C}
s = prepend(s, B)
Expect(s).To(HaveLen(3))
Expect(s[0]).To(Equal(B))
Expect(s[1]).To(Equal(A))
Expect(s[2]).To(Equal(C))
})
})
Context("prependBytes", func() {
It("prepend elem", func() {
Expand Down

0 comments on commit d6d904e

Please sign in to comment.