compare<T extends ObjectComparable> static method
Compares two lists of objects and returns the result.
The oldList
parameter represents the old list of objects.
The newList
parameter represents the new list of objects.
The fieldId
parameter represents the field used to identify objects.
Returns an instance of CompareListsOfObjectResult containing the added, removed, and updated objects.
Implementation
static CompareListsOfObjectResult<T> compare<T extends ObjectComparable>({
required List<T> oldList,
required List<T> newList,
required String fieldId,
}) {
if (fieldId.isEmpty) {
throw Exception('fieldId is required');
}
// Creates maps for quick access to items using the fieldId value as the key.
final oldMap = <dynamic, T>{};
final newMap = <dynamic, T>{};
for (final item in oldList) {
final key = item[fieldId];
oldMap[key] = item;
}
for (final item in newList) {
final key = item[fieldId];
newMap[key] = item;
}
final List<T> removedItems = [];
final List<T> updatedItems = [];
final List<T> addedItems = [];
for (final key in oldMap.keys) {
final oldItem = oldMap[key]!;
final newItem = newMap[key];
if (newItem == null) {
removedItems.add(oldItem);
} else if (oldItem != newItem) {
updatedItems.add(newItem);
}
}
for (final key in newMap.keys) {
if (!oldMap.containsKey(key)) {
addedItems.add(newMap[key]!);
}
}
return CompareListsOfObjectResult<T>(
added: addedItems,
removed: removedItems,
updated: updatedItems,
);
}