Today I Learned - sets, maps

Hyodduru ·2021년 12월 13일
0

JavaScript

목록 보기
35/60
post-thumbnail

강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)

sets

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}

size

몇종류의 item 있는지 확인 (set의 갯수 확인)

console.log(ordersSet.size); // 총 몇종류의 item이 있는지 확인 가능.

has()

item 존재여부 확인

console.log(ordersSet.has('Pizza')); //true
console.log(ordersSet.has('Bread')); //false

add() & delete()

item 추가와 제거

ordersSet.add('Garlic Bread');
ordersSet.add('Garlic Bread');
ordersSet.delete('Risotto');

console.log(ordersSet); //Set(4) {'Pasta', 'Pizza', 'Garlic Bread'}

clear()

delete all of the elements of the set

ordersSet.clear(ordersSet);

주의사항)

  • set 은 index를 가지고 있지않다. => ordersSets[0] 이런 식의 표기 불가능!
  • set의 value를 밖으로 꺼내올 수 있는 방법은 없다. 그 기능은 array를 통해서 하면 됌. set 을 이용해서 unique한 value 값을 확인하기만 하면 되므로!
  • 우리가 set을 가지고 하는 것은 set 내에 해당 item이 있는지 등 뿐이므로!

iterable set

set 또한 iterable이다. => 반복문 이용 가능

for (const order of ordersSet) console.log(order); // Pasta / Pizza / Garlic Bread

Example conversion set to array

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!

Maps : Fundamentals

map 에서는 어떤 datatype의 key, value이든 저장 가능하다.

const rest = new Map();

set()

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'}

map chaining

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()

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

has()

map item 여부확인

console.log(rest.has('categories'));

delete()

map item 삭제

rest.delete(2);

size

map item 개수

console.log(rest.size); // 7

clear

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

Maps : Iteration

set 대신 map 내 item 생성하는 법

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);

Convert object to map

 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));

Convert map to array

 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!']

Which Data Structure to Use?

Data Structure Overview

source of data

  1. from the program itself : Data written directly in source code. based on user actions (ex. status message)
  2. from the UI(User Interface) : Data input from the user or data written in DOM (ex. tasks in to do app)
  3. 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

Arrays vs Sets and Objects vs Maps

1) Arrays vs Sets

Arrays

  • use when you need ordered list of values(might contain duplicates)
  • use when you need to manipulate data

Sets

  • 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를 보완해주는 것!

2) Objects vs Maps

Objects

  • 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)

Maps

  • 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
profile
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다

0개의 댓글