Skip to content

Commit

Permalink
✨ Add the toResult method to OptionMethods
Browse files Browse the repository at this point in the history
Converting an `Option` into a `Result` is a commonly used operation.
  • Loading branch information
aaditmshah committed Jan 30, 2024
1 parent 4253f47 commit 391beaa
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
6 changes: 6 additions & 0 deletions 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<A> = Some<A> | None;

Expand Down Expand Up @@ -34,6 +36,10 @@ abstract class OptionMethods {
if (this.isSome) return this.value;
throw error instanceof Exception ? error : new UnsafeExtractError(error);
}

public toResult<E, A>(this: Option<A>, getError: () => E): Result<E, A> {
return this.isSome ? new Success(this.value) : new Failure(getError());
}
}

export class Some<out A> extends OptionMethods {
Expand Down
31 changes: 31 additions & 0 deletions tests/option.test.ts
Expand Up @@ -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 = <A>(value: A): A => value;

Expand Down Expand Up @@ -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()),
);
}),
);
});
});
});

0 comments on commit 391beaa

Please sign in to comment.