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

Commit

Permalink
feat: add Result.fromMaybe
Browse files Browse the repository at this point in the history
  • Loading branch information
tdreyno committed May 2, 2020
1 parent fb9a4cf commit 76d8f4a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/monads/Result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
isLeft,
isRight,
} from "./Either"
import { Maybe, fold as maybeFold } from "./Maybe"

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

export const fromMaybe = <B>(maybe: Maybe<B>) =>
maybeFold(() => Err(null), Ok)(maybe) as Result<null, B>

// Chain
export const chain = <A, B, U>(fn: (a: B) => Result<A, U>) =>
chain_(fn) as (result: Result<A, B>) => Result<A, U>
Expand Down
6 changes: 6 additions & 0 deletions src/monads/__tests__/Result.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import {
orElse,
isOk,
isError,
fromMaybe,
} from "../Result"
import { Nothing, Just } from "../Maybe"

describe("Result", () => {
test("Ok", () => {
Expand Down Expand Up @@ -64,6 +66,10 @@ describe("Result", () => {
test("chain(Err)", () =>
expect(chain(jest.fn())(Err("whoops"))).toEqual(Err("whoops")))

test("fromMaybe(Nothing)", () =>
expect(fromMaybe(Nothing())).toEqual(Err(null)))
test("fromMaybe(Just)", () => expect(fromMaybe(Just(5))).toEqual(Ok(5)))

test("orElse", () => expect(orElse(() => 10)(Err("whoops"))).toEqual(Ok(10)))

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

0 comments on commit 76d8f4a

Please sign in to comment.