Skip to content

Commit

Permalink
fix: correct usage of maybe.apply (#198)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: apply signature changed
  • Loading branch information
patrickmichalina authored Jan 9, 2024
1 parent 3e0ea01 commit b98f07f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 9 deletions.
4 changes: 3 additions & 1 deletion src/maybe/maybe.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,9 @@ export interface IMaybe<T> extends IMonad<T> {
* Apply a function wrapped in Maybe
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
apply(maybe: IMaybe<ReturnType<T extends (...args: any) => any ? T : any>>): IMaybe<T>
// apply(maybe: IMaybe<ReturnType<T extends (...args: any) => any ? T : any>>): IMaybe<T>

apply<R>(fab: IMaybe<(t: T) => R>): IMaybe<R>

toResult<E>(error: E): IResult<T, E>
}
22 changes: 17 additions & 5 deletions src/maybe/maybe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,18 +573,30 @@ describe('Maybe', () => {
})

describe('apply', () => {
it('should return none in nullish cases', () => {
const thisNone = maybe<number>()
const fnNone = maybe<(n: number) => number>()
const thisSome = maybe(5)
const fnSome = maybe((a: number) => a * 2)

expect(thisNone.apply(fnNone).isNone()).toBe(true)
expect(thisNone.apply(fnSome).isNone()).toBe(true)
expect(thisSome.apply(fnNone).isNone()).toBe(true)
})

it('should apply the IMaybe<function>', () => {
const a = maybe((a: number) => a * 2)
const b = maybe(5)
const a = maybe(5)
const b = maybe((a: number) => a * 2)

expect(a.apply(b).valueOrThrow()).toBe(10)
})

it('should apply the non-function maybe', () => {
it('should apply none objects gracefully', () => {
const a = maybe(2)
const b = maybe(5)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const b: Maybe<(a: number) => number> = maybe(() => undefined as any)

expect(a.apply(b).valueOrThrow()).toBe(5)
expect(a.apply(b).isNone()).toBe(true)
})
})

Expand Down
5 changes: 2 additions & 3 deletions src/maybe/maybe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,8 @@ export class Maybe<T> implements IMaybe<T> {
: new Maybe<T>()
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
public apply(maybe: IMaybe<ReturnType<T extends (...args: any) => any ? T : any>>): IMaybe<NonNullable<T>> {
return maybe.flatMap(a => this.map(b => typeof b === 'function' ? b(a) : a))
public apply<R>(maybeFn: IMaybe<(t: NonNullable<T>) => R>): IMaybe<NonNullable<R>> {
return this.flatMap(v => maybeFn.flatMapAuto(f => f(v)))
}

public toResult<E>(error: E): IResult<T, E> {
Expand Down

0 comments on commit b98f07f

Please sign in to comment.