aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--calculator.go26
-rw-r--r--main.go7
-rw-r--r--ui.go2
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 = ""
+}
diff --git a/main.go b/main.go
index 78f4665..85766f2 100644
--- a/main.go
+++ b/main.go
@@ -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)
diff --git a/ui.go b/ui.go
index 7472dcd..e32d20f 100644
--- a/ui.go
+++ b/ui.go
@@ -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]