https://github.com/dgraham/option-type
An Option type for Flow, inspired by Rust.
https://github.com/dgraham/option-type
maybe optionals result-type
Last synced: 8 months ago
JSON representation
An Option type for Flow, inspired by Rust.
- Host: GitHub
- URL: https://github.com/dgraham/option-type
- Owner: dgraham
- License: mit
- Created: 2017-08-09T02:58:35.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2020-08-31T01:30:50.000Z (almost 6 years ago)
- Last Synced: 2025-02-01T16:47:43.430Z (over 1 year ago)
- Topics: maybe, optionals, result-type
- Language: JavaScript
- Size: 155 KB
- Stars: 4
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Option type
An [Option][] type for [Flow][], inspired by [Rust][].
[Option]: https://en.wikipedia.org/wiki/Option_type
[Flow]: https://flow.org
[Rust]: https://doc.rust-lang.org/std/option/index.html
## Usage
```js
import {type Option, Some, None} from 'option-type';
function divide(numerator: number, denominator: number): Option {
if (denominator === 0) {
return None;
} else {
return Some(numerator / denominator);
}
}
const result = divide(2, 3);
const message = result.match({
Some: x => `Result: ${x}`,
None: () => 'Cannot divide by zero'
});
console.log(message);
```
## Result
A [`Result`][result] type is also included in this package because it's so
closely related to `Option`.
```js
import {type Result, Ok, Err} from 'option-type';
function parse(json: string): Result {
try {
return Ok(JSON.parse(json));
} catch (e) {
return Err(e);
}
}
const result = parse('{"name": "hubot"}');
const message = result.match({
Ok: x => `Result: ${x.name}`,
Err: e => `Failed to parse JSON text: ${e}`
});
console.log(message);
```
[result]: https://doc.rust-lang.org/std/result/enum.Result.html
## Development
```
npm install
npm test
```
## License
Distributed under the MIT license. See LICENSE for details.