summaryrefslogtreecommitdiff
path: root/lib/extensions/list_ext.dart
diff options
context:
space:
mode:
Diffstat (limited to 'lib/extensions/list_ext.dart')
-rw-r--r--lib/extensions/list_ext.dart35
1 files changed, 30 insertions, 5 deletions
diff --git a/lib/extensions/list_ext.dart b/lib/extensions/list_ext.dart
index 8ef2713..dfd27ed 100644
--- a/lib/extensions/list_ext.dart
+++ b/lib/extensions/list_ext.dart
@@ -14,16 +14,41 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
extension ListExt<T> on List<T> {
- /// If predicate is true for any element on the list, replace first element on that position.
- /// Otherwise, add element.
- void addOrReplaceWhere(T dev, bool Function(T exDev) predicate) {
+ /// Similar to addOrReplaceWhere, but simply use a given keySelector do check equality.
+ void addOrReplaceKey<K extends Comparable>(
+ T dev, {
+ required K Function(T item) keySelector,
+ bool Function(T existing)? replaceCondition,
+ }) {
+ final devKey = keySelector(dev);
+ final idx = indexWhere((item) => keySelector(item) == devKey);
+
+ if (idx == -1) {
+ add(dev);
+ } else {
+ final bool shouldReplace = replaceCondition?.call(this[idx]) ?? true;
+ if (shouldReplace) this[idx] = dev;
+ }
+ }
+
+ /// If predicate(1) is false for all elements in the list, add the element.
+ /// Otherwise, the first element that matches this(1) predicate might be replaced.
+ /// For this, check replaceCondition(2).
+ /// If (2) is omitted, the element is always replaced.
+ /// If (2) is given, it's passed the matching element.
+ /// The predicate(2) determines whether to replace the element.
+ void addOrReplaceWhere(
+ T dev,
+ bool Function(T exDev) predicate, {
+ bool Function(T exDev)? replaceCondition,
+ }) {
int idx = indexWhere(predicate);
if (idx == -1) {
add(dev);
} else {
- removeAt(idx);
- insert(idx, dev);
+ final bool shouldReplace = replaceCondition?.call(this[idx]) ?? true;
+ if (shouldReplace) this[idx] = dev;
}
}