Skip to content

Commit 548d337

Browse files
feat: introduce Maybe.mapTo<R>() (#178)
1 parent a10e4be commit 548d337

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

src/maybe/maybe.interface.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ export interface IMaybe<T> extends IMonad<T> {
8282
*/
8383
map<R>(f: (t: T) => NonNullable<R>): IMaybe<R>
8484

85+
/**
86+
* Map to a new value while ignoring previous output value but respecting maybeness
87+
*/
88+
mapTo<R>(v: NonNullable<R>): IMaybe<R>
89+
8590
/**
8691
* Returns true if value is not empty
8792
*/

src/maybe/maybe.spec.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,13 @@ describe('Maybe', () => {
548548
})
549549
})
550550

551+
describe('mapTo', () => {
552+
it('should return new maybe with some', () => {
553+
expect(Maybe.some(1).mapTo('deltaforce').valueOrThrowErr()).toEqual('deltaforce')
554+
expect(Maybe.none().mapTo('deltaforce').valueOrNull()).toEqual(null)
555+
})
556+
})
557+
551558
describe('toResult', () => {
552559
it('should return result object with success', () => {
553560
const hasSome = maybe('hi')

src/maybe/maybe.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ export class Maybe<T> implements IMaybe<T> {
8686
: new Maybe<R>()
8787
}
8888

89+
public mapTo<R>(t: NonNullable<R>): IMaybe<R> {
90+
return this.isSome()
91+
? new Maybe<R>(t)
92+
: new Maybe<R>()
93+
}
94+
8995
public flatMap<R>(fn: (d: NonNullable<T>) => IMaybe<R>): IMaybe<R> {
9096
return this.isNone() ? new Maybe<R>() : fn(this.value as NonNullable<T>)
9197
}

0 commit comments

Comments
 (0)