From 5b81647c27af77be3d35e10cb53cad1897a7f392 Mon Sep 17 00:00:00 2001 From: Sam Anthony Date: Sat, 29 Jul 2023 10:29:15 -0230 Subject: negation command --- calculator.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'calculator.go') 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 { -- cgit v1.2.3