let _set = new Set(); // n.b. set is a reserved word, so I'm calling my variable _set
// Set.prototype.add
_set.add("string").add(42);
// store object references
let obj = { a : 1 };
_set.add(obj);
// Set.prototype.size
_set.size // => 3
_set.add(42) // no repeats
_set.size // => 3
// Set.prototype.has
_set.has("string") // true
_set.has(obj) // true, wowzers!
_set.has(21) // false
// Iterate using for...of
for (let item of _set) console.log(item); // logs in insertion order
// Set.prototype.delete and Set.prototype.clear
_set.delete("string"); // remove a single item
_set.clear(); // wipe the set clean
Could have duplicates
Actually an object
Iterate with for loop
Unique values
No baggage
Iterate with for...of
Has a prototype (default key)
Keys are strings or symbols
Cannot get size easily
No prototype
Keys are any type
Can get size easily
let _map = new Map(); // now I'm just being consistent ;)
// Map.prototype.set
_map.set('a', 1);
_map.set('b', 2);
let objKey = { 'c' : 3 };
_map.set(objKey, 4);
// Map.prototype.get
_map.get('a'); // => 1
_map.get(objKey); // => 4
// Map.prototype.size - much easier than using Object.hasOwnProperty!
_map.size; // => 3
// Iterate over keys using Map.prototype.keys
for (let key of _map.keys()) console.log(key);
// Iterate over values using Map.prototype.values
for (let value of _map.values()) console.log(value);
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)();
}
}
}
// http://www.2ality.com/2015/01/es6-maps-sets.html