function.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. function nullOrUndef(t) {
  4. return t === null || t === undefined;
  5. }
  6. var Maybe = (function () {
  7. function Maybe(t) {
  8. this.t = t;
  9. }
  10. Maybe.lift = function (t) {
  11. return new Maybe(nullOrUndef(t) ? undefined : t);
  12. };
  13. Maybe.all = function (t0, t1) {
  14. return t0.bind(function (_t0) { return t1.fmap(function (_t1) { return [_t0, _t1]; }); });
  15. };
  16. Maybe.prototype.bind = function (fn) {
  17. return nullOrUndef(this.t) ? Maybe.nothing : fn(this.t);
  18. };
  19. Maybe.prototype.fmap = function (fn) {
  20. return this.bind(function (t) { return Maybe.lift(fn(t)); });
  21. };
  22. Object.defineProperty(Maybe.prototype, "isNothing", {
  23. get: function () {
  24. return nullOrUndef(this.t);
  25. },
  26. enumerable: true,
  27. configurable: true
  28. });
  29. Object.defineProperty(Maybe.prototype, "isSomething", {
  30. get: function () {
  31. return !nullOrUndef(this.t);
  32. },
  33. enumerable: true,
  34. configurable: true
  35. });
  36. Maybe.prototype.catch = function (def) {
  37. if (this.isNothing) {
  38. return def();
  39. }
  40. return this;
  41. };
  42. Maybe.prototype.unwrap = function () {
  43. return this.t;
  44. };
  45. Maybe.nothing = new Maybe(undefined);
  46. return Maybe;
  47. }());
  48. exports.Maybe = Maybe;
  49. function unwrapFirst(ts) {
  50. var f = ts.find(function (t) { return t.isSomething; });
  51. if (f) {
  52. return f.unwrap();
  53. }
  54. return undefined;
  55. }
  56. exports.unwrapFirst = unwrapFirst;
  57. function all() {
  58. var preds = [];
  59. for (var _i = 0; _i < arguments.length; _i++) {
  60. preds[_i] = arguments[_i];
  61. }
  62. return function (t) { return !preds.find(function (p) { return !p(t); }); };
  63. }
  64. exports.all = all;
  65. function any() {
  66. var preds = [];
  67. for (var _i = 0; _i < arguments.length; _i++) {
  68. preds[_i] = arguments[_i];
  69. }
  70. return function (t) { return !!preds.find(function (p) { return p(t); }); };
  71. }
  72. exports.any = any;
  73. function ifTrue(pred) {
  74. return function (t) { return (pred(t) ? Maybe.lift(t) : Maybe.nothing); };
  75. }
  76. exports.ifTrue = ifTrue;
  77. function listToMaybe(ms) {
  78. var unWrapped = (ms || []).filter(function (m) { return m.isSomething; }).map(function (m) { return m.unwrap(); });
  79. return unWrapped.length === 0 ? Maybe.nothing : Maybe.lift(unWrapped);
  80. }
  81. exports.listToMaybe = listToMaybe;