diff --git a/go/parsing-a-boolean-expression.go b/go/parsing-a-boolean-expression.go new file mode 100644 index 0000000..6fc3ae9 --- /dev/null +++ b/go/parsing-a-boolean-expression.go @@ -0,0 +1,54 @@ +package main + +import ( + arraystack "github.com/emirpasic/gods/v2/stacks/arraystack" +) + +func parseBoolExpr(expression string) bool { + getRune := func(result bool) rune { + if result { + return 't' + } + return 'f' + } + + st := arraystack.New[rune]() + + for _, token := range expression { + if token == ',' || token == '(' { + // ignore delimiters and opening brackets + continue + } + + // Handle closing of the operation + if token == ')' { + hasTrue, hasFalse := false, false + + for top, has := st.Peek(); has && top != '!' && top != '&' && top != '|'; top, has = st.Peek() { + if top == 't' { + hasTrue = true + } else if top == 'f' { + hasFalse = true + } + st.Pop() + } + + // evaluate the operator + op, _ := st.Pop() + if op == '!' { + st.Push(getRune(!hasTrue)) + } else if op == '&' { + st.Push(getRune(!hasFalse)) + } else { + st.Push(getRune(hasTrue)) + } + + continue + } + + st.Push(token) + } + + result, _ := st.Peek() + return result == 't' +}