Skip to content

Instantly share code, notes, and snippets.

@aeinbu
Last active July 26, 2017 08:24
Show Gist options
  • Save aeinbu/8cea7a926beecb0bf3c43043f16877a9 to your computer and use it in GitHub Desktop.
Save aeinbu/8cea7a926beecb0bf3c43043f16877a9 to your computer and use it in GitHub Desktop.
// traditional version
function toggleValueInArray1(val, arr) {
var ix = arr.indexOf(val);
if(ix === -1){
// add to array
arr.push(val);
}
else
{
// remove from array
arr.splice(ix, 1);
}
}
// functional version
let toggleValueInArray2 = arr => val => {
var ix = arr.indexOf(val);
if(ix === -1){
// add to array
arr.push(val);
}
else
{
// remove from array
arr.splice(ix, 1);
}
}
@aeinbu
Copy link
Author

aeinbu commented Aug 3, 2016

Usage of the traditional version

var arr = ["socks", "pants"];
toggleValueInArray1("socks", arr);
toggleValueInArray1("shirt", arr);

// arr is now ["pants", "shirt"]

Usage of the fp version

let arr = ["socks", "pants"];
let toggler = toggleValueInArray2(arr);
toggler("socks");
toggler("shirt");

// arr is now ["pants", "shirt"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment