Skip to content

Instantly share code, notes, and snippets.

@bambielli
Created October 1, 2018 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bambielli/3b1f30642e9834500a1512b06ce5e102 to your computer and use it in GitHub Desktop.
Save bambielli/3b1f30642e9834500a1512b06ce5e102 to your computer and use it in GitHub Desktop.
Map Set WeakMap WeakSet
// Today I learned about some intracicies of Map, Set, WeakMap and WeakSet
/**
Map
1. Maps can have non-string keys, even objects! Any value is valid, including NaN.
2. When iterating over Maps, insertion order is preserved for iteration.
3. Construct a Map from an object using Object.entries(obj). This converts an object to Map's expected format of nested arrays.
4. Has .keys(), .values(), and .entries() methods.
*/
const map = new Map([['b', 2], ['a', 1], ['c', 3]]);
map.forEach((value, key, map) => {
console.log(key);
console.log(value);
});
/**
Set
1. Setifying something is a good way to remove duplicates in an array of values.
2. When iterating over sets, insertion order is also preserved.
- If a value is encountered twice, the initial insert defines the order in which it is returned during iteration.
3. Constructing a set can be done from a simple array.
4. Also has .keys(), .values(), and .entries() methods. Returns iterables.
*/
const set = new Set([1, 2, 3])
set.forEach((value, value2, set) => {
console.log(value);
console.log(value2);
});
/**
WeakMap and WeakSet
Like Map and Set except:
1. WeakMap keys MUST be object references
2. WeakSet values MUST be object references
3. WeakMap keys / weakSet values can be garbage collected if no other references point to them.
- this means they can be deleted from the weakSet / WeakMap automatically.
This might be useful if you have some contextual information about an object that should only live for the lifetime of the object.
For example, if a user logs in, and you keep track of the user object in session storage, you might store some lifetime metadata
about the user in a weakMap.
Because keys and values can be garbage collected at any time WeakMap and WeakSet do not have size() methods.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment