Last active
March 30, 2021 23:28
-
-
Save mcastelino/267ae5da60ae5f52802b72822b888ef3 to your computer and use it in GitHub Desktop.
Golang: Create a Acyclic function graph
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 main | |
import ( | |
"fmt" | |
) | |
// Data that flows through the processing pipeline | |
type Data struct { | |
Type string | |
Data string | |
} | |
// The Handler function processes the data and then | |
// call the handlers downstream from itself | |
// Each downstream function gets its own copy of the data | |
type Handler func(Data) error | |
type HandlerChain interface { | |
Chain([]Handler) Handler | |
} | |
type Node struct { | |
Name string | |
} | |
func (n *Node) Chain(h ...Handler) Handler { | |
return func(d Data) error { | |
downstreamHandlers := h | |
d.Data = d.Data + "->" + n.Name | |
for _, f := range downstreamHandlers { | |
if f == nil { | |
fmt.Println(d.Data) | |
return nil | |
} | |
if err := f(d); err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
} | |
func main() { | |
a := Node{"A"} | |
b := Node{"B"} | |
c := Node{"C"} | |
d := Node{"D"} | |
e := Node{"E"} | |
f := Node{"F"} | |
path1 := b.Chain(c.Chain(nil)) | |
path2 := d.Chain(d.Chain(e.Chain(nil))) | |
path3 := f.Chain(path1, path2) | |
tree := a.Chain(path1, path2, path3) | |
tree(Data{Data: "hello"}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment