Skip to content

toggle_by

Like toggle, but elements are the same when key gives the same value: toggle objects by id instead of by whole-value equality. Only the first match is removed.

use helpers4::array::toggle_by;

Cargo feature array (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features array

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.9", default-features = false, features = ["array"] }
pub fn toggle_by<T: Clone, K: PartialEq>(
    items: &[T],
    item: T,
    mut key: impl FnMut(&T) -> K,
) -> Vec<T>
ParameterTypeDescription
items&[T]The current elements.
itemTThe element to add, or whose key to remove.
keyimpl FnMut(&T) -> KReturns the identity to compare.

Vec<T> — A new Vec; items is not changed.

use helpers4::array::toggle_by;

let layers = [("a", 1), ("b", 2)];
// Same id: removed, whatever the other fields hold.
assert_eq!(toggle_by(&layers, ("x", 1), |layer| layer.1), vec![("b", 2)]);
assert_eq!(toggle_by(&layers, ("c", 3), |layer| layer.1), vec![("a", 1), ("b", 2), ("c", 3)]);

src/array/toggle_by.rs