-
-
Save NearHuscarl/86ce74d95798635e14c8b848863b429f to your computer and use it in GitHub Desktop.
54898767/enumerate-or-map-through-a-list-with-index-and-value-in-dart
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
// https://gist.github.com/NearHuscarl/86ce74d95798635e14c8b848863b429f | |
extension ExtendedIterable<E> on Iterable<E> { | |
/// Like Iterable<T>.map but callback have index as second argument | |
Iterable<T> mapIndexed<T>(T Function(E e, int i) f) { | |
var i = 0; | |
return map((e) => f(e, i++)); | |
} | |
void forEachIndexed(void Function(E e, int i) f) { | |
var i = 0; | |
forEach((e) => f(e, i++)); | |
} | |
} | |
void main() { | |
final inputs = ['a', 'b', 'c', 'd', 'e', 'f']; | |
final results = inputs | |
.mapIndexed((e, i) => 'item: $e, index: $i') | |
.toList() | |
.join('\n'); | |
print('mapIndexed'); | |
print(results); | |
print(''); | |
print('forEachIndexed'); | |
inputs.forEachIndexed((e, i) => print('item: $e, index: $i')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment