: 정렬되지 않은 컬렉션이다.
: 중복된 원소를 포함하지 않는다.
: 집합은 합집밥, 교집합, 차집합 같은 수학적 연산도 가능하다.
function Set(){
var items = {};
}
add(원소) : 원소를 추가한다.
remove(원소) : 원소를 삭제한다.
has(원소) : 어떤 원소가 집합에 포함되어 있는지 여부를 true, false로 반환한다.
clear() : 모든 원소를 삭제한다.
size() : 원소 개수를 반환한다. 배열의 length와 비슷하다.
values() : 집합의 모든 원소를 배열형태로 반환한다.
//방법1
this.has = function(value){
return value in items;
}
//방법2
this.has = function(value){
retrun 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]; //delete연산자 사용
return true;
}
return false;
}
this.clear = function(){
items {};
}
Object에는 key라는 메소드가 있는데, 객체의 모든 property를 배열로 반환한다.
따라서, 이 배열의 length로 원소개수를 파악할 수 있다.
this.size = function()}{
return Object.keys(items).length;
}
this.values = function(){
return Object.keys(items);
}
이미지 클릭시 이미지 출처로 이동합니다.
this.union = function(otherSet){
var unionSet = new Set(); //합집합 생성
var values = this.values(); //첫번째집합의 모든 value를 추출
for(var i=0; i<values.length; i++){ //합집합에 value를 추가
unionSet.add(values[i]);
}
values = otherSet.value(); //두번째집합의 모든 value를 추출
for(var i=0; i<values.length; i++){ //합집합에 value를 추가
unionSet.add(values[i]);
}
return unionSet;
};
이미지 클릭시 이미지 출처로 이동합니다.
this.intersection = function(otherSet){
var intersectionSet = new Set(); //교집합 생성
var values = this.value(); //첫번째 집합의 모든 value추출
for(var i=0; i<values.length; i++){
if(otherSet.has(values[i])){ //다른집합에 같은 값이 있다면?
intersectionSet.add(values[i]); //교집합에 해당 값 추가
}
}
return intersectionSet;
}
이미지 클릭시 이미지 출처로 이동합니다.
this.difference = function(otherSet){
var differentSet = new Set(); //차집합 생성
var values = this.values(); //첫번째 집합의 값 추출
for(var i=0; i<values.length; i++){
if(!otherSet.has(values[i])){ //두번째 집합에 해당 값이 없다면
differentSet.add(values[i]); //차집합에 추가
}
}
return differenceSet;
}
이미지 클릭시 이미지 출처로 이동합니다.
this.subset = function(otherSet){
//두 집합의 크기를 비교
//만약 this가 otherSet보다 원소가 맞다면, 이미 부분집합 조건이 아님
if(this.size() > otherSet.size()){
return false;
}
else{
var values = this.values(); //this의 values 추출
for(var i=0; i<values.length; i++){
if(!otherSet.has(values[i])){ //otherSet이 this의 값이 없다면 false
return false;
}
}
return true;
}
}