Skip to content

Commit

Permalink
feat(option): add static isSame
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed Dec 18, 2023
1 parent 56e0607 commit 37bba43
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,19 @@ export class Option<T = any> {
public static isOption<T>(maybeOption: unknown): maybeOption is Option<T> {
return !!maybeOption && (maybeOption as Option<T>)[OPTION] === 1;
}

/**
* @returns `true` if the both are `Option` and the value are the same via `Object.is`.
*
* @param a - An `Option` or any value
* @param b - An `Option` or any value
*/
public static isSame(a: unknown, b: unknown): boolean {
return Option.isOption(a) && Option.isOption(b)
? Object.is(a._value, b._value)
: false;
}

private readonly [OPTION] = 1;

private readonly _value: T;
Expand Down
38 changes: 38 additions & 0 deletions test/option.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,37 @@ describe("Option", () => {
});
});

describe("isSame", () => {
it("returns true if both are the same Some value", () => {
const result = Option.isSame(Some("a"), Some("a"));
expect(result).toBe(true);
});

it("returns true if both are the same None", () => {
const result = Option.isSame(None, None);
expect(result).toBe(true);
});

it("returns false when the input is a different Some value", () => {
const result = Option.isSame(Some("a"), Some("b"));
expect(result).toBe(false);
});

it("returns false when the input is None", () => {
const some = Some("hello");
const none = None;
const result = Option.isSame(some, none);
expect(result).toBe(false);
});

it("returns false when the input is a different type", () => {
const some = Some("hello");
const obj = { value: "hello" };
const result = Option.isSame(some, obj);
expect(result).toBe(false);
});
});

describe("isSome", () => {
it("returns true for a Some", () => {
const some = Some("hello");
Expand Down Expand Up @@ -212,6 +243,13 @@ describe("Option", () => {
expect(result).toBe(true);
});

it("returns true when the input is the same None", () => {
const none1 = None;
const none2 = None;
const result = none1.isSame(none2);
expect(result).toBe(true);
});

it("returns false when the input is a different Some value", () => {
const some1 = Some("hello");
const some2 = Some("world");
Expand Down

0 comments on commit 37bba43

Please sign in to comment.