Reputation: 5496
I need to slice a Map. I've got it to work like this:
Map sliceMap(Map map, offset, limit) {
Map result = new Map();
if (map.length < limit) {
limit = map.length;
}
map.keys.toList().getRange(offset, limit).forEach((key) {
result[key] = map[key];
});
return result;
}
Is there a more efficient way and/or a built-in way? I couldn't find any in the API (https://api.dartlang.org/stable/1.21.0/dart-core/Map-class.html).
From aelayeb solution:
Map sliceMap(Map map, offset, limit) {
return new Map.fromIterables(
map.keys.skip(offset).take(limit - offset),
map.values.skip(offset).take(limit - offset)
);
}
Upvotes: 2
Views: 1361
Reputation: 76303
You can use :
Map sliceMap(Map map, offset, limit) {
return new Map.fromIterable(map.keys.skip(offset).take(limit),
value: (k) => map[k]);
}
Upvotes: 2
Reputation: 1258
Here is my approach for what is worth :
new Map.fromIterables(
map.keys.skip(offset).take(limit),
map.values.skip(offset).take(limit)
);
With this you don't have to make the limit test.
Upvotes: 4