Iterable
Iterable이란 객체가 Symbol.iterator 속성을 가지고 있고, 이 속성이 next 메소드를 반환해야 합니다. 이러한 것을 Iterable Protocol을 만족 한다고 표현합니다.
즉, Iterable이란, Iterable Protocol을 만족하는 객체를 말합니다.
아래에 Iterable Protocol을 만족하는 객체의 예시를 보여드리겠습니다.
const iterable = {
[Symbol.iterator]() {
let i = 0;
return {
next() {
return {
value: i++,
done: i > 3,
};
},
};
},
};그리고 이 Iterable 객체는 아래와 같은 특징을 가집니다.
for...of구문을 통해 순회할 수 있습니다.
for (const value of iterable) {
console.log(value);
}
// 0
// 1
// 2Spread Syntax를 통해 배열로 변환할 수 있습니다.
const arr = [...iterable];
console.log(arr); // [0, 1, 2]Destructuring을 통해 배열로 변환할 수 있습니다.
const [a, b, c] = iterable;
console.log(a, b, c); // 0 1 2Array.from메소드를 통해 배열로 변환할 수 있습니다.
const arr = Array.from(iterable);
console.log(arr); // [0, 1, 2]Set생성자를 통해 Set 객체로 변환할 수 있습니다.
const set = new Set(iterable);
console.log(set); // Set { 0, 1, 2 }Map생성자를 통해 Map 객체로 변환할 수 있습니다.
const map = new Map([
[0, 'a'],
[1, 'b'],
[2, 'c'],
]);
console.log(map); // Map { 0 => 'a', 1 => 'b', 2 => 'c' }Promise.all메소드를 통해 Promise 객체로 변환할 수 있습니다.
const promise = Promise.all(iterable);
console.log(promise); // Promise { <pending> }- …
javascript의 Generator
Generator는 Iterable Protocol을 만족하는 객체를 생성하는 함수입니다. Generator 함수는 function* 키워드를 사용하여 정의하며, 함수 내부에서 yield 키워드를 사용하여 값을 반환합니다.
아래에 Generator 함수의 예시를 보여드리겠습니다.
function* generator() {
yield 0;
yield 1;
yield 2;
}
const iterable = generator();그리고 이 Generator 함수는 아래와 같은 특징을 가집니다.
for...of구문을 통해 순회할 수 있습니다.
for (const value of iterable) {
console.log(value);
}
// 0
// 1
// 2Spread Syntax를 통해 배열로 변환할 수 있습니다.
const arr = [...iterable];
console.log(arr); // [0, 1, 2]Destructuring을 통해 배열로 변환할 수 있습니다.
const [a, b, c] = iterable;
console.log(a, b, c); // 0 1 2Array.from메소드를 통해 배열로 변환할 수 있습니다.
const arr = Array.from(iterable);
console.log(arr); // [0, 1, 2]- … 위에서 Iterable 객체의 특징과 동일합니다.