Last active
August 25, 2016 17:27
-
-
Save caelifer/02fa5a60463e1e78e7795c607be4bd50 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 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 + "()") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live code - https://play.golang.org/p/8Kwy_7Lqna
Output: