-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Iteration Protocol #29
Comments
Iteration Protocol
Iterable
Iterable ๊ฐ์ฒด๋ก๋ ๋ด์ฅ ๊ฐ์ฒด์ธ const iterator = [1, 2, 3][Symbol.iterator]();
iterator.next().value; // 1
iterator.next().value; // 2
iterator.next().value; // 3
iterator.next().done; // true ๋ฐ๋ฉด, ์ผ๋ฐ ๊ฐ์ฒด๋ const obj = { a: 1, b: 2 };
console.log(Symbol.iterator in obj); // false
// TypeError: obj is not iterable
for (const item of obj) {
console.log(item);
} ํ์ง๋ง ์ผ๋ฐ ๊ฐ์ฒด๋ const iterableObj = function (max) {
let i = 0;
return {
[Symbol.iterator]() {
return {
next() {
return {
value: ++i,
done: i === max
};
}
};
}
};
};
const iterator = iterableObj(10);
for (let item of iterator) {
console.log(item);
} Iterator
์์์ ์ ๊น ๋ดค๋ ์ฝ๋์ ์ผ๋ถ๋ถ์ ๋ค์ ํ ๋ฒ ์ดํด๋ณด์. [Symbol.iterator]() {
return {
next() {
return {
value: ++i,
done: i === max
};
}
};
}
const array = [1, 2, 3];
const iterator = array[Symbol.iterator]();
console.log('next' in iterator); // true
iterator.next().value; // 1
iterator.next().value; // 2
iterator.next().value; // 3
iterator.next(); // { value: undefined, done: true } Iterator ๊ฐ์ฒด์ Iteration Protocol์ด ์ ํ์ํ ๊น?
๋ง์ฝ, ์์ ๊ฐ์ Data Provider์ธ Iterable ๊ฐ์ฒด๋ค์ด ๊ฐ๊ฐ ๋ค๋ฅธ ๋ฐฉ์์ ์ํ ๋ฐฉ์์ ๊ฐ๋๋ค๋ฉด ์ด๋จ๊น? ๋น์ฐํ ํจ์จ์ ์ด์ง ๋ชปํ๋ค. ์ํ ๋ฐฉ์์ ๋ํ ํ๋์ ๊ท์ฝ์ ์ ํด๋๊ณ ์ฌ์ฉํ๋ค๋ฉด Data Consumer๊ฐ ์ฌ๋ฌ ๊ตฌ์กฐ์ Iterable์ ํจ์จ์ ์ผ๋ก ์ฌ์ฉํ ์ ์์ ๊ฒ์ด๋ค. ์ฆ, Iteration Protocol์ Data Consumer์ Data Provider๋ฅผ ์ฐ๊ฒฐํ๋ ์ธํฐํ์ด์ค ์ญํ ์ ํด์ฃผ๊ธฐ ๋๋ฌธ์ ํ์ํ๋ค๊ณ ๋ณผ ์ ์๋ค. |
๐ Reference
The text was updated successfully, but these errors were encountered: