Option unwrapOr helper (#652)
* Option unwrapOrNull helper * unwrapOrNull -> unwrapOr
This commit is contained in:
@@ -76,5 +76,13 @@ describe('Option', () => {
|
||||
it('compares against raw value', () => {
|
||||
expect(testeq.eq('1234')).toBe(true);
|
||||
});
|
||||
|
||||
it('unwraps to default if empty', () => {
|
||||
expect(new Option(Text).unwrapOr('6789')).toBe('6789');
|
||||
});
|
||||
|
||||
it('unwraps to value if non-empty', () => {
|
||||
expect((new Option(Text, '1234').unwrapOr(null) as Text).toString()).toBe('1234');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -127,7 +127,7 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the value that the Option represents (if available)
|
||||
* @description Returns the value that the Option represents (if available), throws if null
|
||||
*/
|
||||
unwrap (): T {
|
||||
if (this.isNone) {
|
||||
@@ -136,4 +136,14 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
|
||||
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the value that the Option represents (if available) or defaultValue if none
|
||||
* @param defaultValue The value to return if the option isNone
|
||||
*/
|
||||
unwrapOr <O> (defaultValue: O): T | O {
|
||||
return this.isSome
|
||||
? this.unwrap()
|
||||
: defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user