Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ES2015 Collections

Avatar for Greg Jopa Greg Jopa
November 16, 2017

ES2015 Collections

Objects and Arrays are the well known data structures in JavaScript. ES2015 introduces new data structures like Set, Map, and WeakMap for efficiently working with collections.

Avatar for Greg Jopa

Greg Jopa

November 16, 2017
Tweet

More Decks by Greg Jopa

Other Decks in Technology

Transcript

  1. About me I’m Greg Jopa - Software Engineering Manager at

    Cars.com - Previously at YP in Los Angeles - github.com/gregjopa
  2. About this talk - Review Objects and Arrays - Learn

    about ES2015 collections - Set - Map - WeakMap - Ask questions anytime
  3. What is Node.js - A platform built on the V8

    JavaScript engine - Mostly written in C code - Makes writing powerful C/C++ server-side apps easy by wrapping then in JavaScript
  4. ES2015 aka ES6 Goal - make JavaScript more readable -

    Clarity - Expressiveness - Less Redundancy - Better features (collections)
  5. “Programs must be written for people to read, and only

    incidentally for machines to execute.” - “Structure and Interpretation of Computer Programs” by Abelson and Sussman
  6. Collections Collections - objects that store other objects allowing access

    and transversal House Analogy - Numbers, Booleans, and Strings are the bricks - You can’t build a house with a single brick - Collections group these bricks to build complex structures
  7. ES5 Collections - Arrays - flexible - Objects (as dictionaries)

    - Strings (kinda) - Pseudo-arrays - Arguments - NodeList objects
  8. Problems with ES5 Collections - Arrays - Not unique -

    Objects - Keys are always converted to strings - Inherited properties (toString, __proto___)
  9. Sets - Store unique values of any type - Primitive

    values - Objects - Sets preserve order const mySet = new Set(); // methods mySet.add('john'); mySet.add('paul'); mySet.add('paul'); // duplicate not added mySet.has('john'); // => true mySet.delete('john'); mySet.clear(); // properties mySet.size;
  10. Unique Arrays in ES3 and ES5 // E3 solution -

    too hard so use a library like lodash _.uniq([2, 1, 2]); // ES5 solution [2, 1, 2].filter(function (elem, pos, arr) { return arr.indexOf(elem) === pos; });
  11. Unique Arrays in ES6 // ES6 solution Array.from(new Set([2, 1,

    2])); // or use the spread operator [... new Set([2, 1, 2])];
  12. Unique Array of Objects in ES6 // object references are

    also unique const mySet = new Set(); const obj = { a: 1, b: 2 }; mySet.add(obj); // obj is referencing a different object so this is okay mySet.add({a: 1, b: 2}); mySet.has(obj); // true
  13. Maps - Collection of key/value pairs - Store any value

    as key/value - Objects are not converted to strings - Use maps when keys are unknown until runtime const myMap = new Map(); // methods myMap.set(1, 'john'); myMap.get(1); myMap.has(1); // => true myMap.has(2); myMap.delete(1); myMap.clear(); // properties myMap.size;
  14. Problem with Objects as Maps // keys are converted to

    strings const user1 = { name: 'Sam' }; const user2 = { name: 'Tyler' }; const replies = {}; replies[user1] = 5; relies[user2] = 42; console.log(replies[user1]); // => 42 console.log(replies[user2]); // => 42 console.log(Object.keys(replies)); // => ["[object Object]"]
  15. Maps example const recentPosts = new Map(); createPost(newPost, data =>

    { recentPosts.set(data.postId, data.message); }); // ...somewhere else in the code socket.on('new post', data => { recentPosts.set(data.postId, data.message); });
  16. Iterating over Maps and Sets - for...of - forEach const

    mySet = new Set([1, 2, 3]); for (let item of mySet) { console.log(item); } mySet.forEach(item => { console.log(item)});
  17. WeakMaps - Collection of key/value pairs - Only objects can

    be passed as keys - Other data types are not allowed - Better with Memory - Individual entries can be garbage collected while WeakMap still exists - Cleaned up when no longer referenced anywhere else - Cannot be enumerated
  18. WeakMap Syntax const wm = new WeakMap(); const obj1 =

    { first: 1 }; const obj2 = { second: 2 }; // methods wm.set(obj1, 1); wm.set(obj2, 2); wm.get(obj1); // => 1 wm.has(obj2); // => true wm.has({}); wm.delete(obj1);
  19. WeakMap Garbage Collection // destroyed objects get garbage collected const

    wm = new WeakMap(); let obj1 = { first: 1 }; let obj2 = { second: 2 }; wm.set(obj1, 1); wm.set(obj2, 2); wm.get(obj1); // => 1 obj1 = null; wm.get(obj1); // => undefined
  20. WeakMaps in the real-world https://github.com/emberjs/ember.js - Uses WeakMap for managing

    list of observers - Polyfills WeakMap for browser support
  21. WeakMaps in the real-world let _counter = new WeakMap(); let

    _action = new WeakMap(); class Countdown { constructor (counter, action) { _counter.set( this, counter); _action.set( this, action); } dec() { let counter = _counter.get( this); if (counter < 1) return; counter--; _counter.set( this, counter); if (counter === 0) { _action.get( this)(); } } }
  22. Summary Maps and Sets - Store any type of data

    - Can be iterated WeakMaps - Memory efficient - Only objects - Cannot be iterated