feat(result): Add unwrapOrNull method (#24025)

This commit is contained in:
Sergei Zharinov 2023-08-22 22:40:16 +03:00 committed by GitHub
parent b5e4b6c7ec
commit ecbee400cb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 0 deletions

View file

@ -159,6 +159,27 @@ describe('util/result', () => {
const res = Result.err('oops'); const res = Result.err('oops');
expect(() => res.unwrapOrThrow()).toThrow('oops'); expect(() => res.unwrapOrThrow()).toThrow('oops');
}); });
it('unwrapOrNull returns value for ok-result', () => {
const res = Result.ok(42);
expect(res.unwrapOrNull()).toBe(42);
});
it('unwrapOrNull returns null for error result', () => {
const res = Result.err('oops');
expect(res.unwrapOrNull()).toBeNull();
});
it('unwrapOrNull throws uncaught transform error', () => {
const res = Result.ok(42);
expect(() =>
res
.transform(() => {
throw 'oops';
})
.unwrapOrNull()
).toThrow('oops');
});
}); });
describe('Transforming', () => { describe('Transforming', () => {
@ -373,6 +394,16 @@ describe('util/result', () => {
const res = Result.wrap(Promise.reject('oops')); const res = Result.wrap(Promise.reject('oops'));
await expect(res.unwrapOrThrow()).rejects.toBe('oops'); await expect(res.unwrapOrThrow()).rejects.toBe('oops');
}); });
it('unwrapOrNull returns value for ok-result', async () => {
const res = AsyncResult.ok(42);
await expect(res.unwrapOrNull()).resolves.toBe(42);
});
it('unwrapOrNull returns null for error result', async () => {
const res = AsyncResult.err('oops');
await expect(res.unwrapOrNull()).resolves.toBeNull();
});
}); });
describe('Transforming', () => { describe('Transforming', () => {

View file

@ -362,6 +362,22 @@ export class Result<T extends Val, E extends Val = Error> {
throw this.res.err; throw this.res.err;
} }
/**
* Returns the ok-value or `null`.
* When error was uncaught during transformation, it's being re-thrown here.
*/
unwrapOrNull(): T | null {
if (this.res.ok) {
return this.res.val;
}
if (this.res._uncaught) {
throw this.res.err;
}
return null;
}
/** /**
* Transforms the ok-value, sync or async way. * Transforms the ok-value, sync or async way.
* *
@ -672,6 +688,13 @@ export class AsyncResult<T extends Val, E extends Val>
return result.unwrapOrThrow(); return result.unwrapOrThrow();
} }
/**
* Returns the ok-value or `null`.
*/
unwrapOrNull(): Promise<T | null> {
return this.asyncResult.then<T | null>((res) => res.unwrapOrNull());
}
/** /**
* Transforms the ok-value, sync or async way. * Transforms the ok-value, sync or async way.
* *