-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4-result.js
80 lines (64 loc) · 1.46 KB
/
4-result.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict';
class Sum {
static create(shape) {
const keys = Object.keys(shape);
if (keys.length !== 1) {
throw new Error('Sum.create expects a single root tag');
}
const tag = keys[0];
const variants = shape[tag];
const names = Object.keys(variants);
return class Struct {
static tag = tag;
static variants = names;
constructor(...args) {
return Struct.create(...args);
}
static create(value) {
for (let i = 0; i < names.length; i++) {
const variant = names[i];
const VariantClass = variants[variant];
if (VariantClass.is(value)) {
return new VariantClass(value);
}
}
throw new Error('No matching variant for value');
}
};
}
}
class Value {
#value = null;
constructor(value) {
this.#value = value;
}
get value() {
return this.#value;
}
static is(value) {
return !(value instanceof Error);
}
}
class Failure {
#error = null;
constructor(error) {
this.#error = error;
}
get error() {
return this.#error;
}
static is(error) {
return error instanceof Error;
}
}
// Usage
const Result = Sum.create({
Result: {
value: Value,
error: Failure,
},
});
const success = Result.create('Successfully received data');
const failure = Result.create(new Error('Network error'));
console.log('Success:', success.value);
console.log('Failure:', failure.error.message);