From bb49cb762655c5ab446d9a414aea26a21b30a20b Mon Sep 17 00:00:00 2001 From: "T.v.Dein" Date: Mon, 6 Nov 2023 20:12:07 +0100 Subject: [PATCH] Feature/add show stack (#5) * add -s flag and show command to display the last 5 entries --- calc.go | 23 ++++++++++++++++++++++- main.go | 2 ++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/calc.go b/calc.go index 038b439..d9f6353 100644 --- a/calc.go +++ b/calc.go @@ -32,6 +32,7 @@ type Calc struct { debug bool batch bool stdin bool + showstack bool stack *Stack history []string completer readline.AutoCompleter @@ -48,6 +49,7 @@ type Calc struct { const Help string = `Available commands: batch toggle batch mode debug toggle debug output +show show the last 5 items of the stack dump display the stack contents clear clear the whole stack shift remove the last element of the stack @@ -81,7 +83,7 @@ median median of all values` // commands, constants and operators, defined here to feed completion // and our mode switch in Eval() dynamically const ( - Commands string = `dump reverse debug undebug clear batch shift undo help history manual exit quit swap` + Commands string = `dump reverse debug undebug clear batch shift undo help history manual exit quit swap show` Constants string = `Pi Phi Sqrt2 SqrtE SqrtPi SqrtPhi Ln2 Log2E Ln10 Log10E` ) @@ -162,14 +164,21 @@ func (c *Calc) ToggleStdin() { c.stdin = !c.stdin } +func (c *Calc) ToggleShow() { + c.showstack = !c.showstack +} + func (c *Calc) Prompt() string { p := "\033[31m»\033[0m " b := "" + if c.batch { b = "->batch" } + d := "" v := "" + if c.debug { d = "->debug" v = fmt.Sprintf("/rev%d", c.stack.rev) @@ -271,6 +280,8 @@ func (c *Calc) Eval(line string) { for _, entry := range c.history { fmt.Println(entry) } + case "show": + c.ToggleShow() case "exit": fallthrough case "quit": @@ -282,6 +293,16 @@ func (c *Calc) Eval(line string) { } } } + + if c.showstack && !c.stdin { + dots := "" + + if c.stack.Len() > 5 { + dots = "... " + } + last := c.stack.Last(5) + fmt.Printf("stack: %s%s\n", dots, list2str(last)) + } } // Execute a math function, check if it is defined just in case diff --git a/main.go b/main.go index 2d180be..7b3708f 100644 --- a/main.go +++ b/main.go @@ -39,6 +39,7 @@ Usage: rpn [-bdvh] [] Options: -b, --batchmode enable batch mode -d, --debug enable debug mode + -s, --stack show last 5 items of the stack (off by default) -m, --manual show manual -v, --version show version -h, --help show help @@ -58,6 +59,7 @@ func main() { configfile := "" flag.BoolVarP(&calc.batch, "batchmode", "b", false, "batch mode") + flag.BoolVarP(&calc.showstack, "showstack", "s", false, "show stack") flag.BoolVarP(&enabledebug, "debug", "d", false, "debug mode") flag.BoolVarP(&showversion, "version", "v", false, "show version") flag.BoolVarP(&showhelp, "help", "h", false, "show usage")