Created
March 14, 2016 00:43
-
-
Save gordonkristan/44de1637a67578bb9097 to your computer and use it in GitHub Desktop.
Functions as sets in Javavscript
This file contains hidden or 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
const emptySet = () => false; | |
const addElement = (set, element) => { | |
return (item) => (item === element ? true : set(item)); | |
}; | |
const removeElement = (set, element) => { | |
return (item) => (item === element ? false : set(item)); | |
}; | |
// Create a set containing 1,2,3 | |
let mySet = emptySet; | |
mySet = addElement(mySet, 1); | |
mySet = addElement(mySet, 2); | |
mySet = addElement(mySet, 3); | |
// Test for presence of 3 and 4 | |
console.log(mySet(3)); // true | |
console.log(mySet(4)); // false | |
// Remove 1 from set | |
mySet = removeElement(mySet, 1); | |
console.log(mySet(1)); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment