diff options
| -rw-r--r-- | const.go | 14 | ||||
| -rw-r--r-- | func.go | 18 | ||||
| -rw-r--r-- | main.go | 6 | ||||
| -rw-r--r-- | ui.go | 12 |
4 files changed, 45 insertions, 5 deletions
diff --git a/const.go b/const.go new file mode 100644 index 0000000..60bae20 --- /dev/null +++ b/const.go @@ -0,0 +1,14 @@ +package main + +import "math" + +// parseConstant returns nil if s is not a valid constant. +func parseConstant(s string) *float64 { + switch s { + case "pi": + // Assign to variable because can't take address of constant. + var pi float64 = math.Pi + return &pi + } + return nil +} @@ -0,0 +1,18 @@ +package main + +import "math" + +// parseFunction returns nil is s is not a valid function. +func parseFunction(s string) func(Stack) { + switch s { + case "sin": + return sin + } + return nil +} + +func sin(stack Stack) { + if len(stack) > 0 { + stack[len(stack)-1] = math.Sin(stack[len(stack)-1]) + } +} @@ -7,14 +7,12 @@ import ( "github.com/charmbracelet/bubbletea" ) -// Types - type Calculator struct { - stack []float64 + stack Stack buffer string } -// Function Definitions +type Stack []float64 func main() { if _, err := tea.NewProgram(new(UI)).Run(); err != nil { @@ -2,6 +2,7 @@ package main import ( "fmt" + "strconv" "github.com/charmbracelet/bubbletea" ) @@ -40,6 +41,15 @@ func (ui UI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if len(ui.calc.buffer) > 0 { ui.calc.buffer = ui.calc.buffer[:len(ui.calc.buffer)-1] } + case "enter": + if fn := parseFunction(ui.calc.buffer); fn != nil { + fn(ui.calc.stack) + } else if con := parseConstant(ui.calc.buffer); con != nil { + ui.calc.stack = append(ui.calc.stack, *con) + } else if f, err := strconv.ParseFloat(ui.calc.buffer, 64); err != nil { + ui.calc.stack = append(ui.calc.stack, f) + } + ui.calc.buffer = "" default: ui.calc.buffer += msg.String() } @@ -50,7 +60,7 @@ func (ui UI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { func (ui UI) View() string { var s string for _, f := range ui.calc.stack { - s += fmt.Sprintf("%.*g\n", sigDigs, f) + s += fmt.Sprintf(" %.*g\n", sigDigs, f) } s += boxTop(ui.windowWidth) + "\n" s += fmt.Sprintf("%[1]c%-*s%[1]c\n", boxVertical, ui.windowWidth-2, ui.calc.buffer) |