Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface Result<V, E> {
- isVal: boolean;
- isErr: boolean;
- // If this is a Value, apply the function. If this is an Error, does nothing.
- map<U>(f: (v: V) => U): Result<U, E>;
- andThen<U>(f: (v: V) => Result<U, E>): Result<U, E>
- // If this is an Error, apply the function. If this is a Value, does nothing.
- mapErr<E2>(f: (e: E) => E2): Result<V, E2>;
- // Extract the value
- unwrapOrCrash(): V
- unwrap(defaultVal: V): V
- or(r: Result<V, E>): Result<V, E>
- }
- class Val<V, E> implements Result<V, E> {
- private value: V;
- isVal = true;
- isErr = false;
- constructor(v: V) {
- this.value = v;
- }
- map<U>(f: (v: V) => U): Result<U, E> {
- const newVal = f(this.value);
- return new Val(newVal);
- }
- andThen<U>(f: (v: V) => Result<U, E>): Result<U, E> {
- return f(this.value);
- }
- mapErr<E2>(f: (e: E) => E2): Result<V, E2> {
- return new Val(this.value);
- }
- unwrap(_: V): V {
- return this.value;
- }
- unwrapOrCrash(): V {
- return this.value;
- }
- or(r: Result<V, E>): Result<V, E> {
- return this;
- }
- }
- class Err<V, E> implements Result<V, E> {
- private error: E;
- isVal = false;
- isErr = true;
- constructor(e: E) {
- this.error = e;
- }
- map<U>(f: (v: V) => U): Result<U, E> {
- return new Err(this.error);
- }
- mapErr<E2>(f: (e: E) => E2): Result<V, E2> {
- return new Err(f(this.error));
- }
- andThen<U>(f: (v: V) => Result<U, E>): Result<U, E> {
- return new Err(this.error);
- }
- unwrap(v: V): V {
- return v;
- }
- unwrapOrCrash(): V {
- throw Exception("couldn't unwrap a result which is Err");
- }
- or(r: Result<V, E>): Result<V, E> {
- return r
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment