The Bong'

javascript에서 Set과 string

2022-08-14 at javascript category

leetcode의 문제를 풀던 중 set에 대한 이해부족으로 확인한것을 정리해본다.

Set : 중복을 허용하지 않는 값의 모임

const set = new Set();
set.add(1);
set.add(2);
set.add(3);

set.add(1);
set.add(2);
set.add(3);

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

1, 2, 3을 반복적으로 set에 넣어도 중복을 허용하지 않으니 1, 2, 3만 저장된다.
set에 관한 글은 다른곳에서도 잘 다루어진 글이 많으니 여기까지 보고,


Set의 생성자

위에 코드에서 생성자 new Set()에 파라미터로 값을 전달 할 수 있다.

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

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

각각 add했던것과 결과가 같다.
그런데, 여기에 string값을 넣으면 어찌 될까?

const str = 'bong';
const set = new Set();
set.add(str);
const setWithConstructor = new Set(str);

console.log(set); // Set(1) {'bong'}
console.log(setWithConstructor); //Set(4) {'b', 'o', 'n', 'g'}

둘의 결과가 다르다.
아직 무엇이 문제인지는 모르겠지만, 생성자와 add가 다른 기능을 하나? 라는 의심을 먼저 해볼 수 있을테니 공식문서를 봐보자.


iterable

Set관련 공식문서에서는 Set의 문법을 아래와 같이 정의하고 있다.

Syntax

new Set()
new Set(iterable)

cf. add

Syntax
add(value)

즉, 생성자에 값을 전달 안 할수도 있으며, 값을 전달한다면 iterable을 전달해야 하는 것이다.
add함수는 을 전달하는 것이다.

const set1 = new Set([1, 2, 3]); // Ok
const set2 = new Set(['b', 'o', 'n', 'g']); // Ok
const set3 = new Set(123); // Fail > number 123 is not iterable

String은 iterable

위에 확인한것들을 토대로 공식문서를 보거나 검색하지 않아도 iterable하다는 것을 알 수 있다.
그럼 당연히

const str = 'bong';
const number = 123;

console.log(typeof str[Symbol.iterator]) // function
console.log(typeof number[Symbol.iterator]) // undefined

for(const s of str) console.log(s); // b o n g

위의 결과가 될 것이다.


결과적으로... 문자열을 그대로 넣고 싶으면 add
각각 넣고 싶으면 생성자에

이제 다시 위에서 봤던 코드를 다시 봐보자.

const str = 'bong';
const set = new Set();
set.add(str);
const setWithConstructor = new Set(str);

console.log(set); // Set(1) {'bong'}
console.log(setWithConstructor); //Set(4) {'b', 'o', 'n', 'g'}

위의 결과값들이 이해가 될 것이고, split한 자료의 형태를 원한다면 생성자에 문자열 그대로 넣고싶다면 add에 넣으면 된다는것을 알 수 있다.

Bong

Personal blog by Bong.

Sr. Developer / Interested in Functional JAVA, AWS, SQL Tunning