standard-data-structures
Version:
A collection of standard data-structures for node and browser
130 lines (129 loc) • 2.62 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/* tslint:disable no-use-before-declare prefer-function-over-method */
const noSuchValueException_1 = require("../internals/noSuchValueException");
const either_1 = require("./either");
/**
* Used to represent an optional value
*/
class Option {
/**
* Returns `true` if the instance is [[Some]]
*/
get isSome() {
return !this.isNone;
}
/**
* Creates an [[Option]] from an [[Either]]
*/
static fromEither(either) {
return either.fold(Option.none(), () => Option.none(), Option.some);
}
/**
* Checks if the Option type is of [[None]] type
*/
static isNone(A) {
return A.isNone;
}
/**
* Checks if the Option type is of [[Some]] type
*/
static isSome(A) {
return A.isSome;
}
/**
* Creates a [[None]] object
*/
static none() {
return new None();
}
/**
* Creates a [[Some]] object
*/
static some(A) {
return new Some(A);
}
/**
* Transforms the value inside the [[Option]] type.
*/
map(ab) {
return this.chain(a => Option.some(ab(a)));
}
}
exports.Option = Option;
/**
* Is an [[Option]] type that represents existence of a value.
*/
class Some extends Option {
constructor(value) {
super();
this.value = value;
}
/**
* Refer [[Option.chain]]
*/
chain(ab) {
return ab(this.value);
}
/**
* Refer [[Option.fold]]
*/
fold(S, some) {
return some(this.value, S);
}
/**
* Refer [[Option.getOrElse]]
*/
getOrElse(a) {
return this.value;
}
/**
* Refer [[Option.isNone]]
*/
get isNone() {
return false;
}
/**
* Refer [[Option.asEither]]
*/
get asEither() {
return either_1.Either.right(this.value);
}
}
exports.Some = Some;
/**
* Is an [[Option]] type that represents absence of any value.
*/
class None extends Option {
/**
* Refer [[Option.chain]]
*/
chain(ab) {
return this;
}
/**
* Refer [[Option.fold]]
*/
fold(S, some) {
return S;
}
/**
* Refer [[Option.getOrElse]]
*/
getOrElse(A) {
return A;
}
/**
* Refer [[Option.isNone]]
*/
get isNone() {
return true;
}
/**
* Refer [[Option.asEither]]
*/
get asEither() {
return either_1.Either.left(new noSuchValueException_1.NoSuchValueException());
}
}
exports.None = None;