102 lines
1.9 KiB
Go
102 lines
1.9 KiB
Go
|
package calc
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
|
||
|
"gitea.zaclys.com/bvaudour/gob/number"
|
||
|
"gitea.zaclys.com/bvaudour/gob/option"
|
||
|
)
|
||
|
|
||
|
type MacroElement = option.Choice[number.Number, CalcFunc]
|
||
|
|
||
|
type MacroStack []MacroElement
|
||
|
|
||
|
type Macro map[string]MacroStack
|
||
|
|
||
|
func MacroNumber(n number.Number) MacroElement { return option.Left[number.Number, CalcFunc](n) }
|
||
|
|
||
|
func MacroCommand(c CalcFunc) MacroElement { return option.Right[number.Number, CalcFunc](c) }
|
||
|
|
||
|
func (s MacroStack) Clone() MacroStack {
|
||
|
out := make(MacroStack, len(s))
|
||
|
copy(out, s)
|
||
|
|
||
|
return out
|
||
|
}
|
||
|
|
||
|
func NewMacroStack(args ...any) option.Result[MacroStack] {
|
||
|
var s MacroStack
|
||
|
for _, e := range args {
|
||
|
if n, ok := e.(number.Number); ok {
|
||
|
s = append(s, MacroNumber(n))
|
||
|
} else if c, ok := e.(CalcFunc); ok {
|
||
|
s = append(s, MacroCommand(c))
|
||
|
} else {
|
||
|
return option.Err[MacroStack](ErrIsUnknow(fmt.Sprint(e)))
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return option.Ok(s)
|
||
|
}
|
||
|
|
||
|
func (m Macro) Exists(k string) (ok bool) {
|
||
|
_, ok = m[k]
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func (m Macro) Set(k string, s MacroStack) {
|
||
|
m[k] = s
|
||
|
}
|
||
|
|
||
|
func (m Macro) SetStack(k string, args ...any) (err option.Option[error]) {
|
||
|
result := NewMacroStack(args...)
|
||
|
if s, ok := result.Ok(); ok {
|
||
|
m.Set(k, s)
|
||
|
} else if e, ok := result.Err(); ok {
|
||
|
err = option.Some(e)
|
||
|
}
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func (m Macro) Get(k string) (result option.Result[MacroStack]) {
|
||
|
if s, ok := m[k]; ok {
|
||
|
result = option.Ok(s.Clone())
|
||
|
} else {
|
||
|
result = option.Err[MacroStack](ErrNotExist(mac(k)))
|
||
|
}
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func (m Macro) Reset(k string) (err option.Option[error]) {
|
||
|
if m.Exists(k) {
|
||
|
delete(m, k)
|
||
|
} else {
|
||
|
err = option.Some(ErrNotExist(mac(k)))
|
||
|
}
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func (m Macro) ResetAll() (err option.Option[error]) {
|
||
|
if len(m) > 0 {
|
||
|
for k := range m {
|
||
|
delete(m, k)
|
||
|
}
|
||
|
} else {
|
||
|
err = option.Some(ErrIsEmpty(errMemory))
|
||
|
}
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func (m Macro) Clone() Macro {
|
||
|
out := make(Macro)
|
||
|
for k, s := range m {
|
||
|
out[k] = s.Clone()
|
||
|
}
|
||
|
|
||
|
return out
|
||
|
}
|