-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfpdart_either_fizzbuzz_sample.dart
89 lines (80 loc) · 2.16 KB
/
fpdart_either_fizzbuzz_sample.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
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
// ignore_for_file: avoid_print
import 'package:fpdart/fpdart.dart';
/// Fun Example: Functional Fizz-Buzz 😎
void main() {
final values = [
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'not-a-number',
'invalid',
];
final results = parseFizzBuzzDeclarativeWithTearOff(values).join('\n');
print(results);
parseFizzBuzzDeclarativeWithTearOff(values).forEach((result) => result.fold(
(l) => print(l),
(r) => print(r),
));
}
String fizzBuzz(double value) {
if (value % 3 == 0 && value % 5 == 0) {
// multiple of 3 and 5
return 'fizz buzz';
} else if (value % 3 == 0) {
// multiple of 3
return 'fizz';
} else if (value % 5 == 0) {
// multiple of 5
return 'buzz';
} else {
// all other numbers
return value.toString();
}
}
Either<FormatException, double> parseNumber(String value) {
return Either.tryCatch(
() => double.parse(value),
(e, _) => e as FormatException,
);
}
/// Fizzbuzz with Imperative style
Iterable<Either<FormatException, String>> parseFizzBuzzImperative(
List<String> strings) {
// all types are declared explicitly for clarity,
// but we could have used `final` instead:
List<Either<FormatException, String>> results = [];
for (String string in strings) {
// first, parse the input string
Either<FormatException, double> parsed = parseNumber(string);
// then, use map to convert valid numbers using [fizzBuzz]
Either<FormatException, String> result =
parsed.map((value) => fizzBuzz(value));
// add the value
results.add(result);
}
return results;
}
/// Fizzbuzz with declarative Functional style
Iterable<Either<FormatException, String>> parseFizzBuzzDeclarative(
List<String> strings) =>
strings.map(
(string) => parseNumber(string).map(
(value) => fizzBuzz(value),
),
);
/// Fizzbuzz with declarative Functional style with tear-off
Iterable<Either<FormatException, String>> parseFizzBuzzDeclarativeWithTearOff(
List<String> strings) =>
strings.map((string) => parseNumber(string).map(fizzBuzz));