Guest User

Untitled

a guest
Jun 18th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. export type Unsafe<T> = Error | T;
  2.  
  3. export function match<T, TResult>(input: Unsafe<T>, succ: (t: T) => TResult, err: (err: Error) => TResult): TResult {
  4. if (input instanceof Error) {
  5. return err(input);
  6. }
  7. return succ(input as T);
  8. }
  9.  
  10. export function matcher<T>(input: Unsafe<T>): IMatcher<T> {
  11. return new Matcher(input);
  12. }
  13.  
  14. interface IRightMatcherContext<TResult> {
  15. left(act: (err: Error) => TResult): TResult;
  16. }
  17.  
  18. class RightMatcherContext<T, TResult> implements IRightMatcherContext<TResult> {
  19.  
  20. private right: (t: T) => TResult;
  21. private input: Unsafe<T>;
  22.  
  23. constructor(input: Unsafe<T>, right: (t: T) => TResult) {
  24. this.right = right;
  25. this.input = input;
  26. }
  27.  
  28. public left(act: (err: Error) => TResult): TResult {
  29. return match(this.input, this.right, act);
  30. }
  31. }
  32.  
  33. interface IMatcher<T> {
  34. ifLeft(act: (err: Error) => void): void;
  35. ifRight(act: (t: T) => void): void;
  36.  
  37. right<TResult>(act: (t: T) => TResult): RightMatcherContext<T, TResult>;
  38. }
  39.  
  40. class Matcher<T> implements IMatcher<T> {
  41. private input: Unsafe<T>;
  42.  
  43. constructor(input: Unsafe<T>) {
  44. this.input = input;
  45. }
  46.  
  47. public ifLeft(act: (err: Error) => void): void {
  48. if (this.input instanceof Error) {
  49. act(this.input);
  50. }
  51. }
  52.  
  53. public ifRight(act: (t: T) => void): void {
  54. if (!(this.input instanceof Error)) {
  55. act(this.input as T);
  56. }
  57. }
  58.  
  59. public right<TResult>(act: (t: T) => TResult): RightMatcherContext<T, TResult> {
  60. throw new Error("Method not implemented.");
  61. }
  62. }
Add Comment
Please, Sign In to add comment