Skip to content

feat(example): calculator realm #4084

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 26 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
9b9492a
feat: add calculator and home realm
NicolasMelet Apr 9, 2025
354b409
feat: changed txlink for path querry, compute still in progress
NicolasMelet Apr 10, 2025
69c4861
feat: computation now works again, app fully handled with path
NicolasMelet Apr 11, 2025
e330d9c
clean: removed useless variable and added documentation
NicolasMelet Apr 11, 2025
345cc21
feat: added unit tests
NicolasMelet Apr 11, 2025
8cd3d2a
fix: changed panick errors to standart error handling for evaluateVal…
NicolasMelet Apr 14, 2025
44cb487
feat: parenthesis now available
NicolasMelet Apr 14, 2025
f7ebebc
feat: handle negative values + added tests
NicolasMelet Apr 14, 2025
c7b7ad9
Merge branch 'master' into master
NicolasMelet Apr 14, 2025
7787495
fix: unexport render functions
NicolasMelet Apr 14, 2025
9aaa711
clean: removed newlines in tests
NicolasMelet Apr 14, 2025
ffeae14
clean: use out string instead of strings builder
NicolasMelet Apr 14, 2025
def6b5c
clean: use md package for markdown
NicolasMelet Apr 15, 2025
09209d1
Merge branch 'master' into master
NicolasMelet Apr 15, 2025
c566b19
Merge branch 'master' into master
leohhhn Apr 15, 2025
e10b516
clean: used mdtable package
NicolasMelet Apr 16, 2025
7df0d90
chore: remove home realm
NicolasMelet Apr 16, 2025
d529ff5
Merge branch 'master' into master
NicolasMelet Apr 16, 2025
8a1f4e7
Merge branch 'master' into master
NicolasMelet Apr 17, 2025
c34cbf4
fix: parenthesis can appear in url + cleanup table making in code
NicolasMelet Apr 17, 2025
99fd13f
Merge branch 'master' into master
NicolasMelet Apr 17, 2025
2749424
Merge branch 'master' into master
NicolasMelet Apr 18, 2025
d216360
Merge branch 'master' into master
NicolasMelet Apr 22, 2025
ffeda4b
Merge branch 'master' into master
NicolasMelet Apr 23, 2025
e2ddb3c
Merge branch 'master' into master
NicolasMelet Apr 30, 2025
cda0688
Merge branch 'master' into master
NicolasMelet Apr 30, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 212 additions & 0 deletions examples/gno.land/r/miko/calculator/calculator.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
package calculator

import (
"strconv"
"strings"

"gno.land/p/demo/ufmt"
"gno.land/p/moul/realmpath"
"gno.land/r/leon/hof"
)

type Node struct {
value string // Value of the current node
left *Node
right *Node
}

const (
specialCharacters = "p-*/."
topPriority = "*/"
lowPriority = "p-"

realmPath = "/r/miko/calculator"
)

var (
val float64
displayVal string

operationMap = map[string]func(left float64, right float64) float64{
"p": func(left float64, right float64) float64 { return left + right },
"-": func(left float64, right float64) float64 { return left - right },
"*": func(left float64, right float64) float64 { return left * right },
"/": func(left float64, right float64) float64 {
if right == 0 {
panic("Division by 0 is forbidden")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 0 division can only be detected when reading the tree, and I don't see a way of properly handling this case that doesn't involve a weird third parameter for all operation function, or a global variable

}
return left / right
},
}
)

func init() {
hof.Register("Miko's calculator", "Let's do maths")
}

func evaluateValidity(line string) (bool, string) {
if len(line) == 0 {
return false, "Invalid empty input"
} // edge case empty line
if strings.Index(specialCharacters, string(line[0])) != -1 ||
strings.Index(specialCharacters, string(line[len(line)-1])) != -1 {
return false, "Invalid equation"
} // edge case special character at begining or end

isPriorSpecial := false
countParenthesis := 0

for i := 0; i < len(line); i++ {
if line[i] == '<' {
countParenthesis += 1
continue
}
if line[i] == '>' {
if isPriorSpecial == true {
return false, "Invalid equation"
}
countParenthesis -= 1
isPriorSpecial = false
continue
}
if strings.Index(specialCharacters, string(line[i])) != -1 {
if isPriorSpecial {
return false, "Invalid equation"
}
isPriorSpecial = true
continue
}
if line[i] != 'p' && (line[i] < '0' || line[i] > '9') {
return false, "Invalid character encountered "
}
isPriorSpecial = false
}

if countParenthesis != 0 {
return false, "Invalid equation"
}
println(countParenthesis)
return true, ""
}

