Reputation: 6107
Based on some answers on Stack Overflow, I tried to create an "extension" of List for mapIndexed, that is, a map function which also passes index. This is what I got:
mixin MapIndexed on List {
Iterable<U> mapIndexed<T, U>(U Function(T e, int i) f) {
int i = 0;
return map<U>((it) { final t = i; i++; return f(it, t); });
}
}
The problem is, I don't know how to call this. I created this based on the iOS Swift's extension concept. Ultimately, I just want that I can call result = myList.mapIndexed((element, index) => doMapping);
. How can I do this correctly? The way it is right now, the closest I can do to achieve this is by function:
Iterable<U> mapIndexed<T, U>(List<T> list, U Function(T e, int i) f) {
int i = 0;
return list.map<U>((it) { final t = i; i++; return f(it, t); });
}
result = mapIndexed(list, (element, index) => doMapping);
Upvotes: 0
Views: 334
Reputation: 24740
try the following:
extension MapIndexed on Iterable {
Iterable<U> mapIndexed<T, U>(U Function(T e, int i) f) {
int i = 0;
return map<U>((it) { final t = i; i++; return f(it, t); });
}
}
with that you could test it by:
print([1,3,5].mapIndexed((value, index) => index * 10 + value));
you should see the output:
(1, 13, 25)
Upvotes: 2