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()),
+ );
+ }),
+ );
+ });
+ });
});