From 76d8f4a1d911e100d3b7af7a8e113bbc9cfc4d94 Mon Sep 17 00:00:00 2001 From: Thomas Reynolds Date: Sat, 2 May 2020 15:21:18 -0700 Subject: [PATCH] feat: add Result.fromMaybe --- src/monads/Result.ts | 4 ++++ src/monads/__tests__/Result.spec.ts | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/src/monads/Result.ts b/src/monads/Result.ts index e462a2a..4b77d6d 100644 --- a/src/monads/Result.ts +++ b/src/monads/Result.ts @@ -9,6 +9,7 @@ import { isLeft, isRight, } from "./Either" +import { Maybe, fold as maybeFold } from "./Maybe" export type Ok = Right export type Err = Left @@ -31,6 +32,9 @@ export const cata = (handlers: { export const fold = (errorFn: (a: A) => U, okFn: (b: B) => U) => fold_(errorFn, okFn) as (result: Result) => U +export const fromMaybe = (maybe: Maybe) => + maybeFold(() => Err(null), Ok)(maybe) as Result + // Chain export const chain = (fn: (a: B) => Result) => chain_(fn) as (result: Result) => Result diff --git a/src/monads/__tests__/Result.spec.ts b/src/monads/__tests__/Result.spec.ts index 9873b98..3b5d204 100644 --- a/src/monads/__tests__/Result.spec.ts +++ b/src/monads/__tests__/Result.spec.ts @@ -9,7 +9,9 @@ import { orElse, isOk, isError, + fromMaybe, } from "../Result" +import { Nothing, Just } from "../Maybe" describe("Result", () => { test("Ok", () => { @@ -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))