JSPM

  • Created
  • Published
  • Downloads 11
  • Score
    100M100P100Q57087F
  • License MIT

Simply typesafe Result and Option monads in typescript and javascript.

Package Exports

  • simply-result
  • simply-result/dist/main.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (simply-result) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Latest released version Minified and gzipped bundle size Type support Downloads from NPM MIT licensed

simply-result

Simply typesafe Result and Option monads in typescript and javascript. 1kb minified and gzipped. Branchless implementation, waisting no processing cycles on unnecessary operations.

import { Result, Ok, Some, None } from 'simply-result';

const doSomeWork = (): Result<number, Error> => Ok(3);

const str = doSomeWork()
    .match({
        Ok: v => v === 0 ? None : Some(v),
        Err: () => None,
    })
    .map(it => 1 / it)
    .map(it => it.toPrecision(3));

if (str.isSome) {
    console.log(str.value); // "0.333"
}

Installation

NPM

npm i simply-result

import {
    Result, Ok, Err,
    Option, Some, None,
    Try, TryAsync, Get, 
    transpose, flatten, 
    fromPromise,
} from 'simply-result';

Demo

TS Playground

See ./demo

Type Docs

Result

type Result<V, E = Error> =
  | Ok<V>
  | Err<E>

interface Ok<V> {
  isOk: true
  isErr: false
  ok: V
  match<T>(cases: {
    Ok: (value: V) => T
  }): T
  map<T>(fn: (value: V) => T): Ok<T>
  mapErr(fn: unknown): Ok<V>
  toString(): string
}

interface Err<E> {
  isOk: false
  isErr: true
  err: E
  match<T>(cases: {
    Err: (error: E) => T
  }): T
  map(fn: unknown): Err<E>
  mapErr<F>(fn: (error: E) => F): Err<F>
  toString(): string
}

function Ok<V>(value: V): Ok<V>

function Err<E>(error: E): Err<E>

Option

type Option<V> =
  | Some<V>
  | None

interface Some<V> {
  isSome: true
  isNone: false
  value: V
  match<T>(cases: {
    Some: (value: V) => T
  }): T
  map<T>(fn: (value: V) => T): Some<T>
  toString(): string
}

interface None {
  isSome: false
  isNone: true
  match<T>(cases: {
    None: () => T
  }): T
  map(fn: unknown): None
  toString(): string
}

function Some<V>(value: V): Some<V>

const None: None

Helpers

function Try<V, E = Error>(fn: () => V): Result<V, E>

function TryAsync<V, E = Error>(fn: () => Promise<V>): Promise<Result<V, E>>

function Get<V, K>(maplike: {
  get(key: K): V
  has(key: K): boolean
}, key: K): Option<V>

function transpose<V, E>(result: Result<Option<V>, E>): Option<Result<V, E>>

function flatten<V>(outerOption: Option<Option<V>>): Option<V>
function flatten<V, E>(outerResult: Result<Result<V, E>, E>): Result<V, E>

function fromPromise<T, E = Error>(promiselike: PromiseLike<T>): Promise<Result<T, E>>