-
Notifications
You must be signed in to change notification settings - Fork 88
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
Proposal: a solution for emulating Rust's ? operator #444
Comments
I am not sure if I am following your steps: In your solution, as a programmer, do you mean we always need two functions ( Not just it, the programmer also needs to be aware of the usage of I think this is too overhead for daily programming - It makes code messy. |
I actually did have a thought on how to bring Step 1- New API
|
The above is still not perfect - it requires the usage of the |
@Bistard Thank you for your comments.
Yes.
I admit that this is not an elegant solution. However, in my opinion, this makes early-return pattern less messy. The thing is about the control flow, so if we pursue a perfect solution, eventually we will need to introduce a new syntax to javascript. This might be interesting, but is far beyond the scope of this repository. Comment on #444 (comment) : |
In short
The following code emulates the ? operator:
Of course you can use
yield*
s andreturn
s as many as you want in ablock
.Description
An expression
yield* gen
in a generator function, heregen
is a generator, yields what are yielded ingen
, and is evaluated to what is returned ingen
, without yielding the returned value. (Please see MDN)As
returnError
is defined to return a generator that yields the argument if the argument is error and otherwise returns its unwrapped (ok's) value,yield* returnError(r)
yieldsr
ifr
is error, and otherwise is evaluated tor.value
without yielding anything.Finally, as
block
is defined to callnext()
on the argument exactly once and return that value,block(function*(){STATEMENTS})
is evaluated to the first occurrence inSTATEMENTS
of eitheryield* returnError(some_error)
orreturn some_result
.More integrated version (including async support)
It makes no sense to import
returnError
orblock
independently, so I combined them into single objectblock
.async block is also implemented by overload. It can be used as its type implies.
Question
Should I make a PR? I'm willing to make a PR if this is useful for this project.
If so, do anyone have any opinion how to integrate this to the existing APIs? (naming, module structure, or anything else)
Of course, any comments would be appreciated.
Related issues
#183
The text was updated successfully, but these errors were encountered: