Skip to content

Instantly share code, notes, and snippets.

@AlexVegner
Created January 24, 2020 18:27
Show Gist options
  • Save AlexVegner/cd618ab13f587ea3184380f0a80a2880 to your computer and use it in GitHub Desktop.
Save AlexVegner/cd618ab13f587ea3184380f0a80a2880 to your computer and use it in GitHub Desktop.
dart_generator.dart
import 'dart:async';
main() async {
print(naturalsTo(10).toList());
print(await asynchronousNaturalsTo(10).toList());
print(naturalsDownFrom(10).toList());
print(await periodicGenerator(10).toList());
}
Iterable<int> naturalsTo(int n) sync* {
int k = 0;
while (k < n) yield k++;
}
Stream<int> asynchronousNaturalsTo(int n) async* {
int k = 0;
while (k < n) yield k++;
}
Iterable<int> naturalsDownFrom(int n) sync* {
if (n > 0) {
yield n;
yield* naturalsDownFrom(n - 1);
}
}
Stream<int> periodicGenerator(int n) async* {
yield* Stream.periodic(Duration(seconds: 1), (value) => value).take(n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment