|
1 | 1 | import { Option, Cases } from "./types"; |
2 | 2 |
|
| 3 | +/** |
| 4 | + * `Optional` (like Java) implementation in TypeScript. |
| 5 | + * |
| 6 | + * `Optional<T>` is a type which *may* or *may not* contain a *payload* of type `T`. |
| 7 | + * It provides a common interface regardless of whether an instance is *present* or is *empty*. |
| 8 | + * |
| 9 | + * This module is inspired by [Optional class in Java 8+](https://docs.oracle.com/javase/10/docs/api/java/util/Optional.html). |
| 10 | + * |
| 11 | + * The following methods are currently not supported: |
| 12 | + * |
| 13 | + * - `equals` |
| 14 | + * - `toString` |
| 15 | + * - `hashCode` |
| 16 | + * - `stream` |
| 17 | + */ |
3 | 18 | export default abstract class Optional<T> { |
4 | 19 | /** |
5 | 20 | * Returns `true` if this is present, otherwise `false`. |
@@ -95,12 +110,30 @@ export default abstract class Optional<T> { |
95 | 110 | */ |
96 | 111 | abstract orElseThrow<U>(errorSupplier: () => U): T; |
97 | 112 |
|
| 113 | + /** |
| 114 | + * Converts this to an `Option`. |
| 115 | + */ |
98 | 116 | abstract toOption(): Option<T>; |
99 | 117 |
|
| 118 | + /** |
| 119 | + * If a payload is present, returns the payload, |
| 120 | + * otherwise returns `null`. |
| 121 | + */ |
100 | 122 | abstract orNull(): T | null; |
101 | 123 |
|
| 124 | + /** |
| 125 | + * If a payload is present, returns the payload, |
| 126 | + * otherwise returns `undefined`. |
| 127 | + */ |
102 | 128 | abstract orUndefined(): T | undefined; |
103 | 129 |
|
| 130 | + /** |
| 131 | + * Returns an appropriate result by emulating pattern matching with the given `cases`. |
| 132 | + * If a payload is present, returns the result of `present` case, |
| 133 | + * otherwise returns the result of `empty` case. |
| 134 | + * |
| 135 | + * @param cases cases for this `Optional` |
| 136 | + */ |
104 | 137 | abstract matches<U>(cases: Cases<T, U>): U; |
105 | 138 |
|
106 | 139 | /** |
@@ -147,6 +180,12 @@ export default abstract class Optional<T> { |
147 | 180 | return new EmptyOptional(); |
148 | 181 | } |
149 | 182 |
|
| 183 | + /** |
| 184 | + * Retrieve the given `option` as an Optional. |
| 185 | + * |
| 186 | + * @param option an `Option` object to retrieve |
| 187 | + * @throws {TypeError} when the given `option` does not have a valid `kind` attribute. |
| 188 | + */ |
150 | 189 | static from<T>(option: Option<T>): Optional<T> { |
151 | 190 | switch (option.kind) { |
152 | 191 | case "present": return Optional.of(option.value); |
|
0 commit comments