Update docs for Graph and Node

Updates godoc and adds Add() method instead of using
append on the private slice.

Signed-off-by: Alex Ellis (OpenFaaS Ltd) <alexellis2@gmail.com>
This commit is contained in:
Alex Ellis (OpenFaaS Ltd) 2020-06-17 13:00:31 +01:00 committed by Alex Ellis
parent 2b9efd29a0
commit 88f1aa0433
2 changed files with 52 additions and 45 deletions

View File

@ -1,6 +1,8 @@
package pkg
import "fmt"
import (
"log"
)
func buildInstallOrder(svcs []Service) []string {
graph := Graph{nodes: []*Node{}}
@ -24,10 +26,10 @@ func buildInstallOrder(svcs []Service) []string {
resolve(g, resolved, unresolved)
}
fmt.Printf("Installation order:\n")
log.Printf("Start-up order:\n")
order := []string{}
for _, node := range resolved.nodes {
fmt.Printf("- %s\n", node.Name)
log.Printf("- %s\n", node.Name)
order = append(order, node.Name)
}

View File

@ -2,12 +2,57 @@ package pkg
import "log"
// Node represents a node in a Graph with
// 0 to many edges
type Node struct {
Name string
Edges []*Node
}
// Graph is a collection of nodes
type Graph struct {
nodes []*Node
}
// Contains returns true if the target Node is found
// in its list
func (g *Graph) Contains(target *Node) bool {
for _, g := range g.nodes {
if g.Name == target.Name {
return true
}
}
return false
}
// Add places a Node into the current Graph
func (g *Graph) Add(target *Node) {
g.nodes = append(g.nodes, target)
}
// Remove deletes a target Node reference from the
// list of nodes in the graph
func (g *Graph) Remove(target *Node) {
var found *int
for i, n := range g.nodes {
if n == target {
found = &i
break
}
}
if found != nil {
g.nodes = append(g.nodes[:*found], g.nodes[*found+1:]...)
}
}
// resolve finds the order of dependencies for a graph
// of nodes.
// Inspired by algorithm from
// https://www.electricmonk.nl/log/2008/08/07/dependency-resolving-algorithm/
func resolve(node *Node, resolved, unresolved *Graph) {
unresolved.nodes = append(unresolved.nodes, node)
unresolved.Add(node)
for _, edge := range node.Edges {
@ -24,46 +69,6 @@ func resolve(node *Node, resolved, unresolved *Graph) {
}
}
resolved.nodes = append(resolved.nodes, node)
resolved.Add(node)
unresolved.Remove(node)
}
func newNode(name string, edges []*Node) *Node {
return &Node{
Name: name,
Edges: edges,
}
}
type Node struct {
Name string
Edges []*Node
}
type Graph struct {
nodes []*Node
}
func (g *Graph) Contains(target *Node) bool {
for _, g := range g.nodes {
if g.Name == target.Name {
return true
}
}
return false
}
func (g *Graph) Remove(target *Node) {
var found *int
for i, n := range g.nodes {
if n == target {
found = &i
break
}
}
if found != nil {
g.nodes = append(g.nodes[:*found], g.nodes[*found+1:]...)
}
}