From dacbe59c89758d8ffc74e097c9fe7b7f7cc6c687 Mon Sep 17 00:00:00 2001 From: gibbz00 Date: Thu, 13 Jun 2024 21:53:18 +0200 Subject: [PATCH] feat: add `OptionExt.ofUndefinable()` --- src/option/option.spec.ts | 11 ++++++++++- src/option/option.ts | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) 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). */