From 097d5d01aa6326c70bd5acaa1f85b7af9cce4945 Mon Sep 17 00:00:00 2001 From: Patrick Michalina Date: Sun, 19 May 2019 23:40:04 -0500 Subject: [PATCH] feat(maybe): introduce maybeToPromise --- src/monads/maybe.ts | 6 ++++++ test/monads/maybe.spec.ts | 31 ++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/monads/maybe.ts b/src/monads/maybe.ts index 643bda9..9042dbf 100644 --- a/src/monads/maybe.ts +++ b/src/monads/maybe.ts @@ -45,3 +45,9 @@ export const maybe = (value?: T): IMaybe> => { filter: filter(value) } } + +export const maybeToPromise = + (catchResponse: any = 'not found') => + (maybe: IMaybe) => maybe.isSome() + ? Promise.resolve(maybe.valueOrUndefined() as T) + : Promise.reject(catchResponse) diff --git a/test/monads/maybe.spec.ts b/test/monads/maybe.spec.ts index 5b238ae..b51d548 100644 --- a/test/monads/maybe.spec.ts +++ b/test/monads/maybe.spec.ts @@ -1,4 +1,4 @@ -import { maybe } from '../../src' +import { maybe, IMaybe, maybeToPromise } from '../../src' describe('Maybe', () => { describe('when returning a value with possible throw', () => { @@ -466,4 +466,33 @@ describe('Maybe', () => { expect(maybe(sut3).isNone()).toEqual(false) }) }) + + describe('maybeToPromise', () => { + it('should flatmap', () => { + const sut = new Promise>((a, b) => a(maybe('test'))) + + sut + .then(maybeToPromise()) + .then(result => expect(result).toEqual('test')) + .catch(_shouldNotBeHere => expect(false).toBe(true)) + }) + + it('should catch w/ default message', () => { + const sut = new Promise>((a, b) => a(maybe())) + + sut + .then(maybeToPromise()) + .then(_shouldNotBeHere => expect(false).toBe(true)) + .catch(error => expect(error).toEqual('not found')) + }) + + it('should catch w/ custom message', () => { + const sut = new Promise>((a, b) => a(maybe())) + + sut + .then(maybeToPromise('err')) + .then(_shouldNotBeHere => expect(false).toBe(true)) + .catch(error => expect(error).toEqual('err')) + }) + }) })