diff --git a/src/option/option.spec.ts b/src/option/option.spec.ts index 13b1d9b..9038fc2 100644 --- a/src/option/option.spec.ts +++ b/src/option/option.spec.ts @@ -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 = Some(value); diff --git a/src/option/option.ts b/src/option/option.ts index 899dbd2..519fdc2 100644 --- a/src/option/option.ts +++ b/src/option/option.ts @@ -186,6 +186,24 @@ export interface Option { 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(value: T | undefined): Option { + return value === undefined ? None : Some(value); + } +} + /** * Implementation of Option representing a value (Some). */