모던 자바스크립트 Deep Dive: 37장 Set과 Map

37장 Set과 Map

37.1 Set

  • Set 객체는 중복되지 않는 유일한 값들의 집합
  • Set 객체는 배열과 유사하지만 다음과 같은 차이가 있다.
    • 동일한 값을 중복하여 포함할 수 없다.
    • 요소 순서에 의미가 없다.
    • 인덱스로 요소에 접근할 수 없다.
  • Set 객체의 특성은 수학적 집합의 특성과 일치해 수학적 집합을 구현하기 위한 자료구조이다.
  • 따라서 Set을 통해 교집합, 합집합, 차집합, 여집합 등을 구현할 수 있다.

Set 객체의 생성

  • Set 객체는 Set 생성자 함수로 생성한다.
  • Set 생성자 함수에 인수를 전달하지 않으면 빈 Set 객체가 생성됨
const set = new Set();
console.log(set); // Set(0)[]

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

이터러블 34장
이터러블 : 이터러블 프로토콜을 준수한 객체
Symbol.iterator를 프로퍼티 키로 사용한 메서드를 직접 구현하거나 프로토타입 체인을 통해 상속받은 객체

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

conset set2 = new Set('hello');
console.log(set2); //Set(4) {'h','e','l','o'}
  • 중복을 허용하지 않는 Set 객체의 특성을 활용해 배열에서 중복된 요소를 제거할 수 있다.
//배열의 중복 요소 제거
const uniq = array => array.filter((v,i,self) => self.indexOf(v) === i);
console.log(uniq([2,1,2,3,4,3,4])); // [2,1,3,4]

//Set을 사용한 배열의 중복 요소 제거
const uniq = array => [...new Set(array)]; //**35장 스프레드 문법**을 이용하면 이터러블을 배열로 간편하게 변환할 수 있음
console.log(uniq([2,1,2,3,4,3,4]));// [2,1,3,4]

요소 개수 확인

  • Set 객체의 요소 개수를 확인할 때는 Set.prototype.size 프로퍼티를 사용
const {size} = new Set([1,2,3,3]); //**36장 구조분해 할당**
console.log(size); //3
  • size 프로퍼티는 setter함수 없이 getter 함수만 존재하는 접근자 프로퍼티이기 때문에 size 프로퍼티에 숫자를 할당해 Set 객체의 요소 개수를 변경할 수 없다.
const set = new Set([1,2,3]);
console.log(Object.getOwnPropertyDescriptor(Set.prototype,'size'))
/*{
  get: [Function: get size],
  set: undefined,
  enumerable: false,
  configurable: true
}*/
set.size = 10; //무시됨
console.log(set.size); //3

요소 추가

  • Set 객체에 요소를 추가할 땐 Set.prototype.add 메서드를 이용한다.
const set = new Set();
console.log(set);// Set(0){}

set.add(1);
console.log(set);// Set(1){1}
  • add 메서드는 새로운 요소가 추가된 Set 객체를 반환하기 때문에 add 메서드를 연속으로 호출할 수 있다.
const set = new Set();

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

set.add(2); //중복된 요소의 추가는 허용되지 않으며 무시된다.
console.log(set);// Set(2){1,2}
  • Set 객체는 일치 비교 연산자와 다르게 NaN과 NaN을 같다고 평가하고 일치 비교 연산자와 같게 +0과 -0을 같다고 평가해 중복 추가를 허용하지 않는다.
const set = new Set();

console.log(NaN === NaN); // false
console.log(0 === -0); //true

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

set.add(0).add(-0);
console.log(set);// Set(2){NaN, 0}
  • Set 객체는 객체나 배열과 같이 자바스크립트의 모든 값을 요소로 저장할 수 있다.
const set = new Set();

set
	.add(1)
	.add('a')
	.add(true)
	.add(undefined)
	.add(null)
	.add({})
	.add([])
	.add(() => {});
console.log(set);// Set(8) {1,'a',true,undefined,null,{},[],()=>{}}

요소 존재 여부 확인

  • Set 객체에 특정 요소가 존재하는지 확인하려면 Set.prptptype.has 메서드를 사용한다.
  • has 메서드는 특정 요소의 존재 여부를 나타내는 불리언 값을 반환한다.
const set = new Set([1,2,3]);

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

요소 삭제

  • Set 객체의 특정 요소를 삭제하려면 Set.prototype.delete 메서드를 사용한다.
  • delete 메서드는 삭제 성공 여부를 나타내는 불리언 값을 반환한다.
  • delete 메서드는 불리언 값을 반환하기 때문에 add 메서드와 달리 연속적으로 호출할 수 없다.
