Skip to content

Commit

Permalink
DOM: Add merge() method on ContainerBuilder
Browse files Browse the repository at this point in the history
Signed-off-by: Richard Kosegi <richard.kosegi@gmail.com>
  • Loading branch information
rkosegi committed Jul 15, 2024
1 parent d171946 commit 836fc30
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
6 changes: 6 additions & 0 deletions dom/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,12 @@ func (c *containerBuilderImpl) Walk(fn WalkFn) {
}
}

func (c *containerBuilderImpl) Merge(other Container, opts ...MergeOption) ContainerBuilder {
m := &merger{}
m.init(opts...)
return m.mergeContainers(c, other)
}

func (c *containerBuilderImpl) AddList(name string) ListBuilder {
lb := &listBuilderImpl{}
c.add(name, lb)
Expand Down
12 changes: 12 additions & 0 deletions dom/container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,15 @@ func TestContainerClone(t *testing.T) {
assert.Equal(t, 123, c2.Lookup("a.x.y").(Leaf).Value())
assert.Equal(t, "123", c2.Lookup("a.b[1]").(Leaf).Value())
}

func TestMergeContainers(t *testing.T) {
a := b.Container()
c := b.Container()
a.AddValueAt("l1.l2c", LeafNode(7))
a.AddValueAt("l1.l2d", LeafNode("0987"))
c.AddValueAt("l1.l2a", LeafNode("123"))
c.AddValueAt("l1.l2b", LeafNode("abc"))
d := c.Merge(a)
assert.Equal(t, 4, len(d.Lookup("l1").(Container).Children()))
assert.Equal(t, "abc", d.Lookup("l1.l2b").(Leaf).Value())
}
2 changes: 1 addition & 1 deletion dom/merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func (mg *merger) mergeListsMeld(l1, l2 List) List {
return l
}

func (mg *merger) mergeContainers(c1, c2 Container) Container {
func (mg *merger) mergeContainers(c1, c2 Container) ContainerBuilder {
merged := map[string]Node{}
for k, v := range c1.Children() {
merged[k] = v
Expand Down
2 changes: 2 additions & 0 deletions dom/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ type ContainerBuilder interface {
RemoveAt(path string)
// Walk walks whole document tree, visiting every node
Walk(fn WalkFn)
// Merge creates new Container instance and merge current Container with other into it.
Merge(other Container, opts ...MergeOption) ContainerBuilder
}

type WalkFn func(path string, parent ContainerBuilder, node Node) bool
Expand Down

0 comments on commit 836fc30

Please sign in to comment.