sdk
sdk copied to clipboard
Request to add toggle method to Set class
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);
}
}
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.