Skip to content

Instantly share code, notes, and snippets.

@channainfo
Last active November 14, 2020 04:51
Show Gist options
  • Save channainfo/5900046b26eb93da96583f569990acba to your computer and use it in GitHub Desktop.
Save channainfo/5900046b26eb93da96583f569990acba to your computer and use it in GitHub Desktop.
List map with index return List and Iterable
// lib/extensions/list_map_with_index_extension.dart
extension MapWithIndex<T> on List<T> {
List<R> mapWithIndex<R>(R Function(T, int i) callback) {
List<R> result = [];
for (int i = 0; i < this.length; i++) {
R item = callback(this[i], i);
result.add(item);
}
return result;
}
Iterable<R> mapWithIndexIterable<R>(R Function(T, int i) callback) {
return this.asMap().keys.toList().map((index) => callback(this[index], index));
}
}
@channainfo
Copy link
Author

For ease of maintenance

List<R> mapWithIndex<R>(R Function(T, int i) callback) {
    return this.asMap().keys.toList().map((index) => callback(this[index], index)).toList();
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment