SHARE
TWEET

Untitled

a guest Feb 22nd, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Map objects create a traditional get and set interface around data stored in key/value pairs.
  2.  
  3. const MyMap = new Map();
  4.  
  5. MyMap.set('name', 'Sheryl');
  6. MyMap.set('occupation', 'Programmer');
  7. MyMap.set('id', 18);
  8.  
  9. MyMap.get('name'); // => 'Sheryl'
  10. MyMap.get('occupation'); // => 'Programmer'
  11. MyMap.get('id'); // => 18
  12.  
  13.  
  14.  
  15. // When you're constructing a Map, you can pass in an Iterable, like an Array, and it'll create key value pairs
  16. // based on the object or array you pass in.
  17.  
  18. const OrderMap = new Map([
  19.   'Welcome',
  20.   'To',
  21.   true,
  22.   'life',
  23.   'programming'
  24. ]);
  25.  
  26. // All the 'keys' will be indexes from the array
  27. OrderMap.get(0); // => 'Welcome'
  28. OrderMap.get(3); // => 'life'
  29. OrderMap.get('whatev'); // => undefined
  30.  
  31.  
  32.  
  33. // If you use Object.entries(), you can actually convert an Object to a Map pretty easily:
  34.  
  35. const Person = {
  36.   name: 'Sheryl',
  37.   occupation: 'Programmer',
  38.   id: 18
  39. };
  40.  
  41. // Creates the same map in the previous example
  42. const PersonMap = new Map(Object.entries(Person));
  43.  
  44. PersonMap.get('name'); // => 'Sheryl'
  45. PersonMap.get('occupation'); // => 'Programmer'
  46. PersonMap.get(18); // => 18
  47.  
  48.  
  49. // Just like with an object, you can iterate over a Map
  50.  
  51. const Person = {
  52.   name: 'Sheryl',
  53.   occupation: 'Programmer',
  54.   id: 18
  55. };
  56.  
  57. // Iterating over an object
  58. for (let key in Person) {
  59.   console.log(Person[key]); // 'Sheryl, 'Programmer', 18 - but not guaranteed in that order!
  60. }
  61.  
  62. // Iterating over a Map
  63. const PersonMap = new Map(Object.entries(Person));
  64.  
  65. // You can iterate with the built-in #forEach
  66. PersonMap.forEach( (key, value) => {
  67.   console.log(key, value); // => 'name', 'Sheryl', 'occupation', 'Programmer', 'id', 18
  68. });
  69.  
  70. // Or you can use a for-of loop
  71. for (let [ key, value ] of PersonMap) {
  72.   console.log(key, value); // => 'name', 'Sheryl', 'occupation', 'Programmer', 'id', 18
  73. }
  74.  
  75. // If you only need keys or values, you can use for-of with the .keys() or .values() methods
  76. for (let key of PersonMap.keys()) {
  77.   console.log(key); // => 'name', 'occupation', 'id'
  78. }
  79.  
  80. for (let value of PersonMap.values()) {
  81.   console.log(value); // => 'Sheryl', 'Programmer', 18
  82. }
  83.  
  84.  
  85. // Think of Map like an enhanced object.
  86. // Unlike an object, you can find out how many key/value pairs exist inside Map
  87.  
  88. // Finding the size of an Object
  89. Object.keys(Person).length; // => 3
  90.  
  91. // Finding the size of a Map
  92. PersonMap.size; // => 3
  93.  
  94.  
  95. // The REAL power comes from having non-string keys.
  96.  
  97. const Dave = {
  98.   id: 19,
  99.   likesBacon: 'yes'
  100. };
  101.  
  102. const Sheryl = {
  103.   id: 18,
  104.   likesBacon: 'also yes'
  105. };
  106.  
  107. const ValidationCache = new Map();
  108. ValidationCache.set(Dave, false);
  109. ValidationCache.set(Sheryl, true);
  110.  
  111. ValidationCache.get(Dave); // false
  112. ValidationCache.get(Sheryl); // true
  113.  
  114.  
  115. // It's not just objects, you can use numbers, NaN, undefined, just about anything.
  116.  
  117. // Unlike Object, Map is ordered by the order of insertion.
  118.  
  119. const SomeMap = new Map();
  120. SomeMap.set('first', 1);
  121. SomeMap.set('second', 2);
  122. SomeMap.set('third', 3);
  123.  
  124. for (let [key, value] of SomeMap) {
  125.   console.log(key, value);
  126. }
  127. // Returns in order:
  128. // first, 1
  129. // second, 2
  130. // third, 3
  131.  
  132.  
  133. // Practical Usage in Modern JavaScript
  134. // SCENARIO: We need a quick way to see if some users (represented by objects) are of legal drinking age
  135. // in our hot "bar loyalty social media site startup".
  136.  
  137. const LegalAgeCache = new Map();
  138.  
  139. const ArrayOfUsers = fetch('/users');
  140. ArrayOfUsers.forEach( user => {
  141.   LegalAgeCache.set(user, user.age >= 21); // Assuming we're in the USA. Sorry international students :(
  142. });
  143.  
  144. // Now wherever we need to check the users that are above age 21...
  145.  
  146. if (LegalAgeCache.get(John)) { // Assuming John is some user object
  147.   return 'beer';
  148. } else {
  149.   return 'appleJuice';
  150. }
  151.  
  152.  
  153. // WeakMap
  154. // WeakMap is the same as Map, but memory from unused references in the map can be cleaned up by JS garbage collection.
  155. // In terms of functional usage WeakMap cannot be iterated over and is better for performance if
  156. // you don't need to iterate over the map. The only methods available to WeakMap are:
  157.  
  158. .get(key)
  159. .set(key, value)
  160. .has(key)
  161. .clear() (this removes everything from the WeakMap)
  162.  
  163. // WeakMap can only use keys that are of type Object, meaning you can't use plain String or Number,
  164. // and you can't use primitive data types like Symbol either.
  165.  
  166. const myObject = {
  167.   name: 'Jeff'
  168. };
  169.  
  170. const myWeakMap = new WeakMap();
  171.  
  172. // This is fine because myObject is a variable that's of type, Object
  173. myWeakMap.set(myObject, 'Jeff is awesome'); // myWeakMap.get(myObject) => 'Jeff is awesome'
  174.  
  175. // This will throw an error, because it's a hardcoded string
  176. myWeakMap.set('Jeff', 'Jeff is cool'); // Error: Invalid value used as weak map key
  177.  
  178. // Under the hood, if an object has no more references pointing to it, it will be cleaned up by the garbage collector,
  179. // and in turn, deletes WeakMap's reference to the cleaned up object, which deletes the corresponding value.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top