본문 바로가기
프로그래밍 개발/JS ES6+

Javascript ES6+ Set

by Jinseok Kim 2020. 12. 16.
반응형

 

 

 

 

 

 

set

 

 

 

Array.prototype.pushUnique = value =>{
    if(!this.include(value)){
        this.push(value)
    }
}return this
const arr = [1, 2, 3]
arr.pushUnique(5)
arr.pushUnique(4)
arr.pushUnique(3)
console.log(arr)

//결과: arr(5) {1, 2, 3, 5, 4}

/////

const set = new Set([1,2,3])
set.add(5)
set.add(4)
set.add(3)
console.log(set)

//결과:Set(5) {1, 2, 3, 5, 4}

 

  • set은 중복이 허용되지 않으며 순서를 보장하는, 값들로만 이루어진 리스트를 만드는 역할을 한다. 
  • 위의 결과를 보면 아주 간단하게 중복된 값을 제외하고 리스트를 만들어 주는 것을 확인 할 수있다.

 

 

 

 

 

 

다양한 메소드를 이용하여 추가, 삭제, 초기화, 요소의 총 개수, 포함여부 확인 할 수 있다.

 

const set = new Set()
set.add(5)
set.add('5')
set.add(-0)
set.add(+0)

console.log(set.size) // 결과:3 (set 리스트의 값 갯수 알아낸다.)


console.log(set.has(5)) //결과: true (set리스트에 5의 값이 존재하는지 확인한다.)
console.log(set.has(6)) //결과: false(set리스트에 6의 값이 존재하는지 확인한다.)

set.delete(5)
console.log(set.has(5)) //결과: false (set리스트에 5의 값이 삭제한다.)

set.clear()
console.log(set.size) //결과: 0
console.log(set) // 결과: Set(0) {} (set의 값 모두 초기화시킨다.)

 

 

 

 

 

 

 

인자로 iterable한 개체를 지정할 수 있다.

 

const set1 =new Set([1, 2, 3, 4, 5, 3, 4, 2])
console.log(set1)

const map = new Map()
map.set('a', 1).set('b',2).set({},3)
const set2 = new Set(map)
console.log(set2)

//결과:
//Set(5) {1, 2, 3, 4, 5}
//Set(3) {Array(2), Array(2), Array(2)}

 

const gen = function* () {
    for (let i=0; i<5; i++){
        yield i+1
    }
}
const set = new Set(gen())
console.log(set)

//결과: Set(5) {1, 2, 3, 4, 5}

 

 

 

 

 

 

 

 

하지만 set으로 만든 리스트는 인덱스(키)가 없다는 사실이 있다.

즉 keys, values, entries가 모두 똑같은 결과를 도출한다.

 

set.forEach(function(key, value, ownerSet) {
  console.log(key, value, this)
}, {})

console.log(set[1])

//결과:
//1 1 {}
//2 2 {}
//3 3 {}
//4 4 {}
//5 5 {}
console.log(set.keys())
console.log(set.values())
console.log(set.entries())

console.log(...set.keys())
console.log(...set.values())
console.log(...set.entries())

// 결과:
// SetIterator {1, 2, 3, 4, 5}
// SetIterator {1, 2, 3, 4, 5}
// SetIterator {1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5}
// 1 2 3 4 5
// 1 2 3 4 5
// (2) [1, 1] (2) [2, 2] (2) [3, 3] (2) [4, 4] (2) [5, 5]

 

 

 

 

 

 

 

set을 이용한 배열로 전환하기

 

const set = new Set([1, 2, 3, 3, 4, 4, 5, 5, 1])
const arr = [...set]
console.log(arr)

//결과:
//[1, 2, 3, 4, 5]

 

const makeUniqueArray = arr => [...new Set(arr)] //(여기서 Set으로 중복처리)
const arr = [1, 2, 3, 3, 4, 4, 5, 5, 1]

const newArr = makeUniqueArray(arr)
console.log(newArr)

//결과:
//[1, 2, 3, 4, 5]

 

 

 

 

 

 

 

 

Weakset

 

 

  • set에 객체를 저장할 경우 set에도 해당 객체에 대한 참조가 연결되어, 여타의 참조가 없어지더라도 set에는 객체가 여전히 살아있다.
  • 하지만 WeakSet은 객체에 대한 참조카운트를 올리지 않아, 여타의 참조가 없어질 경우 WeakSet 내의 객체는 G.C의 대상이 됨.

 

const obj2 = { b: 2 }
const wset = new WeakSet()
wset.add(obj2)
obj2 = null

//결과: 오류

 

활용사례가 아직 많지 않다. 아래 사례의 코드가 존재할 뿐이다.

const isMarked = new WeakSet()
const attachedData = new WeakMap()

class Node {
    constructor (id){
      this.id=id  
    }
mark(){isMarked.add(this)}
unmark(){isMarked.delete(this)}
set data (data) {attachedData.set(this, data)}
get data () {return attachedData.get(this)}      
}
let foo = new Node('foo')
foo.mark()
foo.data = 'bar'
console.log(foo.data)

isMarked.has(foo)
attachedData.has(foo)

foo =null

isMarked.has(foo)
attachedData.has(foo)

//결과:
//bar
//false

 

  •  for ... of 사용 불가
  • size 프로퍼티 없음
  • wset.keys(), wset.values(), wset.entries() 등 사용 불가
  • 즉 iterable이 아니다

 

 

 

 

반응형

'프로그래밍 개발 > JS ES6+' 카테고리의 다른 글

Javascript ES6+ Iterable  (0) 2020.12.18
Javascript ES6+ Map  (0) 2020.12.16
Javascript ES6+ 심볼(Symbol)  (0) 2020.12.15
Javascript ES6+ Destructuring assignment  (0) 2020.12.14
Javascript ES6+ Function 함수  (0) 2020.12.14

댓글