Skip to content

An Option type for Flow, inspired by Rust.

License

Notifications You must be signed in to change notification settings

dgraham/option-type

Repository files navigation

Option type

An Option type for Flow, inspired by Rust.

Usage

import {type Option, Some, None} from 'option-type';

function divide(numerator: number, denominator: number): Option<number> {
  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 type is also included in this package because it's so closely related to Option.

import {type Result, Ok, Err} from 'option-type';

function parse(json: string): Result<Object, Error> {
  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);

Development

npm install
npm test

License

Distributed under the MIT license. See LICENSE for details.

About

An Option type for Flow, inspired by Rust.

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published