Skip to content
Merged
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
6 changes: 6 additions & 0 deletions src/monads/maybe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,9 @@ export const maybe = <T>(value?: T): IMaybe<NonNullable<T>> => {
filter: filter(value)
}
}

export const maybeToPromise =
(catchResponse: any = 'not found') =>
<T>(maybe: IMaybe<T>) => maybe.isSome()
? Promise.resolve(maybe.valueOrUndefined() as T)
: Promise.reject(catchResponse)
31 changes: 30 additions & 1 deletion test/monads/maybe.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { maybe } from '../../src'
import { maybe, IMaybe, maybeToPromise } from '../../src'

describe('Maybe', () => {
describe('when returning a value with possible throw', () => {
Expand Down Expand Up @@ -466,4 +466,33 @@ describe('Maybe', () => {
expect(maybe(sut3).isNone()).toEqual(false)
})
})

describe('maybeToPromise', () => {
it('should flatmap', () => {
const sut = new Promise<IMaybe<string>>((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<IMaybe<string>>((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<IMaybe<string>>((a, b) => a(maybe()))

sut
.then(maybeToPromise('err'))
.then(_shouldNotBeHere => expect(false).toBe(true))
.catch(error => expect(error).toEqual('err'))
})
})
})