30秒学会 Dart 片段 · 2019年5月11日

30秒学会 Dart 片段 – mapList

Maps the values of a list using a function, where the key-value pairs consist of the value as the key and the mapped value.

Use Map.fromIterable() to generate a map with the original values as keys and their mapped values as values.

代码实现

Map<T, Y> mapList<T, Y>(Iterable<T> itr, Y Function(T) fn) {
  return Map.fromIterable(itr, key: (i) => i, value: (i) => fn(i));
}

使用样例

mapList([1, 2, 3], (a) => a * a); // [{1: 1, 2: 4, 3: 9}]