Skip to content

Commit a10e4be

Browse files
feat: add .toResult<E>(error: E) to Maybe class (#177)
1 parent 0e7785c commit a10e4be

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/maybe/maybe.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,4 +547,20 @@ describe('Maybe', () => {
547547
expect(Maybe.some(1).valueOrThrowErr()).toEqual(1)
548548
})
549549
})
550+
551+
describe('toResult', () => {
552+
it('should return result object with success', () => {
553+
const hasSome = maybe('hi')
554+
const sut = hasSome.toResult(new Error('oops'))
555+
556+
expect(sut.unwrap()).toEqual('hi')
557+
})
558+
559+
it('should return result object with fail', () => {
560+
const hasSome = maybe()
561+
const sut = hasSome.toResult(new Error('oops'))
562+
563+
expect(sut.unwrapFail()).toEqual(new Error('oops'))
564+
})
565+
})
550566
})

src/maybe/maybe.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { IResult } from '../result/result.interface'
2+
import { FailResult, OkResult } from '../result/result'
13
import { IMaybePattern, IMaybe } from './maybe.interface'
24

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

112+
public toResult<E>(error: E): IResult<T, E> {
113+
return this
114+
.map<IResult<T, E>>(b => new OkResult<T, E>(b))
115+
.valueOr(new FailResult<T, E>(error))
116+
}
117+
110118
}

0 commit comments

Comments
 (0)