diff --git a/compiler/forget/src/__tests__/Result-test.ts b/compiler/forget/src/__tests__/Result-test.ts new file mode 100644 index 0000000000..5d6fa40d8b --- /dev/null +++ b/compiler/forget/src/__tests__/Result-test.ts @@ -0,0 +1,130 @@ +import { Err, Ok, Result } from "../lib/Result"; + +function addMax10(a: number, b: number): Result { + const n = a + b; + return n > 10 ? Err(`${n} is too high`) : Ok(n); +} + +function onlyFoo(foo: string): Result { + return foo === "foo" ? Ok(foo) : Err(foo); +} + +describe("Result", () => { + test(".map", () => { + expect(addMax10(1, 1).map((n) => n * 2)).toEqual(Ok(4)); + expect(addMax10(10, 10).map((n) => n * 2)).toEqual(Err("20 is too high")); + }); + + test(".mapErr", () => { + expect(addMax10(1, 1).mapErr((e) => `not a number: ${e}`)).toEqual(Ok(2)); + expect(addMax10(10, 10).mapErr((e) => `couldn't add: ${e}`)).toEqual( + Err("couldn't add: 20 is too high") + ); + }); + + test(".mapOr", () => { + expect(onlyFoo("foo").mapOr(42, (v) => v.length)).toEqual(3); + expect(onlyFoo("bar").mapOr(42, (v) => v.length)).toEqual(42); + }); + + test(".mapOrElse", () => { + expect( + onlyFoo("foo").mapOrElse( + () => 42, + (v) => v.length + ) + ).toEqual(3); + expect( + onlyFoo("bar").mapOrElse( + () => 42, + (v) => v.length + ) + ).toEqual(42); + }); + + test(".andThen", () => { + expect(addMax10(1, 1).andThen((n) => Ok(n * 2))).toEqual(Ok(4)); + expect(addMax10(10, 10).andThen((n) => Ok(n * 2))).toEqual( + Err("20 is too high") + ); + }); + + test(".and", () => { + expect(addMax10(1, 1).and(Ok(4))).toEqual(Ok(4)); + expect(addMax10(10, 10).and(Ok(4))).toEqual(Err("20 is too high")); + expect(addMax10(1, 1).and(Err("hehe"))).toEqual(Err("hehe")); + expect(addMax10(10, 10).and(Err("hehe"))).toEqual(Err("20 is too high")); + }); + + test(".or", () => { + expect(addMax10(1, 1).or(Ok(4))).toEqual(Ok(2)); + expect(addMax10(10, 10).or(Ok(4))).toEqual(Ok(4)); + expect(addMax10(1, 1).or(Err("hehe"))).toEqual(Ok(2)); + expect(addMax10(10, 10).or(Err("hehe"))).toEqual(Err("hehe")); + }); + + test(".orElse", () => { + expect(addMax10(1, 1).orElse((str) => Err(str.toUpperCase()))).toEqual( + Ok(2) + ); + expect(addMax10(10, 10).orElse((str) => Err(str.toUpperCase()))).toEqual( + Err("20 IS TOO HIGH") + ); + }); + + test(".isOk", () => { + expect(addMax10(1, 1).isOk()).toBeTruthy(); + expect(addMax10(10, 10).isOk()).toBeFalsy(); + }); + + test(".isErr", () => { + expect(addMax10(1, 1).isErr()).toBeFalsy(); + expect(addMax10(10, 10).isErr()).toBeTruthy(); + }); + + test(".expect", () => { + expect(addMax10(1, 1).expect("a number under 10")).toEqual(2); + expect(() => { + addMax10(10, 10).expect("a number under 10"); + }).toThrowErrorMatchingInlineSnapshot( + `"a number under 10: 20 is too high"` + ); + }); + + test(".expectErr", () => { + expect(() => { + addMax10(1, 1).expectErr("a number under 10"); + }).toThrowErrorMatchingInlineSnapshot(`"a number under 10: 2"`); + expect(addMax10(10, 10).expectErr("a number under 10")).toEqual( + "20 is too high" + ); + }); + + test(".unwrap", () => { + expect(addMax10(1, 1).unwrap()).toEqual(2); + expect(() => { + addMax10(10, 10).unwrap(); + }).toThrowErrorMatchingInlineSnapshot( + `"Can't unwrap \`Err\` to \`Ok\`: 20 is too high"` + ); + }); + + test(".unwrapOr", () => { + expect(addMax10(1, 1).unwrapOr(4)).toEqual(2); + expect(addMax10(10, 10).unwrapOr(4)).toEqual(4); + }); + + test(".unwrapOrElse", () => { + expect(addMax10(1, 1).unwrapOrElse(() => 4)).toEqual(2); + expect(addMax10(10, 10).unwrapOrElse((s) => s.length)).toEqual(14); + }); + + test(".unwrapErr", () => { + expect(() => { + addMax10(1, 1).unwrapErr(); + }).toThrowErrorMatchingInlineSnapshot( + `"Can't unwrap \`Ok\` to \`Err\`: 2"` + ); + expect(addMax10(10, 10).unwrapErr()).toEqual("20 is too high"); + }); +}); diff --git a/compiler/forget/src/lib/Result.ts b/compiler/forget/src/lib/Result.ts new file mode 100644 index 0000000000..e2130f14d0 --- /dev/null +++ b/compiler/forget/src/lib/Result.ts @@ -0,0 +1,244 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Direct translation of Rust's Result type, although some ownership related methods are omitted. +export interface Result { + /** + * Maps a `Result` to `Result` by applying a function to a contained `Ok` value, + * leaving an `Err` value untouched. + * + * This function can be used to compose the results of two functions. + */ + map(fn: (val: T) => U): Result; + /** + * Maps a `Result` to `Result` by applying a function to a contained `Err` value, + * leaving an `Ok` value untouched. + * + * This function can be used to pass through a successful result while handling an error. + */ + mapErr(fn: (val: E) => F): Result; + /** + * Returns the provided default (if `Err`), or applies a function to the contained value + * (if `Ok`). + * + * Arguments passed to {@link mapOr} are eagerly evaluated; if you are passing the result of a + * function call, it is recommended to use {@link mapOrElse}, which is lazily evaluated. + */ + mapOr(fallback: U, fn: (val: T) => U): U; + /** + * Maps a `Result` to `U` by applying fallback function default to a contained `Err` value, + * or function `fn` to a contained `Ok` value. + * + * This function can be used to unpack a successful result while handling an error. + */ + mapOrElse(fallback: () => U, fn: (val: T) => U): U; + /** + * Calls `fn` if the result is `Ok`, otherwise returns the `Err` value of self. + * + * This function can be used for control flow based on Result values. + */ + andThen(fn: (val: T) => Result): Result; + /** + * Returns res if the result is `Ok`, otherwise returns the `Err` value of self. + * + * Arguments passed to {@link and} are eagerly evaluated; if you are passing the result of a + * function call, it is recommended to use {@link andThen}, which is lazily evaluated. + */ + and(res: Result): Result; + /** + * Returns `res` if the result is `Err`, otherwise returns the `Ok` value of self. + * + * Arguments passed to {@link or} are eagerly evaluated; if you are passing the result of a + * function call, it is recommended to use {@link orElse}, which is lazily evaluated. + */ + or(res: Result): Result; + /** + * Calls `fn` if the result is `Err`, otherwise returns the `Ok` value of self. + * + * This function can be used for control flow based on result values. + */ + orElse(fn: (val: E) => Result): Result; + /** + * Returns `true` if the result is `Ok`. + */ + isOk(): this is OkImpl; + /** + * Returns `true` if the result is `Err`. + */ + isErr(): this is ErrImpl; + /** + * Returns the contained `Ok` value or throws. + */ + expect(msg: string): T; + /** + * Returns the contained `Err` value or throws. + */ + expectErr(msg: string): E; + /** + * Returns the contained `Ok` value. + */ + unwrap(): T; + /** + * Returns the contained `Ok` value or a provided default. + * + * Arguments passed to {@link unwrapOr} are eagerly evaluated; if you are passing the result of a + * function call, it is recommended to use {@link unwrapOrElse}, which is lazily evaluated. + */ + unwrapOr(fallback: T): T; + /** + * Returns the contained `Ok` value or computes it from a closure. + */ + unwrapOrElse(fallback: (val: E) => T): T; + /** + * Returns the contained `Err` value or throws. + */ + unwrapErr(): E; +} + +export function Ok(val: T): OkImpl { + return new OkImpl(val); +} + +class OkImpl implements Result { + constructor(private val: T) {} + + map(fn: (val: T) => U): Result { + return new OkImpl(fn(this.val)); + } + + mapErr(_fn: (val: never) => F): Result { + return this; + } + + mapOr(_fallback: U, fn: (val: T) => U): U { + return fn(this.val); + } + + mapOrElse(_fallback: () => U, fn: (val: T) => U): U { + return fn(this.val); + } + + andThen(fn: (val: T) => Result): Result { + return fn(this.val); + } + + and(res: Result): Result { + return res; + } + + or(_res: Result): Result { + return this; + } + + orElse(_fn: (val: never) => Result): Result { + return this; + } + + isOk(): boolean { + return true; + } + + isErr(): boolean { + return false; + } + + expect(_msg: string): T { + return this.val; + } + + expectErr(msg: string): never { + throw new Error(`${msg}: ${this.val}`); + } + + unwrap(): T { + return this.val; + } + + unwrapOr(_fallback: T): T { + return this.val; + } + + unwrapOrElse(_fallback: (val: never) => T): T { + return this.val; + } + + unwrapErr(): never { + throw new Error(`Can't unwrap \`Ok\` to \`Err\`: ${this.val}`); + } +} + +export function Err(val: E): ErrImpl { + return new ErrImpl(val); +} + +class ErrImpl implements Result { + constructor(private val: E) {} + + map(_fn: (val: never) => U): Result { + return this; + } + + mapErr(fn: (val: E) => F): Result { + return new ErrImpl(fn(this.val)); + } + + mapOr(fallback: U, _fn: (val: never) => U): U { + return fallback; + } + + mapOrElse(fallback: () => U, _fn: (val: never) => U): U { + return fallback(); + } + + andThen(_fn: (val: never) => Result): Result { + return this; + } + + and(_res: Result): Result { + return this; + } + + or(res: Result): Result { + return res; + } + + orElse(fn: (val: E) => ErrImpl): Result { + return fn(this.val); + } + + isOk(): boolean { + return false; + } + + isErr(): boolean { + return true; + } + + expect(msg: string): never { + throw new Error(`${msg}: ${this.val}`); + } + + expectErr(_msg: string): E { + return this.val; + } + + unwrap(): never { + throw new Error(`Can't unwrap \`Err\` to \`Ok\`: ${this.val}`); + } + + unwrapOr(fallback: T): T { + return fallback; + } + + unwrapOrElse(fallback: (val: E) => T): T { + return fallback(this.val); + } + + unwrapErr(): E { + return this.val; + } +}