From 011ddded67bcc33726c1a55de1840cbf9c830475 Mon Sep 17 00:00:00 2001 From: MikuroXina <10331164+MikuroXina@users.noreply.github.com> Date: Sun, 20 Oct 2024 13:38:10 +0900 Subject: [PATCH] feat: Add isSomeAnd and isNoneOr --- src/option.test.ts | 18 ++++++++++++++++++ src/option.ts | 24 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/option.test.ts b/src/option.test.ts index 6dd7629c..cf06934a 100644 --- a/src/option.test.ts +++ b/src/option.test.ts @@ -147,6 +147,24 @@ Deno.test("xor", () => { assertEquals(Option.xor(Option.some(100))(Option.some(2)), Option.none()); }); +Deno.test("isSomeAnd", () => { + assertEquals(Option.isSomeAnd((x: number) => x >= 2)(Option.some(2)), true); + assertEquals( + Option.isSomeAnd((x: number) => x >= 2)(Option.some(1.9)), + false, + ); + assertEquals(Option.isSomeAnd((x: number) => x >= 2)(Option.none()), false); +}); + +Deno.test("isNoneOr", () => { + assertEquals(Option.isNoneOr((x: number) => x >= 2)(Option.some(2)), true); + assertEquals( + Option.isNoneOr((x: number) => x >= 2)(Option.some(1.9)), + false, + ); + assertEquals(Option.isNoneOr((x: number) => x >= 2)(Option.none()), true); +}); + Deno.test("filter", () => { const isEven = Option.filter((x: number) => x % 2 === 0); assertEquals(isEven(Option.none()), Option.none()); diff --git a/src/option.ts b/src/option.ts index 32bcf8b8..54c60b7d 100644 --- a/src/option.ts +++ b/src/option.ts @@ -405,6 +405,30 @@ export const xor = (optB: Option) => (optA: Option): Option => { return none(); }; +/** + * Checks an {@link Option.Option | `Option`} is a `Some` and satisfies the predicate `pred`. + * + * It is equivalent to `!isNoneOr((item) => !pred(item))`. + * + * @param pred - The predicate to check. + * @returns Whether the condition is satisfied. + */ +export const isSomeAnd = + (pred: (item: T) => boolean) => (opt: Option): boolean => + isSome(opt) && pred(opt[1]); + +/** + * Checks an {@link Option.Option | `Option`} is a `None` or satisfies the predicated `pred`. + * + * It is equivalent to `!isSomeAnd((item) => !pred(item))`. + * + * @param pred - The predicate to check. + * @returns Whether the condition is satisfied. + */ +export const isNoneOr = + (pred: (item: T) => boolean) => (opt: Option): boolean => + isNone(opt) || pred(opt[1]); + /** * Returns `Some` only if `opt` is a `Some` and its value satisfies `predicate`, otherwise returns `None`. *