37장. Set과 Map

Doozuu·2023년 8월 31일
0

Javascript

목록 보기
76/99

37.1 Set

Set 객체는 중복되지 않는 유일한 값들의 집합이다.

  • Set 객체는 배열과 유사하지만 다음과 같은 차이가 있다.

이러한 Set 객체의 특성은 수학적 집합의 특성과 일치한다.
Set은 수학적 집합을 구현하기 위한 자료구조다. 따라서 Set을 통해 교집합, 합집합, 차집합, 여집합 등을 구현할 수 있다.


37.1.1 Set 객체의 생성

Set 객체는 Set 생성자 함수로 생성한다.

const set = new Set();
console.log(set); // Set(0) {}

Set 생성자 함수는 이터러블을 인수로 전달받아 Set 객체를 생성한다.
이때 이터러블의 중복된 값은 Set 객체에 요소로 저장되지 않는다.

const set1 = new Set([1,2,3,3]);
console.log(set1); // Set(3) {1,2,3}

const set2 = new Set('hello');
console.log(set2); // Set(4) {'h','e','l','o'}

중복을 허용하지 않는 Set 객체의 특성을 활용하여 배열에서 중복된 요소를 제거할 수 있다.

const uniq = array => [...new Set(array)];
console.log(uniq([2,1,2,3,4,3,4])); // [2,1,3,4]

37.1.2 요소 개수 확인

Set 객체의 요소 개수를 확인할 때는 Set.prototype.size 프로퍼티를 사용한다.


37.1.3 요소 추가

Set 객체에 요소를 추가할 때는 Set.prototype.add 메서드를 사용한다.

const set = new Set();

set.add(1);
console.log(set); // Set(1) {1}

Set 객체는 객체나 배열과 같이 자바스크립트의 모든 값을 요소로 저장할 수 있다.

const set = new Set();

set
  .add(1)
  .add('a')
  .add(true)
  .add(undefined)
  .add(null)
  .add({})
  .add([])
  .add(() => {})

37.1.4 요소 존재 여부 확인

set 객체에 특정 요소가 존재하는지 확인하려면 Set.prototype.has 메서드를 사용한다.
has 메서드는 특정 요소의 존재 여부를 나타내는 불리언 값을 반환한다.

const set = new Set([1,2,3]);

console.log(set.has(2)); // true

37.1.5 요소 삭제

set 객체의 특정 요소를 삭제하려면 Set.prototype.delete 메서드를 사용한다.
delete 메서드는 삭제 성공 여부를 나타내는 불리언 값을 반환한다.

delete 메서드에는 인덱스가 아니라 삭제하려는 요소값을 인수로 전달해야 한다. Set 객체는 순서에 의미가 없다. 다시 말해, 배열과 같이 인덱스를 갖지 않는다.
(만약 존재하지 않는 Set 객체의 요소를 삭제하려 하면 에러 없이 무시된다.)

const set = new Set([1,2,3]);

set.delete(2);
console.log(set); // Set(2) {1,3}

37.1.6 요소 일괄 삭제

Set 객체의 모든 요소를 일괄 삭제하려면 Set.protyotype.clear 메서드를 사용한다. clear 메서드는 언제나 undefined를 반환한다.

const set = new Set([1,2,3]);

set.clear();
console.log(set); // Set(0) {}

37.1.7 요소 순회

Set 객체의 요소를 순회하려면 Set.prototype.forEach 메서드를 사용한다.

이때 콜백 함수는 3개의 인수를 전달받는다.
(현재 순회 중인 요소값, 현재 순회 중인 요소값, 현재 순회 중인 Set 객체 자체)

첫 번째 인수와 두 번째 인수는 같은 값이다.
이처럼 동작하는 이유는 Array.prototype.forEach 메서드와 인터페이스를 통일하기 위함이며 다른 의미는 없다. Array.prototype.forEach 메서드의 콜백 함수는 두 번째 인수로 현재 순회 중인 요소의 인덱스를 전달받는다. 하지만 Set 객체는 순서에 의미가 없어 배열과 같이 인덱스를 갖지 않는다.

const set = new Set([1,2,3]);

set.forEach((v, v2, set) => console.log(v, v2, set));

Set 객체는 이터러블이기 때문에 for...of 문으로 순회할 수도 있다.


37.1.8 집합 연산

Set 객체는 수학적 집합을 구현하기 위한 자료구조다.
따라서 Set을 통해 교집합, 합집합, 차집합, 여집합 등을 구현할 수 있다.

교집합

Set.prototype.intersection = function(set){
	const result = new Set();
    
    for (const value of set) { 
    	if(this.has(value)) result.add(value);
    }
  
  	return result;
}

