-
-
Save hasnat/919da6daddc942a8bc2c980b9db70e4c to your computer and use it in GitHub Desktop.
lodash toggle array element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import toggleItemInArray from '../toggleItemInArray'; | |
it('toggles item properly', () => { | |
expect(toggleItemInArray([], 'a')).toEqual(['a']); | |
expect(toggleItemInArray(['a', 'b'], 'a')).toEqual(['b']); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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