What is the best way to toggle an item in an array using TypeScript.
With toggle I mean:
- If present, remove the value.
- If not present, add the value.
Solution with least amount of computational effort preferred.
Below is a generic typesafe method that "toggles" a value in an array. Note that the method returns a new array, and doesn't mutate the original one.
const toggle = <T extends unknown>(array: Array<T>, value: T) => {
const newArray = array.filter((x) => x !== value)
if (newArray.length === array.length) return array.concat(value)
return newArray
}