associateBy<K> method

Map<K, E> associateBy<K>(
  1. K keySelector(
    1. int index,
    2. E element
    )
)

Returns a Map containing the elements from the collection indexed by the key returned from keySelector function applied to each element.

If any two elements would have the same key returned by keySelector the last one gets added to the map.

Implementation

Map<K, E> associateBy<K>(K Function(int index, E element) keySelector) {
  final map = <K, E>{};
  final it = iterator;

  for (var i = 0; it.moveNext(); i++) {
    final key = keySelector(i, it.current);
    map[key] = it.current;
  }

  return map;
}