From 37bba43712cd7ccb2d378dec350681fba17d8f7e Mon Sep 17 00:00:00 2001 From: CRIMX Date: Mon, 18 Dec 2023 19:21:08 +0800 Subject: [PATCH] feat(option): add static isSame --- src/option.ts | 13 +++++++++++++ test/option.test.ts | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/option.ts b/src/option.ts index 19e1c2a..26055cc 100644 --- a/src/option.ts +++ b/src/option.ts @@ -74,6 +74,19 @@ export class Option { public static isOption(maybeOption: unknown): maybeOption is Option { return !!maybeOption && (maybeOption as Option)[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; diff --git a/test/option.test.ts b/test/option.test.ts index 2b6c1d8..744d1f4 100644 --- a/test/option.test.ts +++ b/test/option.test.ts @@ -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"); @@ -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");