-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(extract): add extracting contained value from unwrap
- Loading branch information
1 parent
9d77de2
commit 1f06d87
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | ||
}); | ||
}); |