Set / 집합
February 19, 2020
Set / 집합
-
정의
- 정렬되지 않은 컬렉션으로 원소는 반복되지 않는다.
- 정렬 개념이 없는, 원소가 중복되지 않는 배열
- 사용처 : 합집합, 교집합, 차지합
-
기능
- add(item) : 원소 추가
- remove(item) : 원소 삭제
- has(item) : 원소 포함 여부
- clear() : 모든 원소 삭제
- size() : 원소 갯수 반환(length)
- values() : 집한의 모든 원소를 배열 형태로 반환
-
코드 구현
function Set(){ let items = {}; this.has = function(value){ return value in items; //return items.hasOwnProperty(value); } this.add = function(value){ if(!this.has(value)){ items[value] = value; // 키와 값을 동일하게 저장(값을 찾을때 유용) return true; } return false; } this.remove = function(value){ if(this.has(value)){ delete items[value]; return true; } return false; } this.clear = function(){ items = {}; } this.size = function(){ return Object.keys(items).length; // Object.keys() 메소드는 배열로 반환 } this.value = function(){ return Object.keys(items); } // Object,keys()가 explore v8 에서 작동이 안되기 때문에 아래 처럼 구현 this.sizeLegacy = function(){ let count = 0; for(let item in items){ if(items.hasOwnProperty(item)){ ++count; } } return count } this.valueLegacy = function(){ let keys = []; for(let item in items){ keys.push(item) } return keys } }
-
합집합
this.union = function(otherSet){ const unionSet = new Set(); let values = this.values(); for(let i = 0; i < values.length; i++){ unionSet.add(values[i]); } values = otherSet.values(); for(let i = 0; i < values.length; i++){ unionSet.add(values[i]); } return unionSet; }
-
교집합
this.intersection = function(otherSet){ const intersectionSet = new Set(); let values = this.values(); for(let i = 0; i < values.length; i++){ if(otherSet.has(values[i])){ intersectionSet.add(values[i]) } } return intersectionSet }
-
차집합
this.defference = function(otherSet){ const defferenceSet = new Set(); let values = this.values(); for(let i = 0; i < values.length; i++){ if(!otherSet.has(values[i])){ defferenceSet.add(values[i]) } } return defferenceSet }
-
부분집합
this.subSet = function(otherSet){ if(this.size() > otherSet.size()){ return false; } else { let values = this.values(); for(let i = 0; i < values.length; i++){ if(!otherSet.has(values[i])){ return false; } } return true; } }
-