From ad5e392c42d02f7b33c882aa771949f891cd4dda Mon Sep 17 00:00:00 2001 From: Paolo Roth Date: Tue, 16 Jul 2019 14:19:26 +0200 Subject: [PATCH] feat: adds flattern --- README.md | 9 +++++++++ src/Option.ts | 18 ++++++++++++++++++ src/__tests__/Option.spec.ts | 4 ++++ 3 files changed, 31 insertions(+) diff --git a/README.md b/README.md index d375adc..ff7fec5 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Heavily inspired by rust [std::option](https://doc.rust-lang.org/std/option/inde - [andThen](#andThen) - [expect](#expect) - [filter](#filter) + - [flattern](#flattern) - [isNone](#isNone) - [isSome](#isSome) - [map](#map) @@ -123,6 +124,14 @@ Option(1).filter(a => a > 0).isSome() // true Option(1).filter(a => a > 10).isSome() // false ``` +#### flattern + +Converts from `Option>` to `Option` + +```ts +Option(Some(100)).flattern() // Some(100) +``` + #### isNone Returns if has not a value diff --git a/src/Option.ts b/src/Option.ts index 3a4314f..36a99de 100644 --- a/src/Option.ts +++ b/src/Option.ts @@ -89,6 +89,24 @@ class OptionLike { return predicateresult ? this : (None() as any); } + /** + * Converts from `Option>` to `Option` + * + * ```ts + * Option(Some(100)).flattern() // Some(100) + * ``` + * + * @returns {OptionLike} + * @memberof OptionLike + */ + public flattern(): OptionLike { + if (this.value instanceof OptionLike) { + return this.value; + } + + return this; + } + /** * Returns if has not a value * diff --git a/src/__tests__/Option.spec.ts b/src/__tests__/Option.spec.ts index 6d59a09..29f1997 100644 --- a/src/__tests__/Option.spec.ts +++ b/src/__tests__/Option.spec.ts @@ -118,4 +118,8 @@ describe(`Option`, () => { expect(Some(100).transpose()).toStrictEqual(Ok(Some(100))); expect(None().transpose()).toStrictEqual(Ok(None())); }); + + it("Converts from `Option>` to `Option`", () => { + expect(Option(Some(100)).flattern()).toStrictEqual(Some(100)); + }); });