func searchForPriority(priorityList string, line string) *Node {
// for i := 0; i < len(priorityList); i++ {
// idx := strings.Index(line, string(priorityList[i]))
// if idx != -1 {
// return &Node{string(line[idx]), createTree(line[:idx]), createTree(line[idx+1:])}
// }
// }

countParenthesis := 0
for iPrio := 0; iPrio < len(priorityList); iPrio++ {
for idx := 0; idx < len(line); idx++ {
if line[idx] == '<' {
countParenthesis += 1
}
if line[idx] == '>' {
countParenthesis -= 1
}
if countParenthesis == 0 && line[idx] == priorityList[iPrio] {
println("seen operator")
return &Node{string(line[idx]), createTree(line[:idx]), createTree(line[idx+1:])}
}

}
}
return nil
}

func createTree(line string) *Node {
println(line)
if line[0] == '<' && line[len(line)-1] == '>' && strings.Index(line[1:], "<") == -1 {
println("no parenthesis anymore")
return createTree(line[1 : len(line)-1])
}
node := searchForPriority(lowPriority, line) // we put the lowest priority at the top of the tree, these operations will be executed last
if node != nil {
return node
}
node = searchForPriority(topPriority, line)
if node != nil {
return node
}

// if this code is reached, the only value possible in line is a number
return &Node{line, nil, nil}
}

func readTree(tree *Node) float64 {
operation, exists := operationMap[tree.value]

if exists { // check if the current node is an operator
return operation(readTree(tree.left), readTree(tree.right))
}

parsedValue, _ := strconv.ParseFloat(tree.value, 64)

return parsedValue
}

// expression is the equation you want to solve (p replaces the + symbol)
// exemple: 2p4/2
func ComputeResult(expression string) string {
valid, errString := evaluateValidity(expression)

if !valid { // If a basic error is encountered, return the expression without the = at the end and display the same expression
println(errString) // display error for debug
displayVal = strings.Replace(expression, "p", "+", -1)
displayVal = strings.Replace(displayVal, "<", "(", -1)
displayVal = strings.Replace(displayVal, ">", ")", -1)
return expression
}

tree := createTree(expression)

val = readTree(tree)
displayVal = strconv.FormatFloat(val, 'g', 6, 64)
return displayVal
}

func removeLast(path string) string {
lenPath := len(path)
if lenPath > 0 {
path = path[:lenPath-1]
}
return path
}

func Render(path string) string {
var sb strings.Builder

req := realmpath.Parse(path)
query := req.Query
expression := query.Get("expression")

if expression == "" {
displayVal = "0"
} else {
if expression[len(expression)-1] == '=' {
expression = ComputeResult(expression[:len(expression)-1])
} else {
displayVal = strings.Replace(expression, "p", "+", -1)
displayVal = strings.Replace(displayVal, "<", "(", -1)
displayVal = strings.Replace(displayVal, ">", ")", -1)
}
}

sb.WriteString(`# Calculator page

Have you ever wanted to do maths but never actually found a calculator ?
Do I have the realm for you...

Result: ` + displayVal + `
---------------
| ` + ufmt.Sprintf("[res](%s)", realmPath) + `| ` + ufmt.Sprintf("[(](%s)", realmPath+":?expression="+expression+"<") + `| ` + ufmt.Sprintf("[)](%s)", realmPath+":?expression="+expression+">") + `| ` + ufmt.Sprintf("[del](%s)", realmPath+":?expression="+removeLast(expression)) + `|
|---|---|---|---|
| ` + ufmt.Sprintf("[7](%s)", realmPath+":?expression="+expression+"7") + `| ` + ufmt.Sprintf("[8](%s)", realmPath+":?expression="+expression+"8") + `| ` + ufmt.Sprintf("[9](%s)", realmPath+":?expression="+expression+"9") + `| ` + ufmt.Sprintf("[+](%s)", realmPath+":?expression="+expression+"p") /* here p replaces + because of how + works in bnormal paths*/ + `|
| ` + ufmt.Sprintf("[4](%s)", realmPath+":?expression="+expression+"4") + `| ` + ufmt.Sprintf("[5](%s)", realmPath+":?expression="+expression+"5") + `| ` + ufmt.Sprintf("[6](%s)", realmPath+":?expression="+expression+"6") + `| ` + ufmt.Sprintf("[-](%s)", realmPath+":?expression="+expression+"-") + `|
| ` + ufmt.Sprintf("[1](%s)", realmPath+":?expression="+expression+"1") + `| ` + ufmt.Sprintf("[2](%s)", realmPath+":?expression="+expression+"2") + `| ` + ufmt.Sprintf("[3](%s)", realmPath+":?expression="+expression+"3") + `| ` + ufmt.Sprintf("[*](%s)", realmPath+":?expression="+expression+"*") + `|
| ` + ufmt.Sprintf("[0](%s)", realmPath+":?expression="+expression+"0") + `| ` + ufmt.Sprintf("[.](%s)", realmPath+":?expression="+expression+".") + `| ` + ufmt.Sprintf("[=](%s)", realmPath+":?expression="+expression+"=") + `| ` + ufmt.Sprintf("[/](%s)", realmPath+":?expression="+expression+"/") + `|
`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try out a library for this, such as p/moul/md

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have used this library for the mardown, but for the columns it isn't exactly what I need as the Columns() function always put "|||' between each column, which gives another display than simply "|"

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh sorry, i meant p/moul/mdtable :)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

e10b516
Done !

return sb.String()
}
91 changes: 91 additions & 0 deletions examples/gno.land/r/miko/calculator/calculator_test.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package calculator

import "testing"

func TestCounter_Addition(t *testing.T) {

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove these newlines :)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

9aaa711
Done !

// Increment the value
value := ComputeResult("1p1")

// Verify the value is equal to 2
if value != "2" {
t.Fatalf("1 + 1 is not equal to 2")
}
}

func TestCounter_Subtraction(t *testing.T) {

// Increment the value
value := ComputeResult("1-1")

// Verify the value is equal to 0
if value != "0" {
t.Fatalf("1 - 1 is not equal to 0")
}
}

func TestCounter_Multiplication(t *testing.T) {

// Increment the value
value := ComputeResult("1*4")

// Verify the value is equal to 4
if value != "4" {
t.Fatalf("1 * 4 is not equal to 4")
}
}

func TestCounter_Division(t *testing.T) {

// Increment the value
value := ComputeResult("4/2")

// Verify the value is equal to 2
if value != "2" {
t.Fatalf("4 / 2 is not equal to 2")
}
}

func TestCounter_AdditionDecimal(t *testing.T) {

// Increment the value
value := ComputeResult("1.2p1.3")

// Verify the value is equal to 2.5
if value != "2.5" {
t.Fatalf("1.2 + 1.3 is not equal to 2.5")
}
}

func TestCounter_SubtractionDecimal(t *testing.T) {

// Increment the value
value := ComputeResult("1.3-1.2")

// Verify the value is equal to 0.1
if value != "0.1" {
t.Fatalf("1.3 - 1.2 is not equal to 0.1")
}
}

func TestCounter_MultiplicationDecimal(t *testing.T) {

// Increment the value
value := ComputeResult("3*1.5")

// Verify the value is equal to 4.5
if value != "4.5" {
t.Fatalf("3 * 1.5 is not equal to 4.5")
}
}

func TestCounter_DivisionDecimal(t *testing.T) {

// Increment the value
value := ComputeResult("2/0.5")

// Verify the value is equal to 4
if value != "4" {
t.Fatalf("2 / 0.5 is not equal to 4")
}
}
1 change: 1 addition & 0 deletions examples/gno.land/r/miko/calculator/gno.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module gno.land/r/miko/calculator
1 change: 1 addition & 0 deletions examples/gno.land/r/miko/home/gno.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module gno.land/r/miko/home
48 changes: 48 additions & 0 deletions examples/gno.land/r/miko/home/home.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package home

import (
"gno.land/p/demo/ufmt"
)

var count int

// this here serves to increment my counter
func Increment() {
count++
}

func Decrement() {
count--
}

func init() {
count = 0 // arbitrary value
}

func Render(_ string) string {
out := "# Hey !\n"
out += "My name is Nicolas, french student in computer science !\n\n"
out += "Want to hear about me ?\n\n"
out += RenderPassion()
out += RenderCounter()
return out
}

func RenderPassion() string {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these can be unexported

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7787495
Done !

out := "## Passions\n\n"
out += "### I love:\n\n"
out += "Crying about Hollow knight silksong never coming out\n\n"
out += "![Silksong for 2025 confirmed](https://media.discordapp.net/attachments/1221580738487390268/1357382383166291978/FKcRXNtkuNwC7bL24mgznJq5.png?ex=67f0005b&is=67eeaedb&hm=1610610eff0fbbe10c0492bd63ae6c4f57c2c2586c1e52639330b1d394381033&=&format=webp&quality=lossless&width=233&height=350)"
out += "\n\n"
out += "Playing the award winning MMORPG Final Fantasy XIV online\n\n"
out += "And when I'm not doing any of the above, I like coding in C/C++ ~( °v°)\n"
return out
}

func RenderCounter() string {
out := "## Secret counter\n\n"
out += "No one really knows what this counter actually counts\n\n"
out += "**" + ufmt.Sprintf("%d", count) + "**"
out += "\n\n\n... but it really ain't that high\n\n"
return out
}
Loading