Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

Add .toMap extensions for tuples/pairs and key+value records #359

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions lib/src/iterable_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -914,6 +914,18 @@ extension IterableIterableExtension<T> on Iterable<Iterable<T>> {
};
}

/// Extensions that apply to iterables of tuples/pairs (records with two unnamed elements).
extension IterableTupleExtension<T1, T2> on Iterable<(T1, T2)> {
Copy link
Contributor

@lrhn lrhn Sep 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not keen on just using a positional pair as the representation of a key/value pair.
I'd use a type like ({T1 key, T2 value}) instead. I can see that there is a version below that does that, so I would just drop this one.

It does get a little more verbose if you don't want to use key and value as the names for the key and value.
And if you do have a list of pairs, then having to do .map((p) => (key: p.$1, value: p.$2)) does feel unnecessary.

(Maps are not sets of pairs. Now that we have records, Set<(...,...)>s are sets of pairs!)

/// Returns a map from the first element of each tuple to the second element.
Map<T1, T2> get toMap => {for (final element in this) element.$1: element.$2};
Copy link
Contributor

@lrhn lrhn Sep 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Just as style comments, not endorsing the functionality:
toX functionality like toMap() is usually a method, not a getter.
The for loop can destructure: {for (var (key, value) in this) key: value}.
This package doesn't use final for local variables.
I'd use "Creates" instead of "Returns" in the comment. Never start a DocComment with "Returns".)

}

extension IterableKeyValueExtension<T1, T2> on Iterable<({T1 key, T2 value})> {
/// Returns a map from the key of each element to the value of that element.
Map<T1, T2> get toMap =>
{for (final element in this) element.key: element.value};
}

/// Extensions that apply to iterables of [Comparable] elements.
///
/// These operations can assume that the elements have a natural ordering,
Expand Down