const set = new Set([1,2,3]);

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

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

set.delete(0); //삭제하려는 요소가 존재하지 않으면 에러없이 무시됨
console.log(set); // Set(1) {3}

요소 일괄 삭제

  • Set 객체의 모든 요소를 일괄 삭제하려면 Set.prototype.clear 메서드를 사용한다.
  • clear 메서드는 언제나 undefined를 반환한다.
const set = new Set([1,2,3]);

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

요소 순회

  • Set 객체의 요소를 순회하려면 Set.prototype.forEach 메서드를 이용한다.
  • Array.prototype.forEach 메서드와 유사하게 콜백함수와 forEach 메서드의 콜백 함수 내부에서 this로 사용될 객체를 인수로 전달한다.
    • 첫 번째 인수: 현재 순회 중인 요소값
    • 두 번째 인수: 현재 순회 중인 요소값
    • 세 번째 인수: 현재 순회 중인 Set 객체 자체
  • 첫 번째 인수와 두 번째 인수의 값이 같은 이유는 Array.prototype.forEach와 인터페이스를 통일하기 위합이며 다른의미는 없다. (Set은 Array와 달리 index가 없기 때문에)
const set = new Set([1,2,3]);

set.forEach((v1,v2,set) => console.log(v1,v2,set));
/*
1 1 Set(3) {1,2,3}
2 2 Set(3) {1,2,3}
3 3 Set(3) {1,2,3}
*/
  • Set 객체는 이터러블이기 때문에 for...of문으로 순회할 수 있으며 스프레드 문법과 배열 디스트럭처링의 대상이 될 수도 있다.
const set = new Set([1,2,3]);
// Set 객체는 Set.prototype의 **33장 Symbol**.iterator 메서드를 상속받는 이터러블이다.
console.log(Symbol.iterator in set); //true

for(const value of set) {
 console.log(value); //1 2 3 
}

//이터러블이기 때문에 스프레드 문법의 대상이 됨
console.log([...set]); // [1,2,3]

//이터러블이기 때문에 배열 디스트럭처링 할당의 대상이 됨
const [a, ...rest] = set;
console.log(a,rest);//1,[2,3]

Set 객체는 요소의 순서에 의미를 갖지 않지만 Set 객체를 순회하는 순서는 요소가 추가된 순서를 따름
-> 다른 이터러블의 순회와 호환성을 유지하기 위해

집합 연산

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

집합 연산을 수행하는 프로토타입 메서드를 구현해보자

교집합

  • A∩B : 집합 A와 집합 B의 공통 요소로 구성됨
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)); //set(2){2,4}
console.log(setB.intersection(setA)); //set(2){2,4}
  • 다음과 같은 방법으로도 가능
Set.prototype.intersection = 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)); //set(2){2,4}
console.log(setB.intersection(setA)); //set(2){2,4}

합집합

  • A∪B는 집합 A와 집합 B의 중복없는 모든 요소로 구성됨
Set.prototype.union = function (set) {
 const result = new Set(this);
  
  for(const value of set){
    result.add(value);
  }
  return result;
}

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

console.log(setA.union(setB)); //set(4){1,2,3,4}
console.log(setB.union(setA)); //set(4){1,2,3,4}
  • 다음과 같은 방법으로도 가능
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)); //set(4){1,2,3,4}
console.log(setB.union(setA)); //set(4){1,2,3,4}

차집합

  • A-B : 집합 A에는 존재하지만 집합 B에는 존재하지 않는 요소로 구성
Set.prototype.difference = function (set) {
 const result = new Set(this);
  
  for(const value of set){
    result.delete(value);
  }
  return result;
}

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

console.log(setA.difference(setB)); //set(2){1,3}
console.log(setB.difference(setA)); //set(0){}
  • 다음과 같은 방법으로도 가능
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.difference(setB)); //set(2){1,3}
console.log(setB.difference(setA)); //set(0){}

부분 집합과 상위 집합

  • A⊆B : 집합 A가 집합 B에 포함되는 경우 집합 A는 집합 B의 부분 집합이며, 집합 B는 집합 A의 상위 집합이다.
Set.prototype.inSuperset = function (subset) {
 const result = new Set(this);
  
  for(const value of subset){
    if(!subset.has(value)) return false;
  }
  return result;
}

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

console.log(setA.inSuperset(setB)); //true
console.log(setB.inSuperset(setA)); //false
  • 다음과 같은 방법으로도 가능
Set.prototype.inSuperset = function (subset) {
  return [...subset].every(v => this.has(v))
}

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

console.log(setA.inSuperset(setB)); //true
console.log(setB.inSuperset(setA)); //false

