Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add isSomeAnd and isNoneOr #265

Merged
merged 1 commit into from
Oct 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/option.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
24 changes: 24 additions & 0 deletions src/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,30 @@ export const xor = <T>(optB: Option<T>) => (optA: Option<T>): Option<T> => {
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 =
<T>(pred: (item: T) => boolean) => (opt: Option<T>): 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 =
<T>(pred: (item: T) => boolean) => (opt: Option<T>): boolean =>
isNone(opt) || pred(opt[1]);

/**
* Returns `Some` only if `opt` is a `Some` and its value satisfies `predicate`, otherwise returns `None`.
*
Expand Down