Skip to content

Instantly share code, notes, and snippets.

@caelifer
Last active August 25, 2016 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caelifer/02fa5a60463e1e78e7795c607be4bd50 to your computer and use it in GitHub Desktop.
Save caelifer/02fa5a60463e1e78e7795c607be4bd50 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strings"
)
// Global scope level
var scope = new(ScopeLevel)
func main() {
for _, op := range []string{
// program
"open",
"open",
"read",
"open",
"write",
"close",
"close",
"open",
"read",
"open",
"read",
"open",
"read",
"close",
"close",
"close",
"write",
"close",
} {
// Format based on scope
Print(op)
}
}
// Ops to Scope command map
var rules = map[string]func(string){
"open": scope.enter,
"close": scope.exit,
}
// Print is a helper function to format ops
func Print(op string) {
if sc, ok := rules[op]; ok {
sc(op)
return
}
scope.print(op)
}
// ScopeLevel type
type ScopeLevel int
func (s *ScopeLevel) enter(op string) {
s.print(op)
*s++
}
func (s *ScopeLevel) exit(op string) {
if *s > 0 {
*s--
}
s.print(op)
}
func (s *ScopeLevel) print(op string) {
leftPad := ""
if *s > 0 {
leftPad = strings.Repeat("\t", int(*s))
}
fmt.Println(leftPad + op + "()")
}
@caelifer
Copy link
Author

caelifer commented Aug 25, 2016

Live code - https://play.golang.org/p/8Kwy_7Lqna

Output:

open()
    open()
        read()
        open()
            write()
        close()
    close()
    open()
        read()
        open()
            read()
            open()
                read()
            close()
        close()
    close()
    write()
close()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment