-
-
Notifications
You must be signed in to change notification settings - Fork 22
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
Add IfFunc helper #99
Conversation
Codecov Report
@@ Coverage Diff @@
## master #99 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 9 9
Lines 491 496 +5
=========================================
+ Hits 491 496 +5
Continue to review full report at Codecov.
|
@oderwat @averageflow if you're still interested in this project and have some spare time, I would love to hear your thoughts on this little change. 😊 |
It is cool but I am not sure if it is so much better than a simple if/else. That is because you always have to type the function definition in addition to the construct itself. As this is needed you also can simply use it as the inline function. But with go-app (which I actually use now) the "app.If()" is much worse than your idea and I thought about having something similar to your version with go-app but then I ended up just inlining the if. See maxence-charriere/go-app#632 Sadly this is not possible with your package because the anonymous function does not satisfy the interface. I just leave this here package main
import (
g "github.com/maragudk/gomponents"
"os"
"testing"
)
func IfFunc(condition bool, cb func() g.Node) g.Node {
if condition {
return cb()
}
return nil
}
// N is needed to implement the interface for anonymous functions
func N(cb func() g.Node) g.Node {
// delegate to the anonymous function
return cb()
}
func IfTestA(t *testing.T) {
var message *string
e := g.El("div",
IfFunc(message != nil, func() g.Node {
return g.El("span", g.Text(*message))
}),
)
_ = e.Render(os.Stdout)
}
func IfTestB(t *testing.T) {
var messagePtr *string
e := g.El("div", N(func() (r g.Node) {
if messagePtr != nil {
r = g.El("span", g.Text(*messagePtr))
}
return
}))
_ = e.Render(os.Stdout)
} P.S.: Sadly there also is no way to create a |
`Func` is a function that returns a `Node` that is itself also a `Node`. Used with `If`, it enables lazy evaluation of the node to return, depending on the condition passed to `If`. See also #99 for a different approach explored.
@oderwat thank you for your detailed reply! You're very kind. 😊 Your Any additional thoughts? |
I have moved on from my previous position, and don't work withGo, or with frontends anymore, but @dadobos does. |
IfFunc
is likeIf
, except it takes a callback function that returns aNode
instead of aNode
directly.Great when the condition is a nil check and the function uses the value that's not nil.