vikramlc / Javascript

0 stars 0 forks source link

Maps and Sets #8

Open vikramlc opened 4 years ago

vikramlc commented 4 years ago

image

vikramlc commented 4 years ago

Creating a set and parsing the set:

const str = ['Hi','there','hello'];
const ids = new Set([...str]); 
console.log(ids); // {"Hi", "there", "hello"}

for(const value of ids.values()) {
    console.log(value); // "Hi", "there", "hello"
}
vikramlc commented 4 years ago

Creating a map and parsing the map:

const person1 = { name: 'Max' };
const person2 = { name: 'Manuel' };

const personData = new Map([[person1, [{ date: 'yesterday', price: 10 }]]]);
console.log(personData);
console.log(personData.get(person1));

personData.set(person2, [{ date: 'two weeks ago', price: 100 }]);
console.log(personData);

console.log('entries');
for (const entry of personData.entries()) {
    console.log(entry);
}

console.log('key/value -> entries');
for (const [key, value] of personData.entries()) {
    console.log(key, value);
}

console.log('keys');
for (const key of personData.keys()) {
    console.log(key);
}

console.log('values');
for (const value of personData.values()) {
    console.log(value);
}

console.log(personData.size);
vikramlc commented 4 years ago

Maps vs Objects: image

WeakSet: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet

let person = { name: 'Max' };
const persons = new WeakSet();
persons.add(person);

person = null; // this will be garbage collected by the browser because of weakset

WeakMap: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap

let person = { name: 'Max' };
const persons = new WeakSet();
persons.add(person);

const personData = new WeakMap();
personData.set(person, 'Extra info!');

person = null; // this will be garbage collected by the browser because of weakmap
console.log(personData);