37.2 Map

  • Map 객체는 키와 값의 쌍으로 이루어진 컬렉션
  • 객체와 유사하지만 차이가 있음

Map 객체의 생성

  • Map 객체는 Map 생성자 함수로 생성하며 인수를 전달하지 않으면 빈 Map 객체가 생성됨
const map = new Map();
console.log(map); // Map(0){}
  • Map 생성자 함수는 이터러블을 인수로 전달받아 Map 객체를 생성함
  • 이때 인수로 전달되는 이터러블은 키와 값의 쌍으로 이루어진 요소로 구성되어야 함
const map1 = new Map([['key1','value1'],['key2','value2']]);
console.log(map1); // Map(2) {'key1' => 'value1','key2' => 'value2'}

const map2 = new Map([1,2]); //TypeError: Iterator value 1 is not an entry object, key와 value로 구성된것이 아닌 단지 value만 나열되어있는 상태
const map2 = new Map([[1,2]]); //Map(1) { 1 => 2 }
  • Map 생성자 함수의 인수로 전달한 이터러블에 중복된 키를 갖는 요소가 존재하면 값은 덮어씌워져 중복된 키를 갖는 요소는 존재하지 않는다.
const map1 = new Map([['key1','value1'],['key1','value1']]);
console.log(map1); // Map(1) {'key1' => 'value1'}

요소 개수 확인

  • Map 객체의 요소 개수를 확인할 때는 Map.prototype.size 프로퍼티를 사용
const {size} = new Map([['key1','value1'],['key2','value2']]);
console.log(size);//2
  • size 프로퍼티는 setter함수 없이 getter 함수만 존재하는 접근자 프로퍼티이기 때문에 size 프로퍼티에 숫자를 할당해 Map 객체의 요소 개수를 변경할 수 없다.
const map = new Map([['key1','value1'],['key2','value2']]);
console.log(Object.getOwnPropertyDescriptor(Map.prototype,'size'))
/*{
  get: [Function: get size],
  set: undefined,
  enumerable: false,
  configurable: true
}*/
map.size = 10; //무시됨
console.log(map.size); //2

요소 추가

  • Map 객체에 요소를 추가할 때는 Map.prototype.set 메서드를 사용
const map = new Map();
console.log(map);// Map(0){}

map.set('key1','value1');
console.log(map);// Map(1) {'key1' => 'value1'}
  • set 메서드는 새로운 요소가 추가된 Map 객체를 반환하기 때문에 set 메서드를 연속으로 호출할 수 있다.
const map = new Map();

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

// 중복된 키를 갖는 요소를 추가하면 값이 덮어써지며 에러 발생은 하지 않는다.
map
  .set('key1','value1')
  .set('key1','value1');
console.log(map);// Map(2) {'key1' => 'value1','key2' => 'value2'}
  • Map 객체는 일치 비교 연산자와 다르게 NaN과 NaN을 같다고 평가하고 일치 비교 연산자와 같게 +0과 -0을 같다고 평가해 중복 추가를 허용하지 않는다.
const map = new Map();

console.log(NaN === NaN); // false
console.log(0 === -0); //true

map.set(NaN,'value1').set(NaN,'value2');
console.log(map);// Map(1){NaN => 'value2'}

map.set(0,'value1').set(-0,'value2');
console.log(map);// Map(2){NaN => 'value2', 0 => 'value1'}
  • 객체는 문자열 또는 심벌 값만 키로 사용할 수 있지만 Map 객체는 키 타입에 제한이 없기 때문에 객체를 포함한 모든 값을 키로 사용할 수 있다. Map 객체와 일반 객체의 가장 두드러지는 차이점이다.
const map = new Map();

const lee = {name:'Lee'};
const kim = {name:'Kim'};

map
	.set(lee,'developer')
	.set(kim,'desiner');

console.log(map); 
// Map(2){{name:'Lee'} => 'developer', {name:'Kim'} => 'desiner'}

요소 취득

  • Map 객체에서 특정 요소를 취득하려면 Map.prototype.get 메서드를 사용한다.
  • get 메서드의 인수로 키를 전달하면 Map 객체에서 인수로 전달한 키를 갖는 값을 반환하며 요소가 존재하지 않으면 undefined를 반환한다.
const map = new Map();

const lee = {name:'Lee'};
const kim = {name:'Kim'};

map
	.set(lee,'developer')
	.set(kim,'desiner');

console.log(map.get(lee)); // developer
console.log(map.get('key')); //undefined 

요소 존재 여부 확인

  • Map 객체에 특정 요소가 존재하는지 확인하려면 Map.prptptype.has 메서드를 사용한다.
  • has 메서드는 특정 요소의 존재 여부를 나타내는 불리언 값을 반환한다.
const lee = {name:'Lee'};
const kim = {name:'Kim'};

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

console.log(map.has(lee)); // true
console.log(map.has('key')); //false

요소 삭제

  • Map 객체의 특정 요소를 삭제하려면 Map.prototype.delete 메서드를 사용한다.
  • delete 메서드는 삭제 성공 여부를 나타내는 불리언 값을 반환한다.
  • delete 메서드는 불리언 값을 반환하기 때문에 add 메서드와 달리 연속적으로 호출할 수 없다.
const lee = {name:'Lee'};
const kim = {name:'Kim'};

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

map.delete(kim);
console.log(map); // Map(1) {{name:'Lee'} => 'developer'}

map.delete('key2'); //삭제하려는 요소가 존재하지 않으면 에러없이 무시됨
console.log(map); // Map(1) {{name:'Lee'} => 'developer'}

요소 일괄 삭제

  • Map 객체의 모든 요소를 일괄 삭제하려면 Map.prototype.clear 메서드를 사용한다.
  • clear 메서드는 언제나 undefined를 반환한다.
const lee = {name:'Lee'};
const kim = {name:'Kim'};

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

map.clear();
console.log(map); // Map(0) {}

요소 순회

  • Map 객체의 요소를 순회하려면 Map.prototype.forEach 메서드를 이용한다.
  • Array.prototype.forEach 메서드와 유사하게 콜백함수와 forEach 메서드의 콜백 함수 내부에서 this로 사용될 객체를 인수로 전달한다.
    • 첫 번째 인수: 현재 순회 중인 요소값
    • 두 번째 인수: 현재 순회 중인 요소키
    • 세 번째 인수: 현재 순회 중인 Map 객체 자체
const lee = {name:'Lee'};
const kim = {name:'Kim'};

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

map.forEach((v,k,map) => console.log(v,k,map));
/*
developer { name: 'Lee' } Map(2) { 
  { name: 'Lee' } => 'developer', 
  { name: 'Kim' } => 'desiner' 
}
desiner { name: 'Kim' } Map(2) { 
  { name: 'Lee' } => 'developer', 
  { name: 'Kim' } => 'desiner' 
}
*/
  • Map 객체는 이터러블이기 때문에 for...of문으로 순회할 수 있으며 스프레드 문법과 배열 디스트럭처링의 대상이 될 수도 있다.
const lee = {name:'Lee'};
const kim = {name:'Kim'};

const map = new Map([[lee,'developer'],[kim,'desiner']]);
// Map 객체는 Map.prototype의 **33장 Symbol**.iterator 메서드를 상속받는 이터러블이다.
console.log(Symbol.iterator in map); //true

for(const entry of map){
 console.log(entry); 
  // [{ name: 'Lee' } => 'developer'] 
  // [{ name: 'Kim' } => 'desiner'] 
}
//이터러블이기 때문에 스프레드 문법의 대상이 됨
console.log([...map]); 
// [[{ name: 'Lee' } => 'developer'] ,[{ name: 'Kim' } => 'desiner']]

//이터러블이기 때문에 배열 디스트럭처링 할당의 대상이 됨
const [a, b] = map;
console.log(a,b);
//[{ name: 'Lee' } => 'developer'] [{ name: 'Kim' } => 'desiner']
  • Map 객체는 이터러블이면서 동시에 이터레이터인 객체를 반환하는 메서드를 제공함
    • Map.prototype.keys : Map 객체에서 요소키를 값으로 갖는 이터러블이면서 동시에 이터레이터인 객체를 반환
    • Map.prototype.values : Map 객체에서 요소값을 값으로 갖는 이터러블이면서 동시에 이터레이터인 객체를 반환
    • Map.prototype.entries : Map 객체에서 요소키와 요소값을 값으로 갖는 이터러블이면서 동시에 이터레이터인 객체를 반환
const lee = {name:'Lee'};
const kim = {name:'Kim'};

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

for(const key of map.keys()){
 console.log(key); //  { name: 'Lee' } { name: 'Kim' }
}
for(const value of map.values()){
 console.log(value); //  'developer' 'desiner'
}
for(const entry of map.entries()){
 console.log(entry); 
  //  [{ name: 'Lee' } => 'developer'] [{ name: 'Kim' } => 'desiner']
}

Map 객체는 요소의 순서에 의미를 갖지 않지만 Map 객체를 순회하는 순서는 요소가 추가된 순서를 따름
-> 다른 이터러블의 순회와 호환성을 유지하기 위해