-
Notifications
You must be signed in to change notification settings - Fork 10
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
Wrapping multiple optional values #8
Comments
Unfortunately the syntax isn't too great: maybe(valueX)
.flatMap(x => maybe(valueY).map(y => ({x, y})))
.foreach({x, y} => {
// use x and y
}) you can make it a tiny bit shorter by wrapping the values with maybe first e.g. const maybeX = maybe(valueX)
const maybeY = maybe(valueY)
maybeX
.flatMap(x => maybeY.map(y => ({x, y})))
.foreach({x, y} => {
// use x and y
}) Something that Scala has which is quite nice for this is a for {
x <- maybeX
y <- maybeY
// do something with x, y / return result
} yield ... |
Ah ok, yep. I was close. One thing I'm struggling with actually is when to use I wonder if there could be an extra method called something like
|
Just thought, couldn't you do this to make it even shorter? Given that you already know const maybeX = maybe(valueX)
const maybeY = maybe(valueY)
maybeX
.flatMap(x => maybeY)
.foreach(y => {
const x = maybeX.just() // we know maybeX is a Just because it passed the flatMap test
// use x and y
}) |
You use The best way to visualise and understand maybeX.map(x => maybeY) // Maybe(Maybe(y)) whereas maybeX.flatMap(x => maybeY) // Maybe(y) so |
It would be possible to make another type of For example: maybe([1, 2, 3])
.filter(a => a.every(e => maybe(e).isJust()))
.foreach(console.log) |
Also in response to your last comment: you could do it like that. But I wouldn't.. as you're creating a dependency that might break if someone updates it. It's also perhaps less clear. The preferred method would be to have default values for your |
This is so useful, thanks. I think I've finally "grokked" |
@alexanderjarvis I'm finding myself doing this a lot. Would you consider a PR that adds a new method, something like all() {
if (Array.isArray(this.value) && this.value.every(x => maybe(x).isJust())) {
return this
} else {
return nothing
}
} And you would use it like: maybe([1, 2, 3])
.all()
.map(transform)
.orJust([]) |
What would the
maybe
version of the following be?Would it be this?
This doesn't seem very functional. Maybe I'm missing something super obvious. Thanks!
The text was updated successfully, but these errors were encountered: