Sets & Maps

What?

ES6 offers nice new features:

… but also Sets and Maps!

Sets

… aka fancier arrays!

const providers = new Set();

iterable object

providers.add('amazon');
providers.add('netflix');
providers.add('netflix');
providers.delete('netflix');
providers.size; // => 1
providers.has('amazon'); // => true
providers.has('itunes'); // => false
providers.values(); // => {'amazon'}

Sets

const countries = ['de', 'us', 'us'];
const countriesSet = new Set(countries);

Cooperating with regular arrays:

// or super-short via ES6 destructuring 🚀
const uniqueCountries = [...new Set(countries)];
// => {'de', 'us'} 
// unique values!

WeakSets

  • only objects allowed
  • objects will be weakly linked
  • only 3 functions:
    • add()
    • delete()
    • has()
  • purpose: "tagging" of objects

→ not so relevant for us

Maps

… aka minimalistic objects!

const filters = new Map();
  • keys can be anything
filters.set('genres', ['action', 'scifi']);
filters.get('genres');    // => ['action', 'scifi']
filters.has('min_price'); // => false
filters.size; // => 1

(no prototype clutter)

Retransformation

How to handle those iterable objects?!

filters.entries(); // => {['genres', ['action', 'scifi']]}
filters.keys();    // => {'genres'}
filters.values();  // => {['action', 'scifi']}
filters.forEach((value, key) => {
    // do stuff...
});

for ([key, value] of filters) {
    // do stuff...
}

WeakMaps

Same story as for WeakSets…

→ not so relevant for us

That stuff
sounds
cool but…

Am I safe
thanks to Babel?

Yes, via polyfill.

🤔

Compatibility

Learning Resources

Tutorial for maps and sets:

http://2ality.com/2015/01/es6-maps-sets.html

Thanks for listening!

As always: MDN as a reference. 💘

Set

Map

ES6: Sets & Maps

By Sebastian Herrmann

ES6: Sets & Maps

What do we gain from using ES6's new sets and maps?

  • 1,759