Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript Iterators: Sets and Maps
/* JavaScript Iterators
Sets and Maps
Sets and Maps can be made Iterable/Iterator by using the methods .entries(), .keys(),
values(), and/or via for of construct.
A Set is a unique (non repeated) version of a Bag data structure. Characteristic equation
is contains() or has().
A Map (in JS) is a key-value pair data structure, unordered (in order of insertion).
In ES6 (and beyond) we tend to use Maps instead of Objects for iteration, because the Object
prototype chain can be problematic for iteration.
Map keys can be any data type (objects, functions, primitives); Object keys can only be
Strings/Symbols. Maps also have better performance for frequent insertions and deletions
according to MDN, but the MDN article does not specify whether Maps are more performant
temporally or for memory.
Sources:
1 - Data structures and algorithms at Princeton and MIT open courseware
2 - Axel Rauschmeyer: http://exploringjs.com/es6/ch_iteration.html
3 - http://www.zsoltnagy.eu/es6-iterators-and-generators-in-practice/
4 - MDN on Maps: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
*/
// Code done on node REPL instead of WebpackBin
// Set
const jazzCats = new Set( [ 'paul chambers', 'monk', 'coltrane' ] )
> jazzCats
Set { 'paul chambers', 'monk', 'coltrane' }
// Sets.entries() makes iterable. Obviously .keys() and .values() would produce identical results.
> jazzCats.entries()
SetIterator {
[ 'paul chambers', 'paul chambers' ],
[ 'monk', 'monk' ],
[ 'coltrane', 'coltrane' ] }
// Map
const artists = new Map( [[ 'jazz', 'coltrane'], ['funk', 'curtis mayfield' ]] )
> artists
Map { 'jazz' => 'coltrane', 'funk' => 'curtis mayfield' }
> artists.entries()
MapIterator { [ 'jazz', 'coltrane' ], [ 'funk', 'curtis mayfield' ] }
> artists.keys()
MapIterator { 'jazz', 'funk' }
> artists.values()
MapIterator { 'coltrane', 'curtis mayfield' }
@abstractmachines

This comment has been minimized.

Owner

abstractmachines commented Nov 2, 2017

For of on Maps (and Sets)

Iterating through entire key-value collection with for of

> for ( let pair of artists) { console.log(pair) }

[ 'jazz', 'coltrane' ]
[ 'funk', 'curtis mayfield' ]

Same thing, with specifying key and value for each element

> for ( let [key, value] of artists ) { console.log(key, value) }

jazz coltrane
funk curtis mayfield 

Conversions

You can convert a Set to an Array with the Spread Operator : let anArray = [...aSet]

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