-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
flattening-lists-in-dart.dart
52 lines (44 loc) · 1.12 KB
/
flattening-lists-in-dart.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
// Want to support my work 🤝? https://buymeacoffee.com/vandad
class Person {
final String name;
const Person(this.name);
@override
String toString() => 'Person: $name';
}
class House {
final List<Person>? tennants;
final List<Person> builders;
const House({
required this.tennants,
required this.builders,
});
}
const houses = [
House(tennants: null, builders: [
Person('Builder 1'),
]),
House(tennants: [
Person('Tennant 1'),
Person('Tennant 2'),
], builders: [
Person('Builder 3')
]),
];
extension OptionalFlattend<T> on Iterable<List<T>?> {
Iterable<T> flattened() => expand((e) => e ?? []);
}
void testOptionalFlatten() {
final allTennants = houses.map((h) => h.tennants).flattened();
print(allTennants); // Person: Tennant 1, Person: Tennant 2
}
extension Flattend<T> on Iterable<List<T>> {
Iterable<T> flattened() => expand((e) => e);
}
void testNonOptionalFlatten() {
final allBuilders = houses.map((h) => h.builders).flattened();
print(allBuilders); // Person: Builder 1, Person: Builder 2
}
void testIt() {
testOptionalFlatten();
testNonOptionalFlatten();
}