Skip to content

Commit

Permalink
Fix lifting ops
Browse files Browse the repository at this point in the history
  • Loading branch information
hermann-p committed Nov 16, 2022
1 parent bd801de commit 5645e52
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Monad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@ function bindM(f: (_: any) => any) {
}

const of = (m: any) => (v: any) =>
m.isJust() || m.isNothing() ? maybe(v) : m.isLeft() || m.isRight() ? either(v) : chain(v);
(m.isJust && m.isJust(m)) || (m.isNothing && m.isNothing())
? maybe(v)
: (m.isLeft && m.isLeft()) || (m.isRight && m.isRight())
? either(v)
: chain(v);

function lift<A>(_: Maybe<Monad<A>>): Maybe<A>;
function lift<A>(_: Either<Monad<A>>): Either<A>;
function lift<A>(_: Chain<Monad<A>>): Chain<A>;
function lift(m: any) {
return of(m.getValueOr(undefined)) as any;
return of(m)(m.getValueOr(undefined)) as any;
}

export { bind, bindM, lift };
31 changes: 31 additions & 0 deletions src/__tests__/monads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ describe("generic monad functions", () => {
expect(j.isNothing()).toBe(true);
});
it("should map right", () => {
const j = M.bind((x: number) => x + 1)(right<number, any>(1));
expect(j.isRight()).toBe(true);
expect(j.getValue()).toBe(2);
});
it("should map left", () => {
const j = M.bind((x: number) => x + 1)(left<any, any>(1));
expect(j.isLeft()).toBe(true);
});
Expand All @@ -128,4 +133,30 @@ describe("generic monad functions", () => {
expect(j.getValue()).toBe(2);
});
});

describe("bindM()", () => {
it("should map just", () => {
const j = M.bindM((x: number) => just(x + 1))(just(1));
console.log({ j });
expect(j.isJust()).toBe(true);
expect(j.getValue()).toBe(2);
});
it("should map nothing", () => {
const j = M.bindM((x: number) => just(x + 1))(nothing<number>());
expect(j.isNothing()).toBe(true);
});
it("should map right", () => {
const j = M.bindM((x: number) => right(x + 1))(right<number, any>(1));
expect(j.isRight()).toBe(true);
expect(j.getValue()).toBe(2);
});
it("should map left", () => {
const j = M.bindM((x: number) => left(x + 1))(right<any, any>(1));
expect(j.isLeft()).toBe(true);
});
it("should map chain", () => {
const j = M.bindM((x: number) => chain(x + 1))(chain(1));
expect(j.getValue()).toBe(2);
});
});
});

0 comments on commit 5645e52

Please sign in to comment.