const setA = new Set([1,2,3,4]);
const setB = new Set([2,4]);

console.log(setA.intersection(setB)); // {2,4}

합집합

Set.prototype.union = function(set){
	const result = new Set(this);
    
    for (const value of set) { 
    	result.add(value);
    }
  
  	return result;
}

// 혹은 아래 방법으로도 가능
Set.prototype.union = function(set){
  	return new Set([...this, ...set]);
}

const setA = new Set([1,2,3,4]);
const setB = new Set([2,4]);

console.log(setA.union(setB)); // {1,2,3,4}

차집합

Set.prototype.difference = function(set){
	const result = new Set(this);
    
    for (const value of set) { 
    	result.delete(value);
    }
  
  	return result;
}

// 혹은 아래 방법으로도 가능
Set.prototype.difference = function(set){
  	return new Set([...this].filter(v => !set.has(v)));
}

const setA = new Set([1,2,3,4]);
const setB = new Set([2,4]);

console.log(setA.intersection(setB)); // {1,3}



37.2 Map

Map 객체는 키와 값의 쌍으로 이루어진 컬렉션이다.

  • Map 객체는 객체와 유사하지만 다음과 같은 차이가 있다.

37.2.1 Map 객체의 생성

Map 객체는 Map 생성자 함수로 생성한다.

const map = new Map();
console.log(map); // Map(0) {}

Map 생성자 함수는 이터러블을 인수로 전달받아 Map 객체를 생성한다.
이때 인수로 전달되는 이터러블은 키와 값의 쌍으로 이루어진 요소로 구성되어야 한다.

const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
console.log(map); // Map(2) {'key1' => 'value1', 'key2' => 'value2'}

Map 생성자 함수의 인수로 전달한 이터러블에 중복된 키를 갖는 요소가 존재하면 값이 덮어써진다. 따라서 Map 객체에는 중복된 키를 갖는 요소가 존재할 수 없다.

37.2.2 요소 개수 확인

Map 객체의 요소 개수를 확인할 때는 Map.prototype.size 프로퍼티를 사용한다.

37.2.3 요소 추가

Map 객체에 요소를 추가할 때는 Map.prototype.set 메서드를 사용한다.

const map = new Map();

map.set('key1','value1');

console.log(map); // Map(2) {'key1' => 'value1'}

객체는 문자열 또는 심벌 값만 키로 사용할 수 있다.
하지만 Map 객체는 키 타입에 제한이 없다. 따라서 객체를 포함한 모든 값을 키로 사용할 수 있다.
이는 Map 객체와 일반 객체의 가장 두드러지는 차이점이다.


37.2.4 요소 취득

Map 객체에서 특정 요소를 취득하려면 Map.prototype.get 메서드를 사용한다.
get 메서드의 인수로 키를 전달하면 Map 객체에서 인수로 전달한 키를 갖는 값을 반환한다.

const map = new Map();

const lee = {name: 'Lee'};

map.set(lee,'developer');

console.log(map.get(lee)); // developer

37.2.5 요소 존재 여부 확인

Map 객체에 특정 요소가 존재하는지 확인하려면 Map.prototype.has 메서드를 사용한다. has 메서드는 특정 요소의 존재 여부를 나타내는 불리언 값을 반환한다.

const lee = {name: 'Lee'};

const map = new Map([[lee,'developer']);

console.log(map.has(lee)); // true

37.2.6 요소 삭제

Map 객체의 요소를 삭제하려면 Map.prototype.delete 메서드를 사용한다.
delete 메서드는 삭제 성공 여부를 나타내는 불리언 값을 반환한다.

const lee = {name: 'Lee'};

const map = new Map([[lee,'developer']);
                     
map.delete(lee);

37.2.7 요소 일괄 삭제

Map 객체의 요소를 일괄 삭제하려면 Map.prototype.clear 메서드를 사용한다.

const lee = {name: 'Lee'};

const map = new Map([[lee,'developer']]);
                     
map.clear();

37.2.8 요소 순회

Map 객체의 요소를 순회하려면 Map.prototype.forEach 메서드를 사용한다.

이때 콜백 함수는 3개의 인수를 전달받는다.
(현재 순회 중인 요소값, 현재 순회 중인 요소키, 현재 순회 중인 Map 객체 자체)

const lee = {name: 'Lee'};

const map = new Map([[lee,'developer']]);

map.forEach((v, k, map) => console.log(v, k, map));

Map 객체는 이터러블이다. 따라서 for...of 문으로 순회할 수 있다.
Map 객체는 이터러블이면서 동시에 이터레이터인 객체를 반환하는 메서드를 제공한다.

profile
모든게 새롭고 재밌는 프론트엔드 새싹

0개의 댓글