TIL 104 | Map, Set, WeakMap, WeakSet

meow·2021년 1월 7일
1

JavaScript

목록 보기
45/46

Hashmap?

Map 인터페이스의 한 종류로, key-value 형태의 데이터를 저장하는 형태를 가지고 있다. Map이란 키와 값을 하나의 쌍으로 묶어서 저장하는 컬렉션 클래스들을 구현하는데 사용된다. 쉽게 말해 key, value 값으로 저장하는 List 형태의 조상이라고 할 수 있다.

Java Hashmap → JavaScript Map

Hashmap은 데이터에 빠르게 접근할 수 있다는 장점이 있다. 아래는 Java에서 Hashmap을 사용하는 예시이다.

import java.util.*;

class Main {
  public static void main(String[] args) {
    
    Map<String, String> myContacts = new HashMap<>();
    myContacts.put('Mia', '555-1234');
    myContacts.put('Jay' '555-2345');
    System.out.println(myContacts.get('Mia')); // 555-1234
    
    // get the entire entrySet
    for(Map.Entry<String, String> entry:myContacts.entrySet()){
      System.out.println(entry.getKey()); // Mia Jay
      System.out.println(entry.getValue());
      System.out.println(myContacts.get(entry.getKey()));
    }
    
    Set<String> keys = myContacts.ketSet();
    for(String key : keys){
      System.out.pringln(key + ':' + myContacts.get(key));
    }
  }
}

Map is just a key-value pair. It's FARE MORE PROTECTED than is a regular object. It also comes with some cool methods specific to map. It is also an iterable.

// Object
const myContactsObj = {
  "mia": "555-1234",
  "Jay": "555-2345"
}

let keyFunction = () => {
  console.log("Hello, World")
}

// Map
let myContactsMap = new Map();
myContacts.set("mia", "555-1234");
const number = myContacts.get("mia");
console.log(number) // 555-1234

myContacts.set(keyFunction, "HaHa");
const huh = myContacts.get(keyFunction);
console.log(huh); // HaHa

위 예시를 보면 loacl storage에서 값을 가져올때 set, get을 사용한 것과 유사한 것을 알 수 있다.

let keyFunction = () => {
  console.log("Hello, World")
}

// Map
let newMap = new Map();

newMap.set(keyFunction, "HaHa");
const huh = newMap.get(keyFunction);
console.log(huh); // HaHa

함수가 key가 되었다?! Map에서 key의 형태는 Object보다 훨씬 자유롭다. Object에서 이렇게 key에 함수를 두면 에러가 발생한다.

const newObj = {
  () => {}: "something" // Error!
}

key 값에 함수를 넣을 일이 있을까 싶겠지만, key와 value에 각각 연결되기 원하는 함수를 넣고 싶을 수도 있을 것이다.

Map methods

.get &.set

let myContacts = new Map();
// .get, .set
myContacts.set('mia', '555-1234');
const number = myContacts('mia')

.size

// .size - key, value 쌍의 갯수
console.log(myContacts.size) // 1

for ... of

// for ... of
for(value of myContacts){
  console.log(value);
}

.clear

// .clear - map 내부의 key-value를 모두 삭제
myContacts.clear();
console.log(myContacts); // Map {}

.entries

// .entries - get all the entries
console.log(myContacts.entries());
// MapIterator {'mia', '555-1234'}

forEach

// entries와 다른 점은 콜백을 할 수 있다는 것
myContacts.forEach(value => console.log(value));
// 555-1234

.keys & .values

console.log(myContacts.keys()); // MapIterator { 'mia' }
console.log(myContacts.values()); // MapIterator { '555-1234' }

Weak Map vs. Map

Weak Map 역시 Java의 영향을 받아 만들어졌다. 두가지 큰 차이점이 있다.

  1. weakMap은 key가 참조되지 않을 때 가비지 컬렉션을 허용한다.
  2. iterable하지 않고, 오직 get, set, has, delete 네가지 메소드만 사용 가능하다.
let aStrongMap = new Map();
let friend = { name: 'Mia' };
aStrongMap.set(friend, 'Best Friend');
console.log(aStrongMap.get(friend)); // Best Friend

friend = null;
console.log(aStrongMap.entries());
// MapIterator { [ { name: 'Mia'}, 'Best Friend'] }

Map은 참조하던 값이 변하더라도 한번 설정된 값이 유지되는 것을 볼 수 있다.

let aWeakMap = new WeakMap();
let friend = { friend: 'Bill' };
aWeakMap.set(friend, 'Best Friend');
console.log(aWeakMap.get(friend)); // Best Friend

friend = null;
console.log(aWeakMap.get(friend));
// undefined

weakMap은 key 값이 null로 사라지자 undefined가 반환된다. 가비지 컬렉팅을 허용하여 메모리를 관리하고 싶다면 weakMap을 사용하는 것이 좋겠지만, 대부분의 경우 Map을 사용한다.

Set constructor

Set 는 배열과 유사하지만 배열이 아니다! 따라서 배열의 메소드를 사용할 수 없다. 어떠한 데이터 타입도 포함할 수 있으며, 모든 요소는 유니크하다. Set은 iterable하다. (삽입된 순서대로)

// array 의 경우 문제 없다.
let employeeId = ['a12', 'e7', 'c2', 'a12'];

// set은 각 요소가 유니크해야 한다.
let employeeId2 = new Set(['a12', 'e7', 'c2', 'a12']);
console.log(employee2); // {'a12', 'e7', 'a12'}

Set 메소드

  • .size : array의 length와 동일
  • .add : array의 push와 동일 * 참조형 데이터는 동일한 요소 추가 가능
  • .clear : empty the Set
  • .delete : 특정 요소를 삭제
  • .entries : Map처럼, iterable을 반환한다. key-value pair를 반환하지만 key와 value는 같다.
  • .forEach
  • .has : 특정 요소가 존재하는지 확인한다.
  • .keys, .values

Weak Set vs. Set

WeakSet는 Set과 달리 Objects 만을 포함할 수 있다.
WeakMap 처럼 가비지 컬렉션이 이루어진다.
Not iterable(no get method, size is ALWAYS 0)
객체들로 이루어진 그룹을 만들고 싶을때 사용할 수 있다. 그 외 응용할만한게 없는듯..?

let harry = {
  name: 'Harry',
  id: 12
}
let ron = {
  name: 'Ron',
  id: 7
}

let employeeIds = new WeakSet();
employeeIds.add(harry);
employeeIds.add(ron);
console.log(employeeIds.has(harry)); // true
profile
🌙`、、`ヽ`ヽ`、、ヽヽ、`、ヽ`ヽ`ヽヽ` ヽ`、`ヽ`、ヽ``、ヽ`ヽ`、ヽヽ`ヽ、ヽ `ヽ、ヽヽ`ヽ`、``ヽ`ヽ、ヽ、ヽ`ヽ`ヽ 、ヽ`ヽ`ヽ、ヽ、ヽ`ヽ`ヽ 、ヽ、ヽ、ヽ``、ヽ`、ヽヽ 🚶‍♀ ヽ``ヽ``、ヽ`、

0개의 댓글