diff options
author | uvok | 2025-08-02 13:53:03 +0200 |
---|---|---|
committer | uvok | 2025-08-02 13:53:03 +0200 |
commit | 282884ee86dc3d1d68e9636e3739cbedf639edef (patch) | |
tree | 6446b295e09336dd7073533fecf4586b52eb4237 | |
parent | 374144259a2e9dfa9ce83cfea6b7bd3a9e74d45e (diff) |
Add several list extensions for add/replace
-rw-r--r-- | lib/extensions/list_ext.dart | 35 |
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; } } |