index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. exports.none = Object.create({
  2. value: function() {
  3. throw new Error('Called value on none');
  4. },
  5. isNone: function() {
  6. return true;
  7. },
  8. isSome: function() {
  9. return false;
  10. },
  11. map: function() {
  12. return exports.none;
  13. },
  14. flatMap: function() {
  15. return exports.none;
  16. },
  17. filter: function() {
  18. return exports.none;
  19. },
  20. toArray: function() {
  21. return [];
  22. },
  23. orElse: callOrReturn,
  24. valueOrElse: callOrReturn
  25. });
  26. function callOrReturn(value) {
  27. if (typeof(value) == "function") {
  28. return value();
  29. } else {
  30. return value;
  31. }
  32. }
  33. exports.some = function(value) {
  34. return new Some(value);
  35. };
  36. var Some = function(value) {
  37. this._value = value;
  38. };
  39. Some.prototype.value = function() {
  40. return this._value;
  41. };
  42. Some.prototype.isNone = function() {
  43. return false;
  44. };
  45. Some.prototype.isSome = function() {
  46. return true;
  47. };
  48. Some.prototype.map = function(func) {
  49. return new Some(func(this._value));
  50. };
  51. Some.prototype.flatMap = function(func) {
  52. return func(this._value);
  53. };
  54. Some.prototype.filter = function(predicate) {
  55. return predicate(this._value) ? this : exports.none;
  56. };
  57. Some.prototype.toArray = function() {
  58. return [this._value];
  59. };
  60. Some.prototype.orElse = function(value) {
  61. return this;
  62. };
  63. Some.prototype.valueOrElse = function(value) {
  64. return this._value;
  65. };
  66. exports.isOption = function(value) {
  67. return value === exports.none || value instanceof Some;
  68. };
  69. exports.fromNullable = function(value) {
  70. if (value == null) {
  71. return exports.none;
  72. }
  73. return new Some(value);
  74. }