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

feat: add OptionExt.ofUndefinable() #139

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
11 changes: 10 additions & 1 deletion src/option/option.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { isNone, isSome, None, Option, OptionType, Some } from './option';
import { isNone, isSome, None, Option, OptionExt, OptionType, Some } from './option';

describe('Option', () => {
describe('OptionExt', () => {
test('OptionExt.ofUndefinable(undefined) should be None', () => {
expect(OptionExt.ofUndefinable(undefined).isNone()).toBe(true);
});
test('OptionExt.ofUndefinable("x") should be Some("x")', () => {
expect(OptionExt.ofUndefinable('x').isSome()).toBe(true);
});
});

describe('Some', () => {
const value = 'test';
const someOption: Option<string> = Some(value);
Expand Down
18 changes: 18 additions & 0 deletions src/option/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,24 @@ export interface Option<T extends NonUndefined> {
unwrap(): T | never;
}

export class OptionExt {
/**
* Construct an Option from a value which may be undefined.
*
* @param value May be either undefined to not undefined.
* @returns `Some(value)` if `value` is not undefined, otherwise `None`.
*
* #### Examples
* ```ts
* console.log(OptionExt.ofUndefinable(undefined).isNone()); // true
* console.log(OptionExt.ofUndefinable("x").isSome()); // true
* ```
*/
static ofUndefinable<T extends NonUndefined>(value: T | undefined): Option<T> {
return value === undefined ? None : Some(value);
}
}

/**
* Implementation of Option representing a value (Some).
*/
Expand Down