-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpipe.spec.ts
106 lines (88 loc) · 2.85 KB
/
pipe.spec.ts
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { Result, ResultOpFn, ResultOpFnAsync } from '@/src/result';
import { ResultAsync, ResultAsyncOpFn } from '@/src/resultAsync';
import { ActionOfT, FunctionOfTtoK, isPromise, Some } from '@/src/utilities';
describe('Result', () => {
describe('pipe', () => {
test('executes all operator functions', () => {
const sut = Result.success(1);
const result = sut.pipe(
map((n) => n + 1),
map((n) => n * 2),
map((n) => `Calculation: ${n}`)
);
expect(sut).toSucceedWith(1);
expect(result).toSucceedWith('Calculation: 4');
});
test('handles side-effect operator functions', () => {
let callCount = 0;
const sut = Result.success(1);
const result = sut.pipe(
tap((n) => callCount++),
tap((n) => callCount++),
tap((n) => callCount++),
tap((n) => callCount++)
);
expect(result).toSucceedWith(1);
expect(callCount).toBe(4);
});
test('handles transitioning to a ResultAsync', async () => {
const sut = Result.success(1);
const result = await sut
.pipe(
map((n) => n + 1),
mapAsync((n) => Promise.resolve(n * 2))
)
.pipe(asyncMap((n) => n + 3))
.toPromise();
expect(result).toSucceedWith(7);
});
});
});
function map<TValue, TError, TNewValue>(
projection: FunctionOfTtoK<TValue, Some<TNewValue>>
): ResultOpFn<TValue, TError, TNewValue, TError> {
return (result) => {
return result.isSuccess
? Result.success(projection(result.getValueOrThrow()))
: Result.failure(result.getErrorOrThrow());
};
}
function tap<TValue, TError>(
action: ActionOfT<TValue>
): ResultOpFn<TValue, TError, TValue, TError> {
return (result) => {
if (result.isSuccess) {
action(result.getValueOrThrow());
}
return result;
};
}
function mapAsync<TValue, TError, TNewValue>(
projection: FunctionOfTtoK<TValue, Promise<Some<TNewValue>>>
): ResultOpFnAsync<TValue, TError, TNewValue, TError> {
return (result) => {
return result.isSuccess
? ResultAsync.from(projection(result.getValueOrThrow()))
: ResultAsync.failure(result.getErrorOrThrow());
};
}
function asyncMap<TValue, TError, TNewValue>(
projection:
| FunctionOfTtoK<TValue, Promise<Some<TNewValue>>>
| FunctionOfTtoK<TValue, Some<TNewValue>>
): ResultAsyncOpFn<TValue, TError, TNewValue, TError> {
return (result) => {
return ResultAsync.from<TNewValue, TError>(
result.toPromise().then(async (r) => {
if (r.isFailure) {
return Result.failure<TNewValue, TError>(r.getErrorOrThrow());
}
const result = projection(r.getValueOrThrow());
if (isPromise(result)) {
return result.then((r) => Result.success<TNewValue, TError>(r));
}
return Result.success<TNewValue, TError>(result);
})
);
};
}