0.2.0 • Published 6 years ago

option-type v0.2.0

Weekly downloads
4
License
MIT
Repository
github
Last release
6 years ago

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.