sdk icon indicating copy to clipboard operation
sdk copied to clipboard

Request to add toggle method to Set class

Open akshdeep-singh opened this issue 3 years ago • 1 comments

Request to add a toggle method to Set which does the following work:

Set<T> set = {};

void toggle(T item) {
  if (set.contains(item)) {
    set.remove(item);
  } else {
    set.add(item);
  }
}

akshdeep-singh avatar Sep 17 '22 09:09 akshdeep-singh

While probably convenient, I don't think we'll change the Set API at this point. Which means this will at most be an extension method. That sounds reasonable, and it can be added to, e.g., package:collection, as

extension SetToggle<T> on Set<T> {
  /// Toggles whether [element] is an element of this set.
  ///
  /// If [element] is not currently a member, it is added, and this method returns `true`.
  /// If [element] is currently a member, it is removed, and this method returns `false`.
  bool toggle(T element) => !remove(element) && add(element);
}

That's not as efficient as doing as single lookup, but it should be OK.

lrhn avatar Sep 17 '22 11:09 lrhn