updateById method
Returns a new list where newItems are added or updated, by their id
(and the id is a function of the item), like so:
- Items with the same
idwill be replaced, in place. - Items with new
ids will be added to the end of the list.
Note: If the original iterable contains more than one item with the
same id as some item in newItems, the first will be replaced, and
the others will be left untouched. If newItems contains more than
one item with the same id, the last one will be used, and the
previous discarded.
Implementation
List<T> updateById(
Iterable<T> newItems,
dynamic Function(T item) id,
) {
final List<T> newList = [];
final Map<dynamic, T> idsPerNewItem = <dynamic, T>{
for (final T item in newItems) id(item): item
};
// Replace those with the same id.
for (final T item in this) {
final itemId = id(item);
if (idsPerNewItem.containsKey(itemId)) {
final T newItem = idsPerNewItem[itemId] as T;
newList.add(newItem);
idsPerNewItem.remove(itemId);
} else
newList.add(item);
}
// Add the new ones at the end.
newList.addAll(idsPerNewItem.values);
return newList;
}