Skip to content
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

Implement {Option,Result}.unwrapOrElse #155

Merged
merged 3 commits into from
Jul 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
21 changes: 21 additions & 0 deletions docs/reference/api/option.rst
Original file line number Diff line number Diff line change
Expand Up @@ -192,5 +192,26 @@ Throws if the value is ``None``.

Returns the contained ``Some`` value or a provided default.

``unwrapOrElse()``
------------------

.. code-block:: typescript

unwrapOrElse<T2>(f: () => T2): T | T2

Returns the contained ``Some`` value or computes a value with a provided function.

The function is called at most one time, only if needed.

Example:

.. code-block:: typescript

Some('OK').unwrapOrElse(
() => { console.log('Called'); return 'UGH'; }
) // => 'OK', nothing printed

None.unwrapOrElse(() => 'UGH') // => 'UGH'


.. _cause: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
22 changes: 22 additions & 0 deletions docs/reference/api/result.rst
Original file line number Diff line number Diff line change
Expand Up @@ -459,4 +459,26 @@ Example:
goodResult.unwrapOr(5); // 1
badResult.unwrapOr(5); // 5

``unwrapOrElse()``
------------------

.. code-block:: typescript

unwrapOrElse<T2>(f: (error: E) => T2): T | T2

Returns the contained ``Ok`` value or computes a value with a provided function.

The function is called at most one time, only if needed.

Example:

.. code-block:: typescript

Ok('OK').unwrapOrElse(
(error) => { console.log(`Called, got ${error}`); return 'UGH'; }
) // => 'OK', nothing printed

Err('A03B').unwrapOrElse((error) => `UGH, got ${error}`) // => 'UGH, got A03B'


.. _cause: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
24 changes: 24 additions & 0 deletions src/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,22 @@ interface BaseOption<T> extends Iterable<T extends Iterable<infer U> ? U : never
*/
unwrapOr<T2>(val: T2): T | T2;

/**
* Returns the contained `Some` value or computes a value with a provided function.
*
* The function is called at most one time, only if needed.
*
* @example
* ```
* Some('OK').unwrapOrElse(
* () => { console.log('Called'); return 'UGH'; }
* ) // => 'OK', nothing printed
*
* None.unwrapOrElse(() => 'UGH') // => 'UGH'
* ```
*/
unwrapOrElse<T2>(f: () => T2): T | T2;

/**
* Calls `mapper` if the Option is `Some`, otherwise returns `None`.
* This function can be used for control flow based on `Option` values.
Expand Down Expand Up @@ -134,6 +150,10 @@ class NoneImpl implements BaseOption<never> {
return val;
}

unwrapOrElse<T2>(f: () => T2): T2 {
return f();
}

expect(msg: string): never {
throw new Error(`${msg}`);
}
Expand Down Expand Up @@ -227,6 +247,10 @@ class SomeImpl<T> implements BaseOption<T> {
return this.value;
}

unwrapOrElse(_f: unknown): T {
return this.value;
}

expect(_msg: string): T {
return this.value;
}
Expand Down
25 changes: 24 additions & 1 deletion src/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { AsyncResult } from './asyncresult.js';
* pub fn contains<U>(&self, x: &U) -> bool
* pub fn contains_err<F>(&self, f: &F) -> bool
* pub fn and<U>(self, res: Result<U, E>) -> Result<U, E>
* pub fn unwrap_or_else<F>(self, op: F) -> T
* pub fn expect_err(self, msg: &str) -> E
* pub fn unwrap_or_default(self) -> T
*/
Expand Down Expand Up @@ -82,6 +81,22 @@ interface BaseResult<T, E> extends Iterable<T extends Iterable<infer U> ? U : ne
*/
unwrapOr<T2>(val: T2): T | T2;

/**
* Returns the contained `Ok` value or computes a value with a provided function.
*
* The function is called at most one time, only if needed.
*
* @example
* ```
* Ok('OK').unwrapOrElse(
* (error) => { console.log(`Called, got ${error}`); return 'UGH'; }
* ) // => 'OK', nothing printed
*
* Err('A03B').unwrapOrElse((error) => `UGH, got ${error}`) // => 'UGH, got A03B'
* ```
*/
unwrapOrElse<T2>(f: (error: E) => T2): T | T2;

/**
* Calls `mapper` if the result is `Ok`, otherwise returns the `Err` value of self.
* This function can be used for control flow based on `Result` values.
Expand Down Expand Up @@ -218,6 +233,10 @@ export class ErrImpl<E> implements BaseResult<never, E> {
return val;
}

unwrapOrElse<T2>(f: (error: E) => T2): T2 {
return f(this.error);
}

expect(msg: string): never {
// The cause casting required because of the current TS definition being overly restrictive
// (the definition says it has to be an Error while it can be anything).
Expand Down Expand Up @@ -340,6 +359,10 @@ export class OkImpl<T> implements BaseResult<T, never> {
return this.value;
}

unwrapOrElse(_f: unknown): T {
return this.value;
}

expect(_msg: string): T {
return this.value;
}
Expand Down
7 changes: 6 additions & 1 deletion test/option.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Err, None, Ok, Option, OptionSomeType, Result, Some } from '../src/index.js';
import { eq } from './util.js';
import { eq, notSupposedToBeCalled } from './util.js';

const someString = Some('foo');
const someNum = new Some(10);
Expand Down Expand Up @@ -67,6 +67,11 @@ test('unwrap', () => {
expect(None.unwrapOr('honk')).toBe('honk');
});

test('unwrapOrElse', () => {
expect(Some('1').unwrapOrElse(notSupposedToBeCalled)).toEqual('1');
expect(None.unwrapOrElse(() => '2')).toEqual('2');
});

test('map / andThen', () => {
expect(None.map(() => 1)).toBe(None);
expect(None.andThen(() => 1)).toBe(None);
Expand Down
7 changes: 6 additions & 1 deletion test/result.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
ResultOkTypes,
Some,
} from '../src/index.js';
import { eq } from './util.js';
import { eq, notSupposedToBeCalled } from './util.js';

test('Err<E> | Ok<T> should be Result<T, E>', () => {
const r1 = Err(0);
Expand Down Expand Up @@ -333,3 +333,8 @@ test('toAsyncResult()', async () => {
const err = Err('error');
expect(await err.toAsyncResult().promise).toEqual(err);
});

test('unwrapOrElse', () => {
expect(Ok({ data: 'user data' }).unwrapOrElse(notSupposedToBeCalled)).toEqual({ data: 'user data' });
expect(Err('bad error').unwrapOrElse((error) => ({ error }))).toEqual({ error: 'bad error' });
});
4 changes: 4 additions & 0 deletions test/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,7 @@ expect.extend({
};
},
});

export function notSupposedToBeCalled() {
throw new Error('This is not supposed to be called');
}
Loading