From 391beaa1c5957bed44e1c4a1ce53bb82106679ad Mon Sep 17 00:00:00 2001 From: Aadit M Shah Date: Tue, 30 Jan 2024 12:01:35 +0530 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20the=20`toResult`=20method=20t?= =?UTF-8?q?o=20`OptionMethods`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Converting an `Option` into a `Result` is a commonly used operation. --- src/option.ts | 6 ++++++ tests/option.test.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/option.ts b/src/option.ts index ecf9258..ba9f0ac 100644 --- a/src/option.ts +++ b/src/option.ts @@ -1,5 +1,7 @@ import { UnsafeExtractError } from "./errors.js"; import { Exception } from "./exceptions.js"; +import type { Result } from "./result.js"; +import { Failure, Success } from "./result.js"; export type Option = Some | None; @@ -34,6 +36,10 @@ abstract class OptionMethods { if (this.isSome) return this.value; throw error instanceof Exception ? error : new UnsafeExtractError(error); } + + public toResult(this: Option, getError: () => E): Result { + return this.isSome ? new Success(this.value) : new Failure(getError()); + } } export class Some extends OptionMethods { diff --git a/tests/option.test.ts b/tests/option.test.ts index 7019822..9852c44 100644 --- a/tests/option.test.ts +++ b/tests/option.test.ts @@ -5,6 +5,7 @@ import { UnsafeExtractError } from "../src/errors.js"; import { Exception } from "../src/exceptions.js"; import type { Option } from "../src/option.js"; import { None, Some } from "../src/option.js"; +import { Failure, Success } from "../src/result.js"; const id = (value: A): A => value; @@ -195,4 +196,34 @@ describe("Option", () => { ); }); }); + + describe("toResult", () => { + it("should convert Some to Success", () => { + expect.assertions(100); + + fc.assert( + fc.property( + fc.anything(), + fc.func(fc.anything()), + (value, getError) => { + expect(new Some(value).toResult(getError)).toStrictEqual( + new Success(value), + ); + }, + ), + ); + }); + + it("should convert None to Failure", () => { + expect.assertions(100); + + fc.assert( + fc.property(genNone, fc.func(fc.anything()), (none, getError) => { + expect(none.toResult(getError)).toStrictEqual( + new Failure(getError()), + ); + }), + ); + }); + }); });