Last active
December 23, 2015 21:09
-
-
Save crosbymichael/6694779 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package graphdb | |
import ( | |
"fmt" | |
"sync" | |
) | |
type Nodes map[string]*Node | |
type Node struct { | |
Id string | |
Value interface{} | |
Children Nodes | |
} | |
type Database struct { | |
nodes Nodes | |
mux sync.Mutex | |
} | |
func NewDatabase() *Database { | |
return &Database{ | |
nodes: Nodes{}, | |
mux: sync.Mutex{}, | |
} | |
} | |
func (d *Database) CreateNode(id string) (*Node, error) { | |
d.mux.Lock() | |
defer d.mux.Unlock() | |
if _, exists := d.nodes[id]; exists { | |
return nil, fmt.Errorf("Node already exists for id: %s", id) | |
} | |
n := &Node{Id: id, Children: Nodes{}} | |
d.nodes[id] = n | |
return n, nil | |
} | |
func (n *Node) AddChild(node *Node) error { | |
if _, exists := n.Children[node.Id]; exists { | |
return fmt.Errorf("Child already exists: %s", node.Id) | |
} | |
n.Children[node.Id] = node | |
return nil | |
} | |
func (n *Node) HasChildren() bool { | |
return len(n.Children) > 0 | |
} | |
func (n *Node) Traverse() <-chan *Node { | |
c := make(chan *Node) | |
go func() { | |
for _, r := range n.Children { | |
c <- r | |
} | |
close(c) | |
}() | |
return c | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment