Advertisement
Guest User

Untitled

a guest
Jul 5th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. interface Result<V, E> {
  2.   isVal: boolean;
  3.   isErr: boolean;
  4.  
  5.   // If this is a Value, apply the function. If this is an Error, does nothing.
  6.   map<U>(f: (v: V) => U): Result<U, E>;
  7.   andThen<U>(f: (v: V) => Result<U, E>): Result<U, E>
  8.  
  9.   // If this is an Error, apply the function. If this is a Value, does nothing.
  10.   mapErr<E2>(f: (e: E) => E2): Result<V, E2>;
  11.  
  12.   // Extract the value
  13.   unwrapOrCrash(): V
  14.   unwrap(defaultVal: V): V
  15.  
  16.   or(r: Result<V, E>): Result<V, E>
  17. }
  18.  
  19. class Val<V, E> implements Result<V, E> {
  20.   private value: V;
  21.   isVal = true;
  22.   isErr = false;
  23.  
  24.   constructor(v: V) {
  25.     this.value = v;
  26.   }
  27.  
  28.   map<U>(f: (v: V) => U): Result<U, E> {
  29.     const newVal = f(this.value);
  30.     return new Val(newVal);
  31.   }
  32.  
  33.   andThen<U>(f: (v: V) => Result<U, E>): Result<U, E> {
  34.     return f(this.value);
  35.   }
  36.  
  37.   mapErr<E2>(f: (e: E) => E2): Result<V, E2> {
  38.     return new Val(this.value);
  39.   }
  40.  
  41.   unwrap(_: V): V {
  42.     return this.value;
  43.   }
  44.  
  45.   unwrapOrCrash(): V {
  46.     return this.value;
  47.   }
  48.  
  49.   or(r: Result<V, E>): Result<V, E> {
  50.     return this;
  51.   }
  52.  
  53. }
  54.  
  55. class Err<V, E> implements Result<V, E> {
  56.   private error: E;
  57.   isVal = false;
  58.   isErr = true;
  59.  
  60.   constructor(e: E) {
  61.     this.error = e;
  62.   }
  63.  
  64.   map<U>(f: (v: V) => U): Result<U, E> {
  65.     return new Err(this.error);
  66.   }
  67.  
  68.   mapErr<E2>(f: (e: E) => E2): Result<V, E2> {
  69.     return new Err(f(this.error));
  70.   }
  71.  
  72.   andThen<U>(f: (v: V) => Result<U, E>): Result<U, E> {
  73.     return new Err(this.error);
  74.   }
  75.  
  76.   unwrap(v: V): V {
  77.     return v;
  78.   }
  79.  
  80.   unwrapOrCrash(): V {
  81.     throw Exception("couldn't unwrap a result which is Err");
  82.   }
  83.  
  84.   or(r: Result<V, E>): Result<V, E> {
  85.     return r
  86.   }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement