강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)
collection of unique value = a set can never have any duplicates
const ordersSet = new Set(['Pasta', 'Pizza', 'Risotto', 'Pasta', 'Pizza']);
console.log(ordersSet); //Set(3) {'Pasta', 'Pizza', 'Risotto'}
console.log(new Set('Jonas')); //Set(5) {'J', 'o', 'n', 'a', 's'}
console.log(new Set()); //Set(0) {size: 0}
몇종류의 item 있는지 확인 (set의 갯수 확인)
console.log(ordersSet.size); // 총 몇종류의 item이 있는지 확인 가능.
item 존재여부 확인
console.log(ordersSet.has('Pizza')); //true
console.log(ordersSet.has('Bread')); //false
item 추가와 제거
ordersSet.add('Garlic Bread');
ordersSet.add('Garlic Bread');
ordersSet.delete('Risotto');
console.log(ordersSet); //Set(4) {'Pasta', 'Pizza', 'Garlic Bread'}
delete all of the elements of the set
ordersSet.clear(ordersSet);
주의사항)
set 또한 iterable이다. => 반복문 이용 가능
for (const order of ordersSet) console.log(order); // Pasta / Pizza / Garlic Bread
const staff = ['Waiter', 'Chef', 'Waiter', 'Manager', 'Chef', 'Waiter'];
const staffUnique = [...new Set(staff)];
console.log(staffUnique); //(3) ['Waiter', 'Chef', 'Manager']
console.log(new Set(staff).size);
conclusion : sets are not intended to replace arrays at all. So whenever you need to store values in order, and that might contain dupicates, always just use arrays. that also to manipulate datas!
map 에서는 어떤 datatype의 key, value이든 저장 가능하다.
const rest = new Map();
add data
rest.set('name', 'Classico Italiano');
rest.set(1, 'Firenze, Italy');
console.log(rest.set(2, 'Lisbon, Portugal')); //Map(3) {'name' => 'Classico Italiano', 1 => 'Firenze, Italy', 2 => 'Lisbon, Portugal'}
rest
.set('categories', ['Italian', 'Pizzeria', 'Vegetarian', 'Oraganic'])
.set('open', 11)
.set('close', 23)
.set(true, 'We are open :D')
.set(false, 'We are close :(');
get values
console.log(rest.get('name')); //Classico Italiano
console.log(rest.get(true)); //We are open :D
const time = 21;
console.log(rest.get(time > rest.get('open') && time < rest.get('close'))); // We are open :D
map item 여부확인
console.log(rest.has('categories'));
map item 삭제
rest.delete(2);
map item 개수
console.log(rest.size); // 7
rest.clear();
map과 set 공통점 많음. ES6에 같이 나와서.
rest.set([1, 2], 'Test');
console.log(rest.size);
console.log(rest.get([1, 2])); //undefined why? 위의 [1,2]와 이 줄에서의 [1,2]는 실제로 같은 array가 아님!!! they are not the same object in the heap
// 이를 해결해주기 위해서는 [1,2]를 변수취급 해줄 것!
const arr = [1, 2];
rest.set(arr, 'Test');
rest.set(document.querySelector('h1'), 'Heading');
console.log(rest);
console.log(rest.get(arr)); //Test
new Map([[key, value],[key,value]])
const question = new Map([
['question', 'What is the best programming language in the world?'],
[1, 'c'],
[2, 'Java'],
[3, 'JavaScript'],
['correct', 3],
[true, 'Correct 🎉'],
[false, 'Try again!'],
]);
console.log(question);
console.log(Object.entries(openingHours)); // (3) //[Array(2), Array(2), Array(2)]
// 0: (2) ['thu', {…}]
// 1: (2) ['fri', {…}]
// 2: (2) ['sat', {…}]
const hoursMap = new Map(Object.entries(openingHours));
console.log(hoursMap);
Iterable map - Quiz app
console.log(question.get('question'));
for (const [key, value] of question) {
if (typeof key === 'number') console.log(`Answer ${key} : ${value}`);
}
Answer 1 : c
Answer 2 : Java
Answer 3 : JavaScript
const answer = Number(prompt('Your answer'));
console.log(question.get(question.get('correct') === answer));
console.log([...question]); // new Map 감싸기 전 형태로 바뀜.
// console.log(question.entries());
// console.log([...question.keys()]); // ['question', 1, 2, 3, 'correct', true, false]
// console.log([...question.values()]); //['What is the best programming language in the world?', 'c', 'Java', 'JavaScript', 3, 'Correct 🎉', 'Try again!']
- from the program itself : Data written directly in source code. based on user actions (ex. status message)
- from the UI(User Interface) : Data input from the user or data written in DOM (ex. tasks in to do app)
- from external sources : Data fetched for example from web API(ex. recipe objects)
source of data ---> collection of data --> Data Structure --->(Simple list?) Arrays or Sets /(Key/Value Pairs?) Object or Maps
참고) arrays, sets, objects, maps are built-in data structures
- use when you need ordered list of values(might contain duplicates)
- use when you need to manipulate data
- use when you need to work with unique values
- use when high-performance is really important
- use to remove duplicates from arrays
Sets는 Array를 대체하는 개념이 아니다. 필요할 때 Array를 보완해주는 것!
- More 'traditional' key / value store ("abused" objects)
- Easier to write and access values with . and []
- Use when you need to include functions(methods)
- Use when working with JSON (can convert to map)
- Better performance
- Keys can have any datatype
- Easy to iterate
- Easy to compute size
- Use when you simply need to map key to values
- Use when you need keys that are not strings