Skip to content

Commit

Permalink
feat(logical): add logical and operator for option
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jul 4, 2023
1 parent a8b61cf commit 9d77de2
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
25 changes: 24 additions & 1 deletion operators/logical.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license.
// This module is browser compatible.

import { isSome } from "./query.ts";
import { isNone, isSome } from "./query.ts";
import { type Option } from "../spec.ts";

/** Returns the {@link option} if it contains a value, otherwise returns {@link obtb}.
Expand All @@ -23,3 +23,26 @@ export function or<T>(option: Option<T>, obtb: Option<T>): Option<T> {

return obtb;
}

/** Returns `None` if the `option` is `None`, otherwise returns `optb`.
*
* @example
* ```ts
* import { and } from "https://deno.land/x/optio/operators/logical.ts";
* import { None, Some } from "https://deno.land/x/optio/spec.ts";
* import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
*
* declare const some: Some<unknown>;
* declare const someb: Some<unknown>;
*
* assertEquals(and(some, None), None);
* assertEquals(and(some, someb), someb);
* assertEquals(and(None, some), None);
* assertEquals(and(None, None), None);
* ```
*/
export function and<T>(option: Option<unknown>, optb: Option<T>): Option<T> {
if (isNone(option)) return option;

return optb;
}
14 changes: 13 additions & 1 deletion operators/logical_test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license.
// This module is browser compatible.

import { or } from "./logical.ts";
import { and, or } from "./logical.ts";
import { None, Some } from "../spec.ts";
import { assert, describe, it } from "../_dev_deps.ts";

Expand All @@ -18,3 +18,15 @@ describe("or", () => {
assert(or(None, None) === None);
});
});

describe("and", () => {
it("should return Some if both of arg is some otherwise None", () => {
const some = Some.of(0);
const someb = Some.of(1);

assert(and(some, None) === None);
assert(and(some, someb) === someb);
assert(and(None, some) === None);
assert(and(None, None) === None);
});
});

0 comments on commit 9d77de2

Please sign in to comment.