aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2023-07-29 10:29:15 -0230
committerSam Anthony <sam@samanthony.xyz>2023-07-29 10:29:15 -0230
commit5b81647c27af77be3d35e10cb53cad1897a7f392 (patch)
tree0d6aab66a9675500b6df449ace25fadb612c86d4
parentfd46878cfa5978a081f1ffdb865394aff234dbc9 (diff)
downloadpfc-5b81647c27af77be3d35e10cb53cad1897a7f392.zip
negation command
-rw-r--r--calculator.go14
-rw-r--r--ui.go6
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 {
diff --git a/ui.go b/ui.go
index 6596b77..85919c4 100644
--- a/ui.go
+++ b/ui.go
@@ -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)
}