Created
July 30, 2014 07:04
-
-
Save khamiltonuk/3d58ac8039cb1b5e3741 to your computer and use it in GitHub Desktop.
Lists of Unique Values - Using ES6 Sets in JavaScript
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
| /* | |
| ** Pushing values to an array | |
| */ | |
| var heroCallList = [ ]; | |
| heroCallList.push("Robin"); | |
| heroCallList.push("Batgirl"); | |
| heroCallList.push("Nightwing"); | |
| console.log(heroCallList); | |
| // => ["Robin", "Batgirl", "Nightwing"] | |
| // Limitations: prone to duplication | |
| /* | |
| ** Checking if value exsists before pushing values to an array | |
| */ | |
| var heroCallList = [ ]; | |
| function addToCallList(hero){ | |
| var exists = false; | |
| for(var i = 0; i < heroCallList.length && !exists; i++){ | |
| exists = heroCallList[i] === hero; | |
| } | |
| if (!exists){ | |
| heroCallList.push(hero); | |
| } | |
| } | |
| addToCallList("Robin"); | |
| addToCallList("Batgirl"); | |
| addToCallList("Superman"); | |
| addToCallList("Batgirl"); | |
| console.log(heroCallList); | |
| // = > ["Robin", "Batgirl", "Superman"] | |
| // Limitations: With each add has to search the entire array, slow at scale | |
| /* | |
| ** Storying values in an object | |
| */ | |
| var heroCallList = Object.create(null); | |
| function addToCallList(hero){ | |
| heroCallList[hero] = true; | |
| } | |
| addToCallList("Robin"); | |
| addToCallList("Batgirl"); | |
| addToCallList("Superman"); | |
| addToCallList("Batgirl"); | |
| console.log(heroCallList); | |
| // => Object {Robin: true, Batgirl: true, Superman: true}; | |
| // Limitations: unintuitive, can't reliably keep a list of anything but strings. | |
| /* | |
| ** Storying values in ES6 set | |
| */ | |
| var heroCallList = new Set(); | |
| heroCallList.add("Robin"); | |
| heroCallList.add("Batgirl"); | |
| heroCallList.add("Superman"); | |
| heroCallList.add("Batgirl"); | |
| console.log(heroCallList); | |
| // => Set [ "Robin", "Batgirl", "Superman" ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment