Skip to content

Instantly share code, notes, and snippets.

@hasnat
Forked from chodorowicz/toggle.js
Last active August 15, 2017 12:39
Show Gist options
  • Save hasnat/919da6daddc942a8bc2c980b9db70e4c to your computer and use it in GitHub Desktop.
Save hasnat/919da6daddc942a8bc2c980b9db70e4c to your computer and use it in GitHub Desktop.
lodash toggle array element
import toggleItemInArray from '../toggleItemInArray';
it('toggles item properly', () => {
expect(toggleItemInArray([], 'a')).toEqual(['a']);
expect(toggleItemInArray(['a', 'b'], 'a')).toEqual(['b']);
});
/**
* descructive
* https://github.com/lodash/lodash/issues/1677
*/
function toggle(collection, item) {
var idx = _.indexOf(collection, item);
if(idx !== -1) {
collection.splice(idx, 1);
} else {
collection.push(item);
}
}
// es6 version
import { indexOf, without } from 'lodash';
export default (collection, item) =>
indexOf(collection, item) !== -1 ? without(collection, item) : [...collection, item];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment