Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

_.toggle function #1677

Closed
cojack opened this issue Dec 1, 2015 · 7 comments
Closed

_.toggle function #1677

cojack opened this issue Dec 1, 2015 · 7 comments

Comments

@cojack
Copy link

cojack commented Dec 1, 2015

Hello,
Could you implement an toggle function? By toggle I mean something like this:

    var idx = _.indexOf(collection, item);
    if(idx !== -1) {
        collection.splice(idx, 1);
    } else {
        collection.push(item);
    }

Thanks in advance.

@jdalton
Copy link
Member

jdalton commented Dec 1, 2015

Hi @cojack!

I think this is better suited as a mixin.

@steven-prybylynskyi
Copy link

Implemented nicely with _.partial

function toggler(collection, item) {
    const idx = _.indexOf(collection, item);
    if(idx !== -1) {
        collection.splice(idx, 1);
    } else {
        collection.push(item);
    }
}
 
const model = [1, 2, 3];
const toggle = _.partial(toggler, model)

toggle(1); // [2,3]
toggle(4); // [2,3,4]

@pie6k
Copy link

pie6k commented Feb 14, 2018

I find it quite common use case. Would be useful without mixins :)

@petekp
Copy link

petekp commented Mar 23, 2018

One use case a _.toggle function would be well suited for is handling state for multiple choice fields, e.g. an example in React:

handleChange = (e: Event) => {
    const [...selectedOptions] = this.state.selectedOptions

    if (selectedOptions.includes(selectedValue)) {
      selectedOptions.splice(selectedOptions.indexOf(selectedValue), 1)
    } else {
      selectedOptions.push(selectedValue)
    }

    this.setState({
      selectedOptions,
    })
  }

could be written something like

handleChange = (e: Event) => {
    const [...selectedOptions] = this.state.selectedOptions

    this.setState({
      selectedOptions: _.toggle(e.target.value, selectedOptions)),
    })
  }

@Martian2Lee
Copy link

_.xor([1], [2]);
= [1, 2]

_.xor([1, 2], [2]);
= [1]

@Jokero

This comment has been minimized.

@lock
Copy link

lock bot commented Oct 26, 2019

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@lock lock bot locked as resolved and limited conversation to collaborators Oct 26, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Development

No branches or pull requests

7 participants