-
Notifications
You must be signed in to change notification settings - Fork 84
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
feat: Add unwrapOrElse #593
Conversation
🦋 Changeset detectedLatest commit: 05f1515 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
src/result-async.ts
Outdated
unwrapOrElse<A>(err: (e: E) => A): Promise<T | A> { | ||
return this._promise.then((res) => { | ||
if (res.isErr()) { | ||
return err(res.error) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
reading this was a little confusing because of the err
function in the library :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
unwrapOrElse<A>(err: (e: E) => A): T | A { | ||
return err(this.error) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I still find the naming err
to be a bit confusing, but now I see that it's used everywhere for this type of argument 🤷🏼 e.g. in match directly below. no reason to break that pattern...
it('unwrapOrElse and return the Ok value', () => { | ||
const okVal = ok(12) | ||
expect(okVal.unwrapOrElse(() => 1)).toEqual(12) | ||
}) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it's part of unwrapOrElse's contract to not call the callback for an Ok value.
It could make sense to test that (using jest.fn
and expect(...).not.toHaveBeenCalled()
)
See comments in #587 |
Similar to unwrap, but returns default value by function: #587
Useful for lazily evaluating defaults or performing processing.
unwrapOrElse exists in Rust:
https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap_or_else