diff options
| -rw-r--r-- | calculator.go | 26 | ||||
| -rw-r--r-- | main.go | 7 | ||||
| -rw-r--r-- | ui.go | 2 |
3 files changed, 28 insertions, 7 deletions
diff --git a/calculator.go b/calculator.go new file mode 100644 index 0000000..30cc7ec --- /dev/null +++ b/calculator.go @@ -0,0 +1,26 @@ +package main + +import "strconv" + +type Stack []float64 + +type Calculator struct { + stack Stack + buffer string +} + +// add performs addition when the user inputs the '+' operator. +func (c *Calculator) add() { + if len(c.stack) < 1 { + return + } + if con := parseConstant(c.buffer); con != nil { + c.stack[len(c.stack)-1] += *con + } else if f, err := strconv.ParseFloat(c.buffer, 64); err == nil { + c.stack[len(c.stack)-1] += f + } else if len(c.stack) > 1 { + c.stack[len(c.stack)-2] += c.stack[len(c.stack)-1] + c.stack = c.stack[:len(c.stack)-1] + } + c.buffer = "" +} @@ -7,13 +7,6 @@ import ( "github.com/charmbracelet/bubbletea" ) -type Calculator struct { - stack Stack - buffer string -} - -type Stack []float64 - func main() { if _, err := tea.NewProgram(new(UI)).Run(); err != nil { fmt.Fprintf(os.Stderr, "%v", err) @@ -37,6 +37,8 @@ func (ui UI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg.String() { case "ctrl+c", "Q": return ui, tea.Quit + case "+": + ui.calc.add() case "backspace": if len(ui.calc.buffer) > 0 { ui.calc.buffer = ui.calc.buffer[:len(ui.calc.buffer)-1] |