nc-photos/app/lib/list_util.dart

72 lines
2.2 KiB
Dart
Raw Normal View History

2022-01-25 11:08:13 +01:00
import 'package:nc_photos/iterator_extension.dart';
2023-02-14 16:40:30 +01:00
/// Contain results from the diff functions
///
/// [onlyInA] contains items exist in a but not b, [onlyInB] contains items
/// exist in b but not a
class DiffResult<T> {
const DiffResult({
required this.onlyInA,
required this.onlyInB,
});
final List<T> onlyInB;
final List<T> onlyInA;
}
2022-01-25 11:08:13 +01:00
/// Return the difference between two sorted lists, [a] and [b]
///
/// [a] and [b] MUST be sorted in ascending order, otherwise the result is
2023-02-14 16:40:30 +01:00
/// undefined
DiffResult<T> diffWith<T>(
Iterable<T> a, Iterable<T> b, int Function(T a, T b) comparator) {
2022-01-25 11:08:13 +01:00
final aIt = a.iterator, bIt = b.iterator;
final aMissing = <T>[], bMissing = <T>[];
while (true) {
if (!aIt.moveNext()) {
// no more elements in a
bIt.iterate((obj) => aMissing.add(obj));
2023-02-14 16:40:30 +01:00
return DiffResult(onlyInB: aMissing, onlyInA: bMissing);
2022-01-25 11:08:13 +01:00
}
if (!bIt.moveNext()) {
// no more elements in b
// needed because aIt has already advanced
bMissing.add(aIt.current);
aIt.iterate((obj) => bMissing.add(obj));
2023-02-14 16:40:30 +01:00
return DiffResult(onlyInB: aMissing, onlyInA: bMissing);
2022-01-25 11:08:13 +01:00
}
final result = _diffUntilEqual(aIt, bIt, comparator);
2023-02-14 16:40:30 +01:00
aMissing.addAll(result.onlyInB);
bMissing.addAll(result.onlyInA);
2022-01-25 11:08:13 +01:00
}
}
2023-02-14 16:40:30 +01:00
DiffResult<T> diff<T extends Comparable>(Iterable<T> a, Iterable<T> b) =>
2022-01-25 11:08:13 +01:00
diffWith(a, b, Comparable.compare);
2023-02-14 16:40:30 +01:00
DiffResult<T> _diffUntilEqual<T>(
2022-01-25 11:08:13 +01:00
Iterator<T> aIt, Iterator<T> bIt, int Function(T a, T b) comparator) {
final a = aIt.current, b = bIt.current;
final diff = comparator(a, b);
if (diff < 0) {
// a < b
if (!aIt.moveNext()) {
2023-02-14 16:40:30 +01:00
return DiffResult(onlyInB: [b] + bIt.toList(), onlyInA: [a]);
2022-01-25 11:08:13 +01:00
} else {
final result = _diffUntilEqual(aIt, bIt, comparator);
2023-02-14 16:40:30 +01:00
return DiffResult(onlyInB: result.onlyInB, onlyInA: [a] + result.onlyInA);
2022-01-25 11:08:13 +01:00
}
} else if (diff > 0) {
// a > b
if (!bIt.moveNext()) {
2023-02-14 16:40:30 +01:00
return DiffResult(onlyInB: [b], onlyInA: [a] + aIt.toList());
2022-01-25 11:08:13 +01:00
} else {
final result = _diffUntilEqual(aIt, bIt, comparator);
2023-02-14 16:40:30 +01:00
return DiffResult(onlyInB: [b] + result.onlyInB, onlyInA: result.onlyInA);
2022-01-25 11:08:13 +01:00
}
} else {
// a == b
2023-02-14 16:40:30 +01:00
return const DiffResult(onlyInB: [], onlyInA: []);
2022-01-25 11:08:13 +01:00
}
}