Skip to content
This repository was archived by the owner on Apr 2, 2023. It is now read-only.

Commit 76d8f4a

Browse files
committed
feat: add Result.fromMaybe
1 parent fb9a4cf commit 76d8f4a

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

src/monads/Result.ts

+4
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
isLeft,
1010
isRight,
1111
} from "./Either"
12+
import { Maybe, fold as maybeFold } from "./Maybe"
1213

1314
export type Ok<B> = Right<B>
1415
export type Err<A> = Left<A>
@@ -31,6 +32,9 @@ export const cata = <A, B, U>(handlers: {
3132
export const fold = <A, B, U>(errorFn: (a: A) => U, okFn: (b: B) => U) =>
3233
fold_(errorFn, okFn) as (result: Result<A, B>) => U
3334

35+
export const fromMaybe = <B>(maybe: Maybe<B>) =>
36+
maybeFold(() => Err(null), Ok)(maybe) as Result<null, B>
37+
3438
// Chain
3539
export const chain = <A, B, U>(fn: (a: B) => Result<A, U>) =>
3640
chain_(fn) as (result: Result<A, B>) => Result<A, U>

src/monads/__tests__/Result.spec.ts

+6
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ import {
99
orElse,
1010
isOk,
1111
isError,
12+
fromMaybe,
1213
} from "../Result"
14+
import { Nothing, Just } from "../Maybe"
1315

1416
describe("Result", () => {
1517
test("Ok", () => {
@@ -64,6 +66,10 @@ describe("Result", () => {
6466
test("chain(Err)", () =>
6567
expect(chain(jest.fn())(Err("whoops"))).toEqual(Err("whoops")))
6668

69+
test("fromMaybe(Nothing)", () =>
70+
expect(fromMaybe(Nothing())).toEqual(Err(null)))
71+
test("fromMaybe(Just)", () => expect(fromMaybe(Just(5))).toEqual(Ok(5)))
72+
6773
test("orElse", () => expect(orElse(() => 10)(Err("whoops"))).toEqual(Ok(10)))
6874

6975
test("isOk(Ok)", () => expect(isOk(Ok(5))).toBe(true))

0 commit comments

Comments
 (0)