Skip to content

Latest commit

 

History

History
121 lines (79 loc) · 2.92 KB

option.md

File metadata and controls

121 lines (79 loc) · 2.92 KB

Option<T>

This container represents an optional value. You can create a Option<T> by calling either of the following constructors:

  • Some('Hello world')
  • None()

Methods and variables

Option.some and Option.value

Option.some is used to check if an Option contains a value or not.

  • If Option.some === true, then Option.value exist.
  • If Option.some === false, then Option.value doesn't exist.

Example

Todo

Option.map()

Map Option<T> into a new Option<U>.

  • .map() is used to continue work on references that may point to a value or not

Example

const helloWorld = new Some("Hello world");

// Converts Some("Hello world") → Some(11)
const helloWorldLength = helloWorld.map(helloStr => helloStr.length);

// Outputs 'Some(11)'
console.log(helloWorldLength);

Option.and()

Combine Option<T> with another Option<U> to create Option<U>.

  • .and() is similar to .map()
  • .and() is useful for when you are combining many Option types.

Example

const helloWorld = new Some("Hello world");

// Converts Some("Hello world") → Some(11)
const helloWorldLength = helloWorld.and(helloStr => new Some(helloStr.length));

// Outputs 'Some(11)'
console.log(helloWorldLength);

Option.unwrap()

Returns the internal value of Option<T>. Throws if there is no value.

In general, because this function may throw, use of .unwrap() use is discouraged. Instead, prefer to use an if statment and check .some and handle the None case explicitly.

  • .unwrap() can be used when an Option is guaranteed to hold a value.
  • .unwrap() can be used when writing first versions of software and refactored later

Example

const helloWorld = new Some("Hello world");

// Outputs 'Hello world'
console.log(helloWorld.unwrap());

Option.unwrapOr()

Returns the internal value of Option<T> if any, otherwise a default value.

Example

const helloWorld = new Some("Hello World");
const none = new None();

// Outputs 'Hello World'
console.log(helloWorld.unwrapOr("Hello Vertical"));

// Outputs 'Hello Vertical'
console.log(none.unwrapOr("Hello Vertical"));

Full example

import { Option, Some, None } from "containers-ts";

function toNumber(s: string): Option<number> {
  const number = Number(s);
  if (isNaN(number)) {
    return new None();
  }
  return new Some(number);
}

function addToString(s: string, n: number): Option<string> {
  return toNumber("4").map(n => String(n + 1));
}

// Outputs: Some("8")
console.log(addToString("4", 4));

// Outputs: None
console.log(addToString("Vertical Strategy", 4));