Skip to content

toggle

Toggles an item's existence in an array

254 bytes

Usage

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

import * as _ from 'radashi'
const gods = ['ra', 'zeus', 'loki']
_.toggle(gods, 'ra') // => ['zeus', 'loki']
_.toggle(gods, 'vishnu') // => ['ra', 'zeus', 'loki', 'vishnu']

toggle(list, item, toKey)

You can pass an optional toKey function to determine the identity of non-primitive values. Helpful when working with more complex data types.

import * as _ from 'radashi'
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]

toggle(list, item, toKey, options)

By default, toggle will append the item if it does not exist. If you need to prepend the item instead you can override the strategy in the options argument.

import * as _ from 'radashi'
const gods = ['ra', 'zeus', 'loki']
_.toggle(gods, 'vishnu', g => g, { strategy: 'prepend' }) // => ['vishnu', 'ra', 'zeus', 'loki']