UNPKG

2.46 kBJavaScriptView Raw
1module.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
40var Result = function(options) {
41 this._value = options.value;
42 this._status = options.status;
43 this._hasValue = options.value !== undefined;
44 this._remaining = options.remaining;
45 this._source = options.source;
46 this._errors = options.errors;
47};
48
49Result.prototype.map = function(func) {
50 if (this._hasValue) {
51 return new Result({
52 value: func(this._value, this._source),
53 status: this._status,
54 remaining: this._remaining,
55 source: this._source,
56 errors: this._errors
57 });
58 } else {
59 return this;
60 }
61};
62
63Result.prototype.changeRemaining = function(remaining) {
64 return new Result({
65 value: this._value,
66 status: this._status,
67 remaining: remaining,
68 source: this._source,
69 errors: this._errors
70 });
71};
72
73Result.prototype.isSuccess = function() {
74 return this._status === "success" || this._status === "cut";
75};
76
77Result.prototype.isFailure = function() {
78 return this._status === "failure";
79};
80
81Result.prototype.isError = function() {
82 return this._status === "error";
83};
84
85Result.prototype.isCut = function() {
86 return this._status === "cut";
87};
88
89Result.prototype.value = function() {
90 return this._value;
91};
92
93Result.prototype.remaining = function() {
94 return this._remaining;
95};
96
97Result.prototype.source = function() {
98 return this._source;
99};
100
101Result.prototype.errors = function() {
102 return this._errors;
103};