Skip to content

Commit

Permalink
feat(extract): add extracting contained value from unwrap
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jul 4, 2023
1 parent 9d77de2 commit 1f06d87
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
31 changes: 31 additions & 0 deletions operators/extract.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license.
// This module is browser compatible.

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

/** Returns the contained `Some` value.
*
* @example
* ```ts
* import { Some } from "https://deno.land/x/optio/spec.ts";
* import { unwrap } from "https://deno.land/x/optio/operators/extract.ts";
* import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
*
* assertEquals(unwrap(Some.of(0)), 0);
* ```
* @throws {Error} if the {@link option} is `None`.
* @example
* ```ts
* import { None } from "https://deno.land/x/optio/spec.ts";
* import { unwrap } from "https://deno.land/x/optio/operators/extract.ts";
* import { assertThrows } from "https://deno.land/std/testing/asserts.ts";
*
* assertThrows(() => unwrap(None));
* ```
*/
export function unwrap<T>(option: Option<T>): T {
if (isSome(option)) return option.get;

throw new Error("option is None");
}
16 changes: 16 additions & 0 deletions operators/extract_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license.
// This module is browser compatible.

import { unwrap } from "./extract.ts";
import { None, Some } from "../spec.ts";
import { assertEquals, assertThrows, describe, it } from "../_dev_deps.ts";

describe("unwrap", () => {
it("should return some value", () => {
assertEquals(unwrap(Some.of(0)), 0);
});

it("should throw error if None", () => {
assertThrows(() => unwrap(None), Error, "option is None");
});
});

0 comments on commit 1f06d87

Please sign in to comment.