diff options
| -rw-r--r-- | calculator.go | 14 | ||||
| -rw-r--r-- | ui.go | 6 |
2 files changed, 17 insertions, 3 deletions
diff --git a/calculator.go b/calculator.go index f0ed7db..3493382 100644 --- a/calculator.go +++ b/calculator.go @@ -38,12 +38,24 @@ func (c *Calculator) swap() { c.stack.push(f) } if st != nil { - c.buf = strings.TrimSpace(printStackVal(*st)) + c.buf = strings.TrimSpace(printNum(*st)) } else { c.buf = "" } } +// negate negates the number in the buffer, if any; or the bottom number on the +// stack, if any. +func (c *Calculator) negate() { + if con := parseConstant(c.buf); con != nil { + c.buf = strings.TrimSpace(printNum(-*con)) + } else if f, err := strconv.ParseFloat(c.buf, 64); err == nil { + c.buf = strings.TrimSpace(printNum(-f)) + } else if len(c.buf) == 0 && len(c.stack) > 0 { + c.stack[len(c.stack)-1] = -c.stack[len(c.stack)-1] + } +} + // performOp performs the specified arithmetic operation and returns nil or // OpError if op is not a valid operator. func (c *Calculator) performOp(op byte) error { @@ -44,6 +44,8 @@ func (ui UI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case "C": ui.calc.buf = "" ui.calc.stack = ui.calc.stack[:0] + case "N": + ui.calc.negate() case "+", "-", "*", "/", "%", "^": if err := ui.calc.performOp(msg.String()[0]); err != nil { panic(err) @@ -71,7 +73,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 += printStackVal(f) + "\n" + s += printNum(f) + "\n" } s += boxTop(ui.windowWidth) + "\n" s += fmt.Sprintf("%[1]c%-*s%[1]c\n", boxVertical, ui.windowWidth-2, ui.calc.buf) @@ -79,7 +81,7 @@ func (ui UI) View() string { return s } -func printStackVal(v float64) string { +func printNum(v float64) string { return fmt.Sprintf(" %.*g", sigDigs, v) } |