Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. const Functor = (x) => ({
  2. map: (f) => Functor(f(x)),
  3. fold: (f) => f(x)
  4. });
  5.  
  6.  
  7. const Right = (x) => ({
  8. map: (f) => Right(f(x)),
  9. fold: (f, g) => g(x),
  10. join: () => x,
  11. chain: function (f) {
  12. return Right(this.map(f).join());
  13. }
  14. });
  15.  
  16. const Left = (x) => ({
  17. map: (f) => Left(x),
  18. fold: (f, g) => f(x),
  19. join: () => x,
  20. chain: function (f) {
  21. return Left(this.map(f).join());
  22. }
  23. });
  24.  
  25. const Maybe = (x) => !!x ? Right(x) : Left(null);
  26.  
  27. const tryCatch = (x) => ({
  28. map: (f) => {
  29. try {
  30. const newVal = f(x);
  31. return Right(x);
  32. }
  33. catch (err) {
  34. return Left(err);
  35. }
  36. },
  37. fold: (f, g) => Maybe(x).fold(f, g),
  38. join: () => x,
  39. chain: function (f) {
  40. return tryCatch(this.map(f).join());
  41. }
  42. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement