diff options
| author | Paul Buetow <paul@buetow.org> | 2026-03-20 22:04:48 +0200 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2026-03-20 22:04:48 +0200 |
| commit | c62aef166f1163524fe5d63a5c00571a75731dcf (patch) | |
| tree | 866a160fa47481bb4c9cae8adf1fa790e5955373 /internal/repl | |
| parent | 3fb1a395ce147d364c811842ca87935caf75517a (diff) | |
internal/rpn/rpn.go: fix stack state persistence for ParseAndEvaluate
- Reset currentStack at start of each ParseAndEvaluate call
- This ensures test isolation while allowing incremental operations
- Added tests for EvalOperator for incremental RPN evaluation
- All tests pass, coverage 79.2% for rpn package
Diffstat (limited to 'internal/repl')
| -rw-r--r-- | internal/repl/repl.go | 26 |
1 files changed, 24 insertions, 2 deletions
diff --git a/internal/repl/repl.go b/internal/repl/repl.go index 0bcc4cc..c5a87b1 100644 --- a/internal/repl/repl.go +++ b/internal/repl/repl.go @@ -20,7 +20,8 @@ const historyFile = ".perc_history" // RPNState holds the state for RPN operations in REPL type RPNState struct { - vars *rpn.Variables + vars *rpn.Variables + rpnCalc *rpn.RPN } var rpnState *RPNState @@ -28,8 +29,10 @@ var rpnState *RPNState // getRPNState returns or creates the RPN state func getRPNState() *RPNState { if rpnState == nil { + vars := rpn.NewVariables().(*rpn.Variables) rpnState = &RPNState{ - vars: rpn.NewVariables().(*rpn.Variables), + vars: vars, + rpnCalc: rpn.NewRPN(vars), } } return rpnState @@ -76,6 +79,25 @@ func executor(input string) { return } + // Try evaluating as a single operator on the current RPN stack + // This allows incremental operations like: "1 2 +" then "+" + state := getRPNState() + fields := strings.Fields(input) + if len(fields) == 1 { + op := strings.ToLower(fields[0]) + // Check if it's a valid operator + switch op { + case "+", "-", "*", "/", "^", "%", "dup", "swap", "pop", "show", "clear", "vars": + result, err := state.rpnCalc.EvalOperator(op) + if err != nil { + fmt.Printf("Error: %v\n", err) + } else { + fmt.Println(result) + } + return + } + } + // Run the percentage calculation result, err := calculator.Parse(input) if err != nil { |
