package termboxModules import "github.com/nsf/termbox-go" // Calculator An input field that allows simple maths type Calculator struct { text string input *InputField x, y, width, height int cursor int bg, fg termbox.Attribute history []string opStack []string showHistoryLines int } // CreateCalculator Create a calculator module func CreateCalculator(x, y, width, height int, fg, bg termbox.Attribute) *Calculator { i := Calculator{x: x, y: y, width: width, height: height, fg: fg, bg: bg, showHistoryLines: 0} i.input = CreateInputField(i.x, i.y, i.width, 2, i.fg, i.bg) i.input.bordered = true return &i } // PushOpStack Pushes a value onto the opStack func (calc *Calculator) PushOpStack(v string) { calc.opStack = append(calc.opStack, v) } // PopOpStack Pops the last value off of the opStack func (calc *Calculator) PopOpStack() string { prevEntry := opStack[len(opStack)-1] calc.opStack = opStack[:len(opStack)-1] return prevEntry } // HandleKeyPress Handle the termbox event, return true if it was consumed func (calc *Calculator) HandleKeyPress(event termbox.Event) bool { if event.Ch == '+' || event.Ch == '-' || event.Ch == '*' || event.Ch == '/' { // Save the value of input to opStack calc.PushOpStack(i.input.GetValue()) calc.PushOpStack(string(event.Ch)) i.input.SetValue("") return true } else if event.Ch == '=' { // Perform the operation var total int // Go ltr through stack doing all multiplication & division /* for len(opStack) > 0 { prevEntry := calc.PopStack() if prevEntry == "+" { prevEntry = calc.PopStack() if addVal, err := strconv.Atoi(prevEntry); err == nil { total = total + addVal } } else if prevEntry == "-" { prevEntry = calc.PopStack() if subVal, err := strconv.Atoi(prevEntry); err == nil { total = total - subVal } } else if prevEntry == "*" { prevEntry = calc.PopStack() if multVal, err := strconv.Atoi(prevEntry); err == nil { total = total * multVal } } else if prevEntry == "/" { prevEntry = calc.PopStack() if divVal, err := strconv.Atoi(prevEntry); err == nil { total = total / divVal } } } */ } else if event.Ch == '0' || event.Ch == '1' || event.Ch == '2' || event.Ch == '3' || event.Ch == '4' || event.Ch == '5' || event.Ch == '6' || event.Ch == '7' || event.Ch == '8' || event.Ch == '9' { return i.input.HandleKeyPress(event) } return false }