Function toggle

use xor instead

If the item matching the condition already exists in the list it will be removed. If it does not it will be added.

const gods = ['ra', 'zeus', 'loki']

toggle(gods, 'ra') // => [zeus, loki]
toggle(gods, 'vishnu') // => [ra, zeus, loki, vishnu]

const ra = { name: 'Ra' }
const zeus = { name: 'Zeus' }
const loki = { name: 'Loki' }
const vishnu = { name: 'Vishnu' }

const gods = [ra, zeus, loki]

toggle(gods, ra, g => g.name) // => [zeus, loki]
toggle(gods, vishnu, g => g.name) // => [ra, zeus, loki, vishnu]

const gods = ['ra', 'zeus', 'loki']

toggle(gods, 'vishnu', g => g, { strategy: 'prepend' }) // => [vishnu, ra, zeus, loki]

toggle(gods, ['vishnu', 'ra']) // => [vishnu, zeus, loki]
  • Type Parameters

    • T

    Parameters

    • list: readonly T[]
    • items: T | readonly T[]
    • OptionaltoKey: null | ((item: T, idx: number) => string | number | symbol)

      Converts an item of type T item into a value that can be checked for equality

    • Optionaloptions: {
          strategy?: "prepend" | "append";
      }
      • Optionalstrategy?: "prepend" | "append"

    Returns T[]