Skip to content

Commit

Permalink
add andThen and orNull methods
Browse files Browse the repository at this point in the history
  • Loading branch information
vojtatranta committed Dec 15, 2024
1 parent 82446f8 commit 6c00a49
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/Maybe.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint-disable array-callback-return */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Maybe } from "./Maybe";

class A {}
Expand Down Expand Up @@ -373,4 +375,51 @@ describe("Maybe", () => {
});
});
});

describe("orNull", () => {
it("should return the value when it exists", () => {
const value = "test" as const;
const result = Maybe.of(value).orNull();
expect(result).toEqual("test");
});

it("should return null when value is undefined", () => {
const result = Maybe.of(undefined).orNull();
expect(result).toEqual(null);
});

it("should return null when value is null", () => {
const result = Maybe.of(null).orNull();
expect(result).toEqual(null);
});
});

describe("andThen", () => {
it("should transform value like map() when value exists", () => {
const value = "test" as const;
const result = Maybe.of(value)
.andThen((str) => str.length)
.getValue();
expect(result).toEqual(4);
});

it("should return Maybe with null when value is null", () => {
const a: string | null = null;
const result = Maybe.of(a)
.andThen((str: never) => {
return str;
})
.getValue();
expect(result).toEqual(null);
});

it("should chain multiple transformations", () => {
const value = "test" as const;
const result = Maybe.of(value)
.andThen((str) => str.length)
.andThen((len) => len * 2)
.getValue();
expect(result).toEqual(8);
});
});
});
8 changes: 8 additions & 0 deletions src/Maybe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ export class Maybe<T> {
return new Maybe<NonNullable<R>>(null);
}

andThen<R>(mapper: (value: NonNullable<T>) => R): Maybe<NonNullable<R>> {
return this.map(mapper);
}

// NOTE: flatMap() "eats" the incomming maybe and will use the value of the current maybe as default
// of the maybe returned by the Mapper()
// you can safely use Maybies in the flatMap() function return value as if it was a direct value
Expand All @@ -109,6 +113,10 @@ export class Maybe<T> {
return new Maybe<U>(null) as LocalReturn;
}

orNull(): T | null {
return this.value ?? null;
}

getValue(): T | null | undefined;
getValue<D>(defaultValue: D): NonNullable<T> | D;
getValue<D>(defaultValue?: D): T | D | null | undefined {
Expand Down

0 comments on commit 6c00a49

Please sign in to comment.