/*! * Copyright (c) 2017-2018 by The Funfix Project Developers. * Some rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Setoid, Monad } from "funland" import * as std from "./std" import { HK, HK2 } from "./kinds" import { Throwable, NoSuchElementError } from "./errors" import { fantasyLandRegister } from "./internals" /** * Represents a value of one of two possible types (a disjoint union). * * A common use of Either is as an alternative to [[Option]] for dealing * with possible missing values. In this usage [[Option.none]] is replaced * with [[Either.left]] which can contain useful information and * [[Option.some]] is replaced with [[Either.right]]. * * Convention dictates that `left` is used for failure and `right` is used * for success. Note that this `Either` type is right-biased, meaning that * operations such as `map`, `flatMap` and `filter` work on the `right` value * and if you want to work on the `left` value, then you need to do a `swap`. * * For example, you could use `Either` to detect whether an * input is a string or an number: * * ```typescript * function tryParseInt(str: string): Either { * const i = parseInt(value) * return isNaN(i) ? Left(str) : Right(i) * } * * const result = tryParseInt("not an int") * if (result.isRight()) { * console.log(`Increment: ${result.get}`) * } else { * console.log(`ERROR: could not parse ${result.swap.get}`) * } * ``` * * @final */ export class Either implements std.IEquals>, HK2<"funfix/either", L, R> { public readonly value: L | R private readonly _isRight: boolean protected constructor(value: L | R, tag: "left" | "right") { this._isRight = tag === "right" this.value = value } /** * Returns `true` if this is a `left`, `false` otherwise. * * ```typescript * Left("hello").isLeft() // true * Right(10).isLeft() // false * ``` */ isLeft(): this is TLeft { return !this._isRight } /** * Returns `true` if this is a `right`, `false` otherwise. * * ```typescript * Left("hello").isRight() // false * Right(10).isRight() // true * ``` */ isRight(): this is TRight { return this._isRight } /** * Returns true if this is a Right and its value is equal to `elem` * (as determined by the `equals` protocol), returns `false` otherwise. * * ```typescript * // True * Right("something").contains("something") * * // False because the values are different * Right("something").contains("anything") // false * * // False because the source is a `left` * Left("something").contains("something") // false * ``` */ contains(elem: R): this is TRight { return this._isRight && std.is(this.value, elem) } /** * Returns `false` if the source is a `left`, or returns the result * of the application of the given predicate to the `right` value. * * ```typescript * // True, because it is a right and predicate holds * Right(20).exists(n => n > 10) * * // False, because the predicate returns false * Right(10).exists(n => n % 2 != 0) * * // False, because it is a left * Left(10).exists(n => n == 10) * ``` */ exists(p: (r: R) => boolean): this is TRight { return this._isRight && p(this.value as R) } /** * Filters `right` values with the given predicate, returning * the value generated by `zero` in case the source is a `right` * value and the predicate doesn't hold. * * Possible outcomes: * * - Returns the existing value of `right` if this is a `right` value and the * given predicate `p` holds for it * - Returns `Left(zero())` if this is a `right` value * and the given predicate `p` does not hold * - Returns the current "left" value, if the source is a `Left` * * ```typescript * Right(12).filterOrElse(x => x > 10, () => -1) // Right(12) * Right(7).filterOrElse(x => x > 10, () => -1) // Left(-1) * Left(7).filterOrElse(x => false, () => -1) // Left(7) * ``` */ filterOrElse(p: (r: R) => boolean, zero: () => LL): Either { return this._isRight ? (p(this.value as R) ? this as any : Left(zero())) : this as any } /** * Binds the given function across `right` values. * * This operation is the monadic "bind" operation. * It can be used to *chain* multiple `Either` references. */ flatMap(f: (r: R) => Either): Either { return this._isRight ? f(this.value as R) : (this as any) } /** Alias for [[flatMap]]. */ chain(f: (r: R) => Either): Either { return this.flatMap(f) } /** * `Applicative` apply operator. * * Resembles {@link map}, but the passed mapping function is * lifted in the `Either` context. */ ap(ff: Either S>): Either { return ff.flatMap(f => this.map(f)) } /** * Applies the `left` function to [[Left]] values, and the * `right` function to [[Right]] values and returns the result. * * ```typescript * const maybeNum: Either = * tryParseInt("not a number") * * const result: string = * maybeNum.fold( * str => `Could not parse string: ${str}`, * num => `Success: ${num}` * ) * ``` */ fold(left: (l: L) => S, right: (r: R) => S): S { return this._isRight ? right(this.value as R) : left(this.value as L) } /** * Returns true if the source is a `left` or returns * the result of the application of the given predicate to the * `right` value. * * ```typescript * // True, because it is a `left` * Left("hello").forAll(x => x > 10) * * // True, because the predicate holds * Right(20).forAll(x => x > 10) * * // False, it's a right and the predicate doesn't hold * Right(7).forAll(x => x > 10) * ``` */ forAll(p: (r: R) => boolean): boolean { return !this._isRight || p(this.value as R) } /** * Returns the `Right` value, if the source has one, * otherwise throws an exception. * * WARNING! * * This function is partial, the `Either` must be a `Right`, otherwise * a runtime exception will get thrown. Use with care. * * @throws [[NoSuchElementError]] in case the the `Either` is a `Left` */ get(): R { if (this._isRight) return this.value as R throw new NoSuchElementError("left.get()") } /** * Returns the value from this `right` or the given `fallback` * value if this is a `left`. * * ```typescript * Right(10).getOrElse(27) // 10 * Left(10).getOrElse(27) // 27 * ``` */ getOrElse(fallback: RR): R | RR { return this._isRight ? this.value as R : fallback } /** * Returns the value from this `right` or a value generated * by the given `thunk` if this is a `left`. * * ```typescript * Right(10).getOrElseL(() => 27) // 10 * Left(10).getOrElseL(() => 27) // 27 * ``` */ getOrElseL(thunk: () => RR): R | RR { return this._isRight ? this.value as R : thunk() } /** * Transform the source if it is a `right` with the given * mapping function. * * ```typescript * Right(10).map(x => x + 17) // right(27) * Left(10).map(x => x + 17) // left(10) * ``` */ map(f: (r: R) => C): Either { return this._isRight ? Right(f(this.value as R)) : (this as any) } /** * Executes the given side-effecting function if the * source is a `right` value. * * ```typescript * Right(12).forAll(console.log) // prints 12 * Left(10).forAll(console.log) // silent * ``` */ forEach(cb: (r: R) => void): void { if (this._isRight) cb(this.value as R) } /** * If this is a `left`, then return the left value as a `right` * or vice versa. * * ```typescript * Right(10).swap() // left(10) * Left(20).swap() // right(20) * ``` */ swap(): Either { return this._isRight ? Left(this.value as R) : Right(this.value as L) } /** * Returns an `Option.some(right)` if the source is a `right` value, * or `Option.none` in case the source is a `left` value. */ toOption(): Option { return this._isRight ? Some(this.value as R) : None } /** * Implements {@link IEquals.equals}. * * @param that is the right hand side of the equality check */ equals(that: Either): boolean { // tslint:disable-next-line:strict-type-predicates if (that == null) return false return this._isRight === that._isRight && std.is(this.value, that.value) } /** Implements {@link IEquals.hashCode}. */ hashCode(): number { return this._isRight ? std.hashCode(this.value as R) << 2 : std.hashCode(this.value as L) << 3 } // Implements HK /** @hidden */ readonly _URI!: "funfix/either" /** @hidden */ readonly _A!: R /** @hidden */ readonly _L!: L // Implements Constructor /** @hidden */ static readonly _Class: Either /** * Builds a pure `Either` value. * * This operation is the pure `Applicative` operation for lifting * a value in the `Either` context. */ static pure(value: A): Either { return new TRight(value) } /** * Builds a left value, equivalent with {@link Left}. */ static left(value: L): Either { return Left(value) } /** * Builds a right value, equivalent with {@link Right}. */ static right(value: R): Either { return Right(value) } /** * Maps 2 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if both `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(3) * Try.map2(Right(1), Right(2), * (a, b) => a + b * ) * * // Yields Left, because the second arg is a Left * Try.map2(Right(1), Left("error"), * (a, b) => a + b * ) * ``` * * This operation is the `Applicative.map2`. */ static map2( fa1: Either, fa2: Either, f: (a1: A1, a2: A2) => R): Either { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 return Right(f(fa1.value as A1, fa2.value as A2)) } /** * Maps 3 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if all 3 `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(6) * Try.map3(Right(1), Right(2), Right(3), * (a, b, c) => a + b + c * ) * * // Yields Left, because the second arg is a Left * Try.map3(Right(1), Left("error"), Right(3), * (a, b, c) => a + b + c * ) * ``` */ static map3( fa1: Either, fa2: Either, fa3: Either, f: (a1: A1, a2: A2, a3: A3) => R): Either { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 if (fa3.isLeft()) return fa3 return Right(f(fa1.value as A1, fa2.value as A2, fa3.value as A3)) } /** * Maps 4 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if all 4 `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(10) * Try.map4(Right(1), Right(2), Right(3), Right(4), * (a, b, c, d) => a + b + c + d * ) * * // Yields Left, because the second arg is a Left * Try.map4(Right(1), Left("error"), Right(3), Right(4), * (a, b, c, d) => a + b + c + d * ) * ``` */ static map4( fa1: Either, fa2: Either, fa3: Either, fa4: Either, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R): Either { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 if (fa3.isLeft()) return fa3 if (fa4.isLeft()) return fa4 return Right(f(fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4)) } /** * Maps 5 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if all 5 `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(15) * Try.map5(Right(1), Right(2), Right(3), Right(4), Right(5), * (a, b, c, d, e) => a + b + c + d + e * ) * * // Yields Left, because the second arg is a Left * Try.map5(Right(1), Left("error"), Right(3), Right(4), Right(5), * (a, b, c, d, e) => a + b + c + d + e * ) * ``` */ static map5( fa1: Either, fa2: Either, fa3: Either, fa4: Either, fa5: Either, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R): Either { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 if (fa3.isLeft()) return fa3 if (fa4.isLeft()) return fa4 if (fa5.isLeft()) return fa5 return Right(f(fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4, fa5.value as A5)) } /** * Maps 6 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if all 6 `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(21) * Try.map5(Right(1), Right(2), Right(3), Right(4), Right(5), Right(6), * (a, b, c, d, e, f) => a + b + c + d + e + f * ) * * // Yields Left, because the second arg is a Left * Try.map5(Right(1), Left("error"), Right(3), Right(4), Right(5), Right(6), * (a, b, c, d, e, f) => a + b + c + d + e + f * ) * ``` */ static map6( fa1: Either, fa2: Either, fa3: Either, fa4: Either, fa5: Either, fa6: Either, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R): Either { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 if (fa3.isLeft()) return fa3 if (fa4.isLeft()) return fa4 if (fa5.isLeft()) return fa5 if (fa6.isLeft()) return fa6 return Right(f(fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4, fa5.value as A5, fa6.value as A6)) } /** * Keeps calling `f` until a `Right(b)` is returned. * * Based on Phil Freeman's * [Stack Safety for Free]{@link http://functorial.com/stack-safety-for-free/index.pdf}. * * Described in `FlatMap.tailRecM`. */ static tailRecM(a: A, f: (a: A) => Either>): Either { let cursor = a while (true) { const result = f(cursor) if (!result.isRight()) return result as any const some = result.value if (some.isRight()) return Right(some.value) cursor = some.value as A } } } /** * Result of the [[Left]] data constructor, representing * "left" values in the [[Either]] disjunction. * * @final */ export class TLeft extends Either { public readonly value!: L constructor(value: L) { super(value, "left") } } /** * The `Left` data constructor represents the left side of the * [[Either]] disjoint union, as opposed to the [[Right]] side. */ export function Left(value: L): TLeft { return new TLeft(value) } /** * Result of the [[Right]] data constructor, representing * "right" values in the [[Either]] disjunction. * * @final */ export class TRight extends Either { public readonly value!: R constructor(value: R) { super(value, "right") } } /** * The `Right` data constructor represents the right side of the * [[Either]] disjoint union, as opposed to the [[Left]] side. */ export function Right(value: R): TRight { return new TRight(value) } /** * Type enumerating the type-classes that `Either` implements. */ export type EitherTypes = Setoid> & Monad<"funfix/either"> /** * Type-class implementations, compatible with the `static-land` * and `funland` specifications. * * See [funland-js.org](https://funland-js.org). */ export const EitherModule: EitherTypes = { // Setoid equals: (x, y) => x ? x.equals(y) : !y, // Functor map: (f: (a: A) => B, fa: Either) => fa.map(f), // Apply ap: (ff: Either B>, fa: Either): Either => fa.ap(ff), // Applicative of: Either.pure, // Chain chain: (f: (a: A) => Either, fa: Either): Either => fa.flatMap(f), // ChainRec chainRec: (f: (next: (a: A) => C, done: (b: B) => C, a: A) => Either, a: A): Either => Either.tailRecM(a, a => f(Either.left as any, Either.right as any, a)) } // Registers Fantasy-Land compatible symbols fantasyLandRegister(Either, EitherModule, EitherModule) /** * Represents optional values, inspired by Scala's `Option` and by * Haskell's `Maybe` data types. * * Option is an immutable data type, represented as a sum type, being * either a [[Some]], in case it contains a single element, or a [[None]], * in case it is empty. * * The most idiomatic way to use an `Option` instance is to treat it * as a collection or monad and use `map`,`flatMap`, `filter`, * or `forEach`. * * @final */ export class Option implements std.IEquals>, HK<"funfix/option", A> { // tslint:disable-next-line:variable-name private readonly _isEmpty: boolean public readonly value: undefined | A protected constructor(ref: A | undefined, isEmpty?: boolean) { /* tslint:disable-next-line:strict-type-predicates */ this._isEmpty = isEmpty != null ? isEmpty : (ref === null || ref === undefined) this.value = ref } /** * Returns the option's value. * * WARNING! * * This function is partial, the option must be non-empty, otherwise * a runtime exception will get thrown. Use with care. * * @throws [[NoSuchElementError]] in case the option is empty */ get(): A { if (!this._isEmpty) return this.value as A throw new NoSuchElementError("Option.get") } /** * Returns the option's value if the option is nonempty, otherwise * return the given `fallback`. * * See [[Option.getOrElseL]] for a lazy alternative. */ getOrElse(fallback: AA): A | AA { if (!this._isEmpty) return this.value as A else return fallback } /** * Returns the option's value if the option is nonempty, otherwise * return `null`. * ``` */ orNull(): A | null { return !this._isEmpty ? this.value as A : null } /** * Returns the option's value if the option is nonempty, otherwise * return `undefined`. */ orUndefined(): A | undefined { return !this._isEmpty ? this.value : undefined } /** * Returns the option's value if the option is nonempty, otherwise * return the result of evaluating `thunk`. * * See [[Option.getOrElse]] for a strict alternative. */ getOrElseL(thunk: () => AA): A | AA { if (!this._isEmpty) return this.value as A else return thunk() } /** * Returns this option if it is nonempty, otherwise returns the * given `fallback`. */ orElse(fallback: Option): Option { if (!this._isEmpty) return this else return fallback } /** * Returns this option if it is nonempty, otherwise returns the * given result of evaluating the given `thunk`. * * @param thunk a no-params function that gets evaluated and * whose result is returned in case this option is empty */ orElseL(thunk: () => Option): Option { if (!this._isEmpty) return this else return thunk() } /** * Returns `true` if the option is empty, `false` otherwise. */ isEmpty(): this is TNone { return this._isEmpty } /** * Returns `true` if the option is not empty, `false` otherwise. */ nonEmpty(): this is TSome { return !this._isEmpty } /** * Returns an option containing the result of applying `f` to * this option's value, or an empty option if the source is empty. * * NOTE: this is similar with `flatMap`, except with `map` the * result of `f` doesn't need to be wrapped in an `Option`. * * @param f the mapping function that will transform the value * of this option if nonempty. * * @return a new option instance containing the value of the * source mapped by the given function */ map(f: (a: A) => B): Option { return this._isEmpty ? None : Some(f(this.value as A)) } /** * Returns the result of applying `f` to this option's value if * the option is nonempty, otherwise returns an empty option. * * NOTE: this is similar with `map`, except that `flatMap` the * result returned by `f` is expected to be boxed in an `Option` * already. * * Example: * * ```typescript * const opt = Option.of(10) * * opt.flatMap(num => { * if (num % 2 == 0) * Some(num + 1) * else * None * }) * ``` * * @param f the mapping function that will transform the value * of this option if nonempty. * * @return a new option instance containing the value of the * source mapped by the given function */ flatMap(f: (a: A) => Option): Option { if (this._isEmpty) return None else return f(this.value as A) } /** Alias for [[flatMap]]. */ chain(f: (a: A) => Option): Option { return this.flatMap(f) } /** * `Applicative` apply operator. * * Resembles {@link map}, but the passed mapping function is * lifted in the `Either` context. */ ap(ff: Option<(a: A) => B>): Option { return ff.flatMap(f => this.map(f)) } /** * Returns this option if it is nonempty AND applying the * predicate `p` to the underlying value yields `true`, * otherwise return an empty option. * * @param p is the predicate function that is used to * apply filtering on the option's value * * @return a new option instance containing the value of the * source filtered with the given predicate */ filter(p: (a: A) => a is B): Option filter(p: (a: A) => boolean): Option filter(p: (a: A) => boolean): Option { if (this._isEmpty || !p(this.value as A)) return None else return this } /** * Returns the result of applying `f` to this option's value, * or in case the option is empty, the return the result of * evaluating the `fallback` function. * * This function is equivalent with: * * ```typescript * opt.map(f).getOrElseL(fallback) * ``` * * @param fallback is the function to be evaluated in case this * option is empty * * @param f is the mapping function for transforming this option's * value in case it is nonempty */ fold(fallback: () => B, f: (a: A) => B): B { if (this._isEmpty) return fallback() return f(this.value as A) } /** * Returns true if this option is nonempty and the value it * holds is equal to the given `elem`. */ contains(elem: A): boolean { return !this._isEmpty && std.is(this.value, elem) } /** * Returns `true` if this option is nonempty and the given * predicate returns `true` when applied on this option's value. * * @param p is the predicate function to test */ exists(p: (a: A) => boolean): boolean { return !this._isEmpty && p(this.value as A) } /** * Returns true if this option is empty or the given predicate * returns `true` when applied on this option's value. * * @param p is the predicate function to test */ forAll(p: (a: A) => boolean): boolean { return this._isEmpty || p(this.value as A) } /** * Apply the given procedure `cb` to the option's value if * this option is nonempty, otherwise do nothing. * * @param cb the procedure to apply */ forEach(cb: (a: A) => void): void { if (!this._isEmpty) cb(this.value as A) } /** * Implements {@link IEquals.equals}. * * @param that is the right hand side of the equality check */ equals(that: Option): boolean { // tslint:disable-next-line:strict-type-predicates if (that == null) return false if (this.nonEmpty() && that.nonEmpty()) { return std.is(this.value, that.value) } return this.isEmpty() && that.isEmpty() } // Implemented from IEquals hashCode(): number { if (this._isEmpty) return 2433880 // tslint:disable-next-line:strict-type-predicates else if (this.value == null) return 2433881 << 2 else return std.hashCode(this.value) << 2 } // Implements HK /** @hidden */ readonly _URI!: "funfix/option" /** @hidden */ readonly _A!: A // Implements Constructor /** @hidden */ static readonly _Class: Option /** * Builds an [[Option]] reference that contains the given value. * * If the given value is `null` or `undefined` then the returned * option will be empty. */ static of(value: A | null | undefined): Option { return value != null ? Some(value) : None } /** * Builds an [[Option]] reference that contains the given reference. * * Note that `value` is allowed to be `null` or `undefined`, the * returned option will still be non-empty. Use [[Option.of]] * if you want to avoid this problem. This means: * * ```typescript * const opt = Some(null) * * opt.isEmpty() * //=> false * * opt.get() * //=> null * ``` */ static some(value: A): Option { return new Option(value, false) } /** * Returns an empty [[Option]]. * * NOTE: Because `Option` is immutable, this function returns the * same cached reference is on different calls. */ static none(): Option { return None } /** * Returns an empty [[Option]]. * * Similar to [[Option.none]], but this one allows specifying a * type parameter (in the context of TypeScript or Flow or other * type system). * * NOTE: Because `Option` is immutable, this function returns the * same cached reference is on different calls. */ static empty(): Option { return None } /** * Alias for [[Some]]. */ static pure(value: A): Option { return Some(value) } /** * Maps 2 optional values by the mapping function, returning a new * optional reference that is `Some` only if both option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(3) * Option.map2(Some(1), Some(2), * (a, b) => a + b * ) * * // Yields None, because the second arg is None * Option.map2(Some(1), None, * (a, b) => a + b * ) * ``` * * This operation is the `Applicative.map2`. */ static map2( fa1: Option, fa2: Option, f: (a1: A1, a2: A2) => R): Option { return fa1.nonEmpty() && fa2.nonEmpty() ? Some(f(fa1.value, fa2.value)) : None } /** * Maps 3 optional values by the mapping function, returning a new * optional reference that is `Some` only if all 3 option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(6) * Option.map3(Some(1), Some(2), Some(3), * (a, b, c) => a + b + c * ) * * // Yields None, because the second arg is None * Option.map3(Some(1), None, Some(3), * (a, b, c) => a + b + c * ) * ``` */ static map3( fa1: Option, fa2: Option, fa3: Option, f: (a1: A1, a2: A2, a3: A3) => R): Option { return fa1.nonEmpty() && fa2.nonEmpty() && fa3.nonEmpty() ? Some(f(fa1.value, fa2.value, fa3.value)) : None } /** * Maps 4 optional values by the mapping function, returning a new * optional reference that is `Some` only if all 4 option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(10) * Option.map4(Some(1), Some(2), Some(3), Some(4), * (a, b, c, d) => a + b + c + d * ) * * // Yields None, because the second arg is None * Option.map4(Some(1), None, Some(3), Some(4), * (a, b, c, d) => a + b + c + d * ) * ``` */ static map4( fa1: Option, fa2: Option, fa3: Option, fa4: Option, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R): Option { return fa1.nonEmpty() && fa2.nonEmpty() && fa3.nonEmpty() && fa4.nonEmpty() ? Some(f(fa1.value, fa2.value, fa3.value, fa4.value)) : None } /** * Maps 5 optional values by the mapping function, returning a new * optional reference that is `Some` only if all 5 option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(15) * Option.map5(Some(1), Some(2), Some(3), Some(4), Some(5), * (a, b, c, d, e) => a + b + c + d + e * ) * * // Yields None, because the second arg is None * Option.map5(Some(1), None, Some(3), Some(4), Some(5), * (a, b, c, d, e) => a + b + c + d + e * ) * ``` */ static map5( fa1: Option, fa2: Option, fa3: Option, fa4: Option, fa5: Option, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R): Option { return fa1.nonEmpty() && fa2.nonEmpty() && fa3.nonEmpty() && fa4.nonEmpty() && fa5.nonEmpty() ? Some(f(fa1.value, fa2.value, fa3.value, fa4.value, fa5.value)) : None } /** * Maps 6 optional values by the mapping function, returning a new * optional reference that is `Some` only if all 6 option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(21) * Option.map6(Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), * (a, b, c, d, e, f) => a + b + c + d + e + f * ) * * // Yields None, because the second arg is None * Option.map6(Some(1), None, Some(3), Some(4), Some(5), Some(6), * (a, b, c, d, e, f) => a + b + c + d + e + f * ) * ``` */ static map6( fa1: Option, fa2: Option, fa3: Option, fa4: Option, fa5: Option, fa6: Option, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R): Option { return fa1.nonEmpty() && fa2.nonEmpty() && fa3.nonEmpty() && fa4.nonEmpty() && fa5.nonEmpty() && fa6.nonEmpty() ? Some(f(fa1.value, fa2.value, fa3.value, fa4.value, fa5.value, fa6.value)) : None } /** * Keeps calling `f` until a `Right(b)` is returned. * * Based on Phil Freeman's * [Stack Safety for Free]{@link http://functorial.com/stack-safety-for-free/index.pdf}. * * Described in `FlatMap.tailRecM`. */ static tailRecM(a: A, f: (a: A) => Option>): Option { let cursor = a while (true) { const result = f(cursor) if (result.nonEmpty()) { const some = result.value if (some.isRight()) return Some(some.value) cursor = some.value as A } else { return None } } } } /** * Result of the [[Some]] data constructor, representing * non-empty values in the [[Option]] disjunction. */ export class TSome extends Option { public readonly value!: A constructor(value: A) { super(value, false) } } /** * The `Some` data constructor for [[Option]] represents existing * values of type `A`. * * Using this function is equivalent with [[Option.some]]. */ export function Some(value: A): TSome { return new TSome(value) } /** * Result of the [[Some]] data constructor, representing * non-empty values in the [[Option]] disjunction. */ export class TNone extends Option { public readonly value!: undefined private constructor() { super(undefined, true) } } /** * The `None` data constructor for [[Option]] represents non-existing * values for any type. * * Using this reference directly is equivalent with [[Option.none]]. */ export const None: TNone = new (TNone as any)() /** * Type enumerating the type classes implemented by `Option`. */ export type OptionTypes = Setoid> & Monad<"funfix/option"> /** * Type-class implementations, compatible with the `static-land` * and `funland` specification. * * See [funland-js.org](https://funland-js.org). */ export const OptionModule: OptionTypes = { // Setoid equals: (x, y) => x ? x.equals(y) : !y, // Functor map: (f: (a: A) => B, fa: Option) => fa.map(f), // Apply ap: (ff: Option<(a: A) => B>, fa: Option): Option => fa.ap(ff), // Applicative of: Option.pure, // Chain chain: (f: (a: A) => Option, fa: Option): Option => fa.flatMap(f), // ChainRec chainRec: (f: (next: (a: A) => C, done: (b: B) => C, a: A) => Option, a: A): Option => Option.tailRecM(a, a => f(Either.left as any, Either.right as any, a)) } // Registers Fantasy-Land compatible symbols fantasyLandRegister(Option, OptionModule, OptionModule) /** * The `Try` type represents a computation that may either result in an * exception, or return a successfully computed value. It's similar to, * but semantically different from the [[Either]] type. * * `Try` is a sum type and so instances of `Try` are either instances * of [[Success]] or of [[Failure]]. * * For example, `Try` can be used to perform division on a user-defined * input, without the need to do explicit exception-handling in all of * the places that an exception might occur. * * Example: * * ```typescript * function divide(dividendS: string, divisorS: string): string { * const dividend = Try(() => parseInt(dividendS)) * .filter(_ => _ === _) // filter out NaN * const divisor = Try(() => parseInt(divisorS)) * .filter(_ => _ === _) // filter out NaN * * // map2 executes the given function only if both results are * // successful; we could also express this with flatMap / chain * const result = Try.map2(dividend, divisor, * (a, b) => a / b * ) * * result.fold( * error => `failure: ${error}` * result => `result: ${result}` * ) * } * ``` * * An important property of `Try` is its ability to pipeline, or chain, * operations, catching exceptions along the way. The `flatMap` and `map` * combinators each essentially pass off either their successfully completed * value, wrapped in the [[Success]] type for it to be further operated upon * by the next combinator in the chain, or the exception wrapped in the * [[Failure]] type usually to be simply passed on down the chain. * Combinators such as `recover` and `recoverWith` are designed to provide * some type of global behavior in the case of failure. * * NOTE: all `Try` combinators will catch exceptions and return failure * unless otherwise specified in the documentation. */ export class Try implements std.IEquals>, HK<"funfix/try", A> { private _isSuccess: boolean public readonly value: Throwable | A protected constructor(value: Throwable | A, tag: "failure" | "success") { this._isSuccess = tag === "success" this.value = value } /** * Returns `true` if the source is a [[Success]] result, * or `false` in case it is a [[Failure]]. */ isSuccess(): this is TSuccess { return this._isSuccess } /** * Returns `true` if the source is a [[Failure]], * or `false` in case it is a [[Success]] result. */ isFailure(): this is TFailure { return !this._isSuccess } /** * Returns a Try's successful value if it's a [[Success]] reference, * otherwise throws an exception if it's a [[Failure]]. * * WARNING! * * This function is partial, the option must be non-empty, otherwise * a runtime exception will get thrown. Use with care. */ get(): A { if (!this._isSuccess) throw this.value return this.value as A } /** * Returns the value from a `Success` or the given `fallback` * value if this is a `Failure`. * * ```typescript * Success(10).getOrElse(27) // 10 * Failure("error").getOrElse(27) // 27 * ``` */ getOrElse(fallback: AA): A | AA { return this._isSuccess ? this.value as A : fallback } /** * Returns the value from a `Success` or the value generated * by a given `thunk` in case this is a `Failure`. * * ```typescript * Success(10).getOrElseL(() => 27) // 10 * Failure("error").getOrElseL(() => 27) // 27 * ``` */ getOrElseL(thunk: () => AA): A | AA { return this._isSuccess ? this.value as A : thunk() } /** * Returns the current value if it's a [[Success]], or * if the source is a [[Failure]] then return `null`. * * ```typescript * Success(10).orNull() // 10 * Failure("error").orNull() // null * ``` * * This can be useful for use-cases such as: * * ```typescript * Try.of(() => dict.user.profile.name).orNull() * ``` */ orNull(): A | null { return this._isSuccess ? this.value as A : null } /** * Returns the current value if it's a [[Success]], or * if the source is a [[Failure]] then return `undefined`. * * ```typescript * Success(10).orUndefined() // 10 * Failure("error").orUndefined() // undefined * ``` * * This can be useful for use-cases such as: * * ```typescript * Try.of(() => dict.user.profile.name).orUndefined() * ``` */ orUndefined(): A | undefined { return this._isSuccess ? this.value as A : undefined } /** * Returns the current value if it's a [[Success]], or if * the source is a [[Failure]] then return the `fallback`. * * ```typescript * Success(10).orElse(Success(17)) // 10 * Failure("error").orElse(Success(17)) // 17 * ``` */ orElse(fallback: Try): Try { if (this._isSuccess) return this return fallback } /** * Returns the current value if it's a [[Success]], or if the source * is a [[Failure]] then return the value generated by the given * `thunk`. * * ```typescript * Success(10).orElseL(() => Success(17)) // 10 * Failure("error").orElseL(() => Success(17)) // 17 * ``` */ orElseL(thunk: () => Try): Try { if (this._isSuccess) return this return thunk() } /** * Inverts this `Try`. If this is a [[Failure]], returns its exception wrapped * in a [[Success]]. If this is a `Success`, returns a `Failure` containing a * [[NoSuchElementError]]. */ failed(): Try { return this._isSuccess ? Failure(new NoSuchElementError("try.failed()")) : Success(this.value as Throwable) } /** * Applies the `failure` function to [[Failure]] values, and the * `success` function to [[Success]] values and returns the result. * * ```typescript * const maybeNum: Try = * tryParseInt("not a number") * * const result: string = * maybeNum.fold( * error => `Could not parse string: ${error}`, * num => `Success: ${num}` * ) * ``` */ fold(failure: (error: Throwable) => R, success: (a: A) => R): R { return this._isSuccess ? success(this.value as A) : failure(this.value as Throwable) } /** * Returns a [[Failure]] if the source is a [[Success]], but the * given `p` predicate is not satisfied. * * @throws NoSuchElementError in case the predicate doesn't hold */ filter(p: (a: A) => a is B): Try filter(p: (a: A) => boolean): Try filter(p: (a: A) => boolean): Try { if (!this._isSuccess) return this try { if (p(this.value as A)) return this return Failure( new NoSuchElementError( `Predicate does not hold for ${this.value as A}` )) } catch (e) { return Failure(e) } } /** * Returns the given function applied to the value if this is * a [[Success]] or returns `this` if this is a [[Failure]]. * * This operation is the monadic "bind" operation. * It can be used to *chain* multiple `Try` references. * * ```typescript * Try.of(() => parse(s1)).flatMap(num1 => * Try.of(() => parse(s2)).map(num2 => * num1 / num2 * )) * ``` */ flatMap(f: (a: A) => Try): Try { if (!this._isSuccess) return this as any try { return f(this.value as A) } catch (e) { return Failure(e) } } /** Alias for [[flatMap]]. */ chain(f: (a: A) => Try): Try { return this.flatMap(f) } /** * `Applicative` apply operator. * * Resembles {@link map}, but the passed mapping function is * lifted in the `Either` context. */ ap(ff: Try<(a: A) => B>): Try { return ff.flatMap(f => this.map(f)) } /** * Returns a `Try` containing the result of applying `f` to * this option's value, but only if it's a `Success`, or * returns the current `Failure` without any modifications. * * NOTE: this is similar with `flatMap`, except with `map` the * result of `f` doesn't need to be wrapped in a `Try`. * * @param f the mapping function that will transform the value * of this `Try` if successful. * * @return a new `Try` instance containing the value of the * source mapped by the given function */ map(f: (a: A) => B): Try { return this._isSuccess ? Try.of(() => f(this.value as A)) : ((this as any) as Try) } /** * Applies the given function `cb` if this is a [[Success]], otherwise * returns `void` if this is a [[Failure]]. */ forEach(cb: (a: A) => void): void { if (this._isSuccess) cb(this.value as A) } /** * Applies the given function `f` if this is a `Failure`, otherwise * returns `this` if this is a `Success`. * * This is like `map` for the exception. * * In the following example, if the `user.profile.email` exists, * then it is returned as a successful value, otherwise * * ```typescript * Try.of(() => user.profile.email).recover(e => { * // Access error? Default to empty. * if (e instanceof TypeError) return "" * throw e // We don't know what it is, rethrow * }) * * Note that on rethrow, the error is being caught in `recover` and * it still returns it as a `Failure(e)`. * ``` */ recover(f: (error: Throwable) => AA): Try { return this._isSuccess ? this : Try.of(() => f(this.value as Throwable)) } /** * Applies the given function `f` if this is a `Failure`, otherwise * returns `this` if this is a `Success`. * * This is like `map` for the exception. * * In the following example, if the `user.profile.email` exists, * then it is returned as a successful value, otherwise * * ```typescript * Try.of(() => user.profile.email).recover(e => { * // Access error? Default to empty. * if (e instanceof TypeError) return "" * throw e // We don't know what it is, rethrow * }) * * Note that on rethrow, the error is being caught in `recover` and * it still returns it as a `Failure(e)`. * ``` */ recoverWith(f: (error: Throwable) => Try): Try { try { return this._isSuccess ? this : f(this.value as Throwable) } catch (e) { return Failure(e) } } /** * Transforms the source into an [[Option]]. * * In case the source is a `Success(v)`, then it gets translated * into a `Some(v)`. If the source is a `Failure(e)`, then a `None` * value is returned. * * ```typescript * Success("value").toOption() // Some("value") * Failure("error").toOption() // None * ``` */ toOption(): Option { return this._isSuccess ? Some(this.value as A) : None } /** * Transforms the source into an [[Either]]. * * In case the source is a `Success(v)`, then it gets translated * into a `Right(v)`. If the source is a `Failure(e)`, then a `Left(e)` * value is returned. * * ```typescript * Success("value").toEither() // Right("value") * Failure("error").toEither() // Left("error") * ``` */ toEither(): Either { return this._isSuccess ? Right(this.value as A) : Left(this.value as Throwable) } /** * Implements {@link IEquals.equals} with overridable equality for `A`. */ equals(that: Try): boolean { // tslint:disable-next-line:strict-type-predicates if (that == null) return false return this._isSuccess ? that._isSuccess && std.is(this.value as A, that.value as A) : !that._isSuccess && std.is(this.value, that.value) } // Implemented from IEquals hashCode(): number { return this._isSuccess ? std.hashCode(this.value as A) : std.hashCode(this.value as Throwable) } // Implements HK /** @hidden */ readonly _URI!: "funfix/try" /** @hidden */ readonly _A!: A // Implements Constructor /** @hidden */ static readonly _Class: Try /** * Evaluates the given `thunk` and returns either a [[Success]], * in case the evaluation succeeded, or a [[Failure]], in case * an exception was thrown. * * Example: * * ```typescript * let effect = 0 * * const e = Try.of(() => { effect += 1; return effect }) * e.get() // 1 * ``` */ static of(thunk: () => A): Try { try { return Success(thunk()) } catch (e) { return Failure(e) } } /** Alias of [[Try.success]]. */ static pure(value: A): Try { return Try.success(value) } /** * Shorthand for `now(undefined as void)`, always returning * the same reference as optimization. */ static unit(): Try { return tryUnitRef } /** * Returns a [[Try]] reference that represents a successful result * (i.e. wrapped in [[Success]]). */ static success(value: A): Try { return Success(value) } /** * Returns a [[Try]] reference that represents a failure * (i.e. an exception wrapped in [[Failure]]). */ static failure(e: Throwable): Try { return Failure(e) } /** * Alias for {@link Try.failure} and {@link Failure}, * wrapping any throwable into a `Try` value. */ static raise(e: Throwable): Try { return Failure(e) } /** * Maps 2 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if both `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(3) * Try.map2(Success(1), Success(2), * (a, b) => a + b * ) * * // Yields Failure, because the second arg is a Failure * Try.map2(Success(1), Failure("error"), * (a, b) => a + b * ) * ``` * * This operation is the `Applicative.map2`. */ static map2( fa1: Try, fa2: Try, f: (a1: A1, a2: A2) => R): Try { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 try { return Success(f(fa1.value as A1, fa2.value as A2)) } catch (e) { return Failure(e) } } /** * Maps 3 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if all 3 `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(6) * Try.map3(Success(1), Success(2), Success(3), * (a, b, c) => { * return a + b + c * } * ) * * // Yields Failure, because the second arg is a Failure * Try.map3( * Success(1), * Failure("error"), * Success(3), * * (a, b, c) => { * return a + b + c * } * ) * ``` */ static map3( fa1: Try, fa2: Try, fa3: Try, f: (a1: A1, a2: A2, a3: A3) => R): Try { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 if (fa3.isFailure()) return fa3 try { return Success(f( fa1.value as A1, fa2.value as A2, fa3.value as A3 )) } catch (e) { return Failure(e) } } /** * Maps 4 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if all 4 `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(10) * Try.map4(Success(1), Success(2), Success(3), Success(4), * (a, b, c, d) => { * return a + b + c + d * } * ) * * // Yields Failure, because the second arg is a Failure * Try.map3( * Success(1), * Failure("error"), * Success(3), * Success(4), * * (a, b, c, d) => { * return a + b + c + d * } * ) * ``` */ static map4( fa1: Try, fa2: Try, fa3: Try, fa4: Try, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R): Try { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 if (fa3.isFailure()) return fa3 if (fa4.isFailure()) return fa4 try { return Success(f( fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4 )) } catch (e) { return Failure(e) } } /** * Maps 5 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if all 5 `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(15) * Try.map5( * Success(1), * Success(2), * Success(3), * Success(4), * Success(5), * * (a, b, c, d, e) => { * return a + b + c + d + e * } * ) * * // Yields Failure, because the second arg is a Failure * Try.map5( * Success(1), * Failure("error"), * Success(3), * Success(4), * Success(5), * * (a, b, c, d, e) => { * return a + b + c + d + e * } * ) * ``` */ static map5( fa1: Try, fa2: Try, fa3: Try, fa4: Try, fa5: Try, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R): Try { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 if (fa3.isFailure()) return fa3 if (fa4.isFailure()) return fa4 if (fa5.isFailure()) return fa5 try { return Success(f( fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4, fa5.value as A5 )) } catch (e) { return Failure(e) } } /** * Maps 6 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if all 6 `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(21) * Try.map6( * Success(1), * Success(2), * Success(3), * Success(4), * Success(5), * Success(6), * * (a, b, c, d, e, f) => { * return a + b + c + d + e + f * } * ) * * // Yields Failure, because the second arg is a Failure * Try.map6( * Success(1), * Failure("error"), * Success(3), * Success(4), * Success(5), * Success(6), * * (a, b, c, d, e, f) => { * return a + b + c + d + e + f * } * ) * ``` */ static map6( fa1: Try, fa2: Try, fa3: Try, fa4: Try, fa5: Try, fa6: Try, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R): Try { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 if (fa3.isFailure()) return fa3 if (fa4.isFailure()) return fa4 if (fa5.isFailure()) return fa5 if (fa6.isFailure()) return fa6 try { return Success(f( fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4, fa5.value as A5, fa6.value as A6 )) } catch (e) { return Failure(e) } } /** * Keeps calling `f` until a `Right(b)` is returned. * * Based on Phil Freeman's * [Stack Safety for Free]{@link http://functorial.com/stack-safety-for-free/index.pdf}. * * Described in `FlatMap.tailRecM`. */ static tailRecM(a: A, f: (a: A) => Try>): Try { let cursor = a while (true) { try { const result = f(cursor) if (result.isFailure()) return result as any const some = result.get() if (some.isRight()) return Success(some.value) cursor = some.value as A } catch (e) { return Failure(e) } } } } /** * Result of the [[Success]] data constructor, representing * successful values in the [[Try]] disjunction. * * @final */ export class TSuccess extends Try { public readonly value!: A constructor(value: A) { super(value, "success") } } /** * The `Success` data constructor is for building [[Try]] values that * are successful results of computations, as opposed to [[Failure]]. */ export function Success(value: A): Try { return new TSuccess(value) } /** * The `Success` data constructor is for building [[Try]] values that * are successful results of computations, as opposed to [[Failure]]. * * @final */ export class TFailure extends Try { public readonly value!: Throwable constructor(value: Throwable) { super(value, "failure") } } /** * The `Failure` data constructor is for building [[Try]] values that * represent failures, as opposed to [[Success]]. */ export function Failure(e: Throwable): Try { return new TFailure(e) } /** * Type enumerating the type classes implemented by `Try`. */ export type TryTypes = Setoid> & Monad<"funfix/try"> /** * Type-class implementations, compatible with the `static-land` * and `funland` specifications. * * See [funland-js.org](https://funland-js.org). */ export const TryModule: TryTypes = { // Setoid equals: (x, y) => x ? x.equals(y) : !y, // Functor map: (f: (a: A) => B, fa: Try) => fa.map(f), // Apply ap: (ff: Try<(a: A) => B>, fa: Try): Try => fa.ap(ff), // Applicative of: Try.pure, // Chain chain: (f: (a: A) => Try, fa: Try): Try => fa.flatMap(f), // ChainRec chainRec: (f: (next: (a: A) => C, done: (b: B) => C, a: A) => Try, a: A): Try => Try.tailRecM(a, a => f(Either.left as any, Either.right as any, a)) } // Registers Fantasy-Land compatible symbols fantasyLandRegister(Try, TryModule, TryModule) /** * Reusable reference, to use in {@link Try.unit}. * * @private * @hidden */ const tryUnitRef: Try = Success(undefined)