Option unwrapOr helper (#652)

* Option unwrapOrNull helper

* unwrapOrNull -> unwrapOr
This commit is contained in:
Jaco Greeff
2019-01-30 15:40:59 +01:00
committed by GitHub
parent 9e76cdd147
commit 82531493da
2 changed files with 19 additions and 1 deletions
+8
View File
@@ -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');
});
});
});
+11 -1
View File
@@ -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;
}
}