Skip to content

Commit

Permalink
use generics for contains() and add generic exists()
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas von Dein committed Dec 7, 2023
1 parent d2db420 commit d9a0d61
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 21 deletions.
32 changes: 15 additions & 17 deletions calc.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ func (c *Calc) Eval(line string) {
continue
}

if _, ok := c.Funcalls[item]; ok {
if exists(c.Funcalls, item) {
if err := c.DoFuncall(item); err != nil {
fmt.Println(err)
} else {
Expand All @@ -270,20 +270,18 @@ func (c *Calc) Eval(line string) {
continue
}

if c.batch {
if _, ok := c.BatchFuncalls[item]; ok {
if err := c.DoFuncall(item); err != nil {
fmt.Println(err)
} else {
c.Result()
}
continue
}
} else {
if _, ok := c.BatchFuncalls[item]; ok {
if exists(c.BatchFuncalls, item) {
if !c.batch {
fmt.Println("only supported in batch mode")
continue
}

if err := c.DoFuncall(item); err != nil {
fmt.Println(err)
} else {
c.Result()
}
continue
}

if contains(c.LuaFunctions, item) {
Expand All @@ -304,22 +302,22 @@ func (c *Calc) Eval(line string) {
}

// internal commands
if _, ok := c.Commands[item]; ok {
if exists(c.Commands, item) {
c.Commands[item].Func(c)
continue
}

if _, ok := c.ShowCommands[item]; ok {
if exists(c.ShowCommands, item) {
c.ShowCommands[item].Func(c)
continue
}

if _, ok := c.StackCommands[item]; ok {
if exists(c.StackCommands, item) {
c.StackCommands[item].Func(c)
continue
}

if _, ok := c.SettingsCommands[item]; ok {
if exists(c.SettingsCommands, item) {
c.SettingsCommands[item].Func(c)
continue
}
Expand Down Expand Up @@ -507,7 +505,7 @@ func (c *Calc) PutVar(name string) {
}

func (c *Calc) GetVar(name string) {
if _, ok := c.Vars[name]; ok {
if exists(c.Vars, name) {
c.Debug(fmt.Sprintf("retrieve %.2f from %s", c.Vars[name], name))
c.stack.Backup()
c.stack.Push(c.Vars[name])
Expand Down
16 changes: 12 additions & 4 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,24 @@ import (
"strings"
)

// find an item in a list
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
// find an item in a list, generic variant
func contains[E comparable](s []E, v E) bool {
for _, vs := range s {
if v == vs {
return true
}
}
return false
}

// look if a key in a map exists, generic variant
func exists[K comparable, V any](m map[K]V, v K) bool {
if _, ok := m[v]; ok {
return true
}
return false
}

func const2num(name string) float64 {
switch name {
case "Pi":
Expand Down

0 comments on commit d9a0d61

Please sign in to comment.