Skip to content

Commit

Permalink
feat(extract): add unwrapOr operator
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jul 4, 2023
1 parent 2959665 commit 65b1a2e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
18 changes: 18 additions & 0 deletions operators/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,24 @@ export function unwrap<T>(option: Option<T>): T {
throw new Error("option is None");
}

/** Returns the contained `Some` value, otherwise {@link defaultValue}.
*
* @example
* ```ts
* import { None, Some } from "https://deno.land/x/optio/spec.ts";
* import { unwrapOr } from "https://deno.land/x/optio/mod.ts";
* import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
*
* assertEquals(unwrapOr(Some.of(0), 1), 0);
* assertEquals(unwrapOr(None, 1), 1);
* ```
*/
export function unwrapOr<T>(option: Option<T>, defaultValue: T): T {
if (isSome(option)) return option.get;

return defaultValue;
}

/** Returns the contained `Some` value.
*
* @example
Expand Down
12 changes: 11 additions & 1 deletion operators/extract_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 { expect, unwrap } from "./extract.ts";
import { expect, unwrap, unwrapOr } from "./extract.ts";
import { None, Some } from "../spec.ts";
import { assertEquals, assertThrows, describe, it } from "../_dev_deps.ts";

Expand All @@ -15,6 +15,16 @@ describe("unwrap", () => {
});
});

describe("unwrapOr", () => {
it("should some value if some", () => {
assertEquals(unwrapOr(Some.of(0), 1), 0);
});

it("should default value if None", () => {
assertEquals(unwrapOr(None, 1), 1);
});
});

describe("expect", () => {
it("should return some value", () => {
assertEquals(expect(Some.of(0), ""), 0);
Expand Down

0 comments on commit 65b1a2e

Please sign in to comment.