Last active
February 15, 2021 21:23
-
-
Save chodorowicz/1a77655681a3f67ea36de974a1357882 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
/** | |
* 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 function toggleItemInArray(collection, item) { | |
const index = indexOf(collection, item); | |
if (index !== -1) { | |
return without(collection, item); | |
} | |
return [...collection, item]; | |
} | |
// tests | |
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
// lodash xor | |
_.xor([1], [2]); // = [1, 2] | |
_.xor([1, 2], [2]); // = [1] |
Martian2Lee
commented
Jul 5, 2018
Oh yeah, _.xor
seems like a much better option 😃
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment