Skip to content

Commit

Permalink
feat: add .toResult<E>(error: E) to Maybe class (#177)
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickmichalina authored Aug 24, 2021
1 parent 0e7785c commit a10e4be
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/maybe/maybe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -547,4 +547,20 @@ describe('Maybe', () => {
expect(Maybe.some(1).valueOrThrowErr()).toEqual(1)
})
})

describe('toResult', () => {
it('should return result object with success', () => {
const hasSome = maybe('hi')
const sut = hasSome.toResult(new Error('oops'))

expect(sut.unwrap()).toEqual('hi')
})

it('should return result object with fail', () => {
const hasSome = maybe()
const sut = hasSome.toResult(new Error('oops'))

expect(sut.unwrapFail()).toEqual(new Error('oops'))
})
})
})
8 changes: 8 additions & 0 deletions src/maybe/maybe.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { IResult } from '../result/result.interface'
import { FailResult, OkResult } from '../result/result'
import { IMaybePattern, IMaybe } from './maybe.interface'

export class Maybe<T> implements IMaybe<T> {
Expand Down Expand Up @@ -107,4 +109,10 @@ export class Maybe<T> implements IMaybe<T> {
return maybe.flatMap(a => this.map(b => typeof b === 'function' ? b(a) : a))
}

public toResult<E>(error: E): IResult<T, E> {
return this
.map<IResult<T, E>>(b => new OkResult<T, E>(b))
.valueOr(new FailResult<T, E>(error))
}

}

0 comments on commit a10e4be

Please sign in to comment.