Last active
July 29, 2022 09:25
-
-
Save nosmirck/3b18e0a8d0d5658b7da409dca889babf to your computer and use it in GitHub Desktop.
Async where and examples for List<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main(List<String> arguments) async { | |
var list = List.generate(10, (i) => i)..addAll(List.generate(10, (i) => i)); | |
//Normal Where | |
print(list.where(foo).toList()); | |
//Async Where | |
print((await list.whereAsync(fooAsync)).toList()); | |
//Normal UniqueWhere | |
print(list.uniqueWhere(foo).toList()); | |
//Async UniqueWhere | |
print((await list.uniqueWhereAsync(fooAsync)).toList()); | |
} | |
bool foo(int n) { | |
return n > 5; | |
} | |
Future<bool> fooAsync(int n) async { | |
await Future.delayed(Duration(seconds: 1)); | |
return foo(n); | |
} | |
extension MyIterable<T> on Iterable<T> { | |
Future<Iterable<T>> whereAsync(Future<bool> Function(T) test) async { | |
return (await Future.wait( | |
map((e) async { | |
return [await test(e), e]; | |
}), | |
)) | |
.where((t) => t.first) | |
.map((t) => t.last); | |
} | |
Iterable<T> uniqueWhere(bool Function(T) test) { | |
return Set.from(where(test)); | |
} | |
Future<Iterable<T>> uniqueWhereAsync(Future<bool> Function(T) test) async { | |
return Set.from(await whereAsync(test)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment