parsing-results.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. module.exports = {
  2. failure: function(errors, remaining) {
  3. if (errors.length < 1) {
  4. throw new Error("Failure must have errors");
  5. }
  6. return new Result({
  7. status: "failure",
  8. remaining: remaining,
  9. errors: errors
  10. });
  11. },
  12. error: function(errors, remaining) {
  13. if (errors.length < 1) {
  14. throw new Error("Failure must have errors");
  15. }
  16. return new Result({
  17. status: "error",
  18. remaining: remaining,
  19. errors: errors
  20. });
  21. },
  22. success: function(value, remaining, source) {
  23. return new Result({
  24. status: "success",
  25. value: value,
  26. source: source,
  27. remaining: remaining,
  28. errors: []
  29. });
  30. },
  31. cut: function(remaining) {
  32. return new Result({
  33. status: "cut",
  34. remaining: remaining,
  35. errors: []
  36. });
  37. }
  38. };
  39. var Result = function(options) {
  40. this._value = options.value;
  41. this._status = options.status;
  42. this._hasValue = options.value !== undefined;
  43. this._remaining = options.remaining;
  44. this._source = options.source;
  45. this._errors = options.errors;
  46. };
  47. Result.prototype.map = function(func) {
  48. if (this._hasValue) {
  49. return new Result({
  50. value: func(this._value, this._source),
  51. status: this._status,
  52. remaining: this._remaining,
  53. source: this._source,
  54. errors: this._errors
  55. });
  56. } else {
  57. return this;
  58. }
  59. };
  60. Result.prototype.changeRemaining = function(remaining) {
  61. return new Result({
  62. value: this._value,
  63. status: this._status,
  64. remaining: remaining,
  65. source: this._source,
  66. errors: this._errors
  67. });
  68. };
  69. Result.prototype.isSuccess = function() {
  70. return this._status === "success" || this._status === "cut";
  71. };
  72. Result.prototype.isFailure = function() {
  73. return this._status === "failure";
  74. };
  75. Result.prototype.isError = function() {
  76. return this._status === "error";
  77. };
  78. Result.prototype.isCut = function() {
  79. return this._status === "cut";
  80. };
  81. Result.prototype.value = function() {
  82. return this._value;
  83. };
  84. Result.prototype.remaining = function() {
  85. return this._remaining;
  86. };
  87. Result.prototype.source = function() {
  88. return this._source;
  89. };
  90. Result.prototype.errors = function() {
  91. return this._errors;
  92. };