简体   繁体   中英

Slice a Map in Dartlang

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)
  );
}

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.

You can use :

Map sliceMap(Map map, offset, limit) {
  return new Map.fromIterable(map.keys.skip(offset).take(limit),
      value: (k) => map[k]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM