-
Notifications
You must be signed in to change notification settings - Fork 7
/
either_test.dart
58 lines (47 loc) · 1.7 KB
/
either_test.dart
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
import 'package:either_option/src/either.dart';
import 'package:test/test.dart';
void main() {
final message = "Invalid operation";
Either<String, double> safeDivision(int a, int b) {
if (b == 0) return Left(message);
return Right(a / b);
}
group('Test Either implementation', () {
test('Basic Either state', () {
final a = safeDivision(2, 0);
final b = safeDivision(4, 2);
expect(a.isLeft, true);
expect(b.isRight, true);
expect(a.isRight, false);
expect(b.isLeft, false);
});
test('All useful functions ', () {
final a = safeDivision(2, 0);
final b = safeDivision(4, 2);
// fold
expect(a.fold((_) => "ko", (_) => "ok"), "ko");
expect(b.fold((_) => "ko", (_) => "ok"), "ok");
// swap
expect(a.swap(), Right(message));
expect(b.swap(), Left(2));
//map on projection
double onRight(double val) => val * 3;
int onLeft(String msg) => msg.length;
expect(a.left.map(onLeft), Left(message.length));
expect(a.right.map(onRight), Left(message));
expect(b.right.map((l) => onRight(l)), Right(6));
expect(b.left.map((l) => onLeft(l)), Right(2));
// flatMap
onRigthEth(double val) => Right(val * 3);
onLeftEth(String msg) => Left(msg.length);
expect(a.left.flatMap((l) => onLeftEth(l)), Left(message.length));
expect(a.right.flatMap(onRigthEth), Left(message));
expect(b.right.flatMap((r) => onRigthEth(r)), Right(6));
expect(b.left.flatMap(onLeftEth), Right(2));
// cond
final String hello = "either_option";
final result = Either.cond(hello.length > 50, hello.length, hello);
expect(result, Left(hello));
});
});
}