From 282884ee86dc3d1d68e9636e3739cbedf639edef Mon Sep 17 00:00:00 2001 From: uvok Date: Sat, 2 Aug 2025 13:53:03 +0200 Subject: Add several list extensions for add/replace --- lib/extensions/list_ext.dart | 35 ++++++++++++++++++++++++++++++----- 1 file 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 . extension ListExt on List { - /// 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( + 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; } } -- cgit v1.2.3