Iterator.prototype.take()
Baseline
2025
Newly available
Since โจMarch 2025โฉ, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Experimental: ์ด ๊ธฐ๋ฅ์ ์คํ์ ์ธ ๊ธฐ๋ฅ์
๋๋ค.
ํ๋ก๋์
ํ๊ฒฝ์์ ์ฌ์ฉํ๊ธฐ ์ ์ ๋ธ๋ผ์ฐ์ ํธํ์ฑ ํ๋ฅผ ์ฃผ์ ๊น๊ฒ ํ์ธํ์ธ์.
Iterator
์ธ์คํด์ค์ take()
๋ฉ์๋๋ ์ด ๋ฐ๋ณต์์์ ์ฃผ์ด์ง ์ซ์๋งํผ์ ์์๋ฅผ ์ฐ์ถํ๊ณ ์ข
๋ฃํ๋ ์๋ก์ด ๋ฐ๋ณต์ ํฌํผ๋ฅผ ๋ฐํํฉ๋๋ค.
๊ตฌ๋ฌธ
take(limit)
๋งค๊ฐ๋ณ์
limit
-
์ํ ์์์ ๋ถํฐ ์ทจํ ์์์ ์.
๋ฐํ ๊ฐ
์๋ก์ด ๋ฐ๋ณต์ ํฌํผ๋ฅผ ๋ฐํํฉ๋๋ค. ๋ฐํ๋ ๋ฐ๋ณต์ ํฌํผ๋ ์๋ ๋ฐ๋ณต์์ ์์๋ค์ ํ๋์ฉ ์ฐ์ถํ๊ณ , limit
๊ฐ์๋งํผ์ ์์๊ฐ ์ฐ์ถ๋์๊ฑฐ๋ ์๋ ๋ฐ๋ณต์๊ฐ ์์ง๋์์ ๋, ๋ ์ค ๋จผ์ ๋ฐ์ํ๋ ๊ฒฝ์ฐ ์๋ฃ๋ฉ๋๋ค (next()
๋ฉ์๋๊ฐ { value: undefined, done: true }
๋ฅผ ์์ฑํฉ๋๋ค).
์์ธ
RangeError
-
์ ์๋ก ๋ณํ์
limit
๊ฐNaN
๋๊ฑฐ๋ ์์์ผ ๊ฒฝ์ฐ์ ๋ฐ์ํฉ๋๋ค.
์์
take() ์ฌ์ฉํ๊ธฐ
๋ค์ ์์ ๋ ํผ๋ณด๋์น ์์ด์ ํญ์ ์์ฑํ๋ ๋ฐ๋ณต์๋ฅผ ๋ค๊ณ , ์ฒ์ ์ธ ํญ์ ์ถ๋ ฅํฉ๋๋ค.
function* fibonacci() {
let current = 1;
let next = 1;
while (true) {
yield current;
[current, next] = [next, current + next];
}
}
const seq = fibonacci().take(3);
console.log(seq.next().value); // 1
console.log(seq.next().value); // 1
console.log(seq.next().value); // 2
console.log(seq.next().value); // undefined
for...of ๋ฃจํ์ ๊ฐ์ด take() ์ฌ์ฉํ๊ธฐ
take()
์ ๋ฐ๋ณต์๋ฅผ ์ง์ ์ด๋์ํค์ง ์์ ๋ ๊ฐ์ฅ ํธ๋ฆฌํฉ๋๋ค. ๋ฐ๋ณต์๋ ์ํ ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์, ๋ฐํ๋ ํฌํผ๋ฅผ for...of
๋ฃจํ๋ก ๋ฐ๋ณตํ ์ ์์ต๋๋ค.
for (const n of fibonacci().take(5)) {
console.log(n);
}
// Logs:
// 1
// 1
// 2
// 3
// 5
fibonacci()
๋ ๋ฌดํ ๋ฐ๋ณต์์ด๊ธฐ ๋๋ฌธ์ ์ง์ ์ ์ผ๋ก ์ํ์ํค๊ธฐ ์ํด for
๋ฃจํ๋ฅผ ์ฌ์ฉํ ํ์๊ฐ ์์ต๋๋ค.
drop()๊ณผ take() ๊ฒฐํฉํ๊ธฐ
๋ฐ๋ณต์์ ์ผ๋ถ๋ฅผ ์ป๊ธฐ ์ํด take()
๊ณผ Iterator.prototype.drop()
์ ๊ฐ์ด ์ฌ์ฉํ ์ ์์ต๋๋ค.
for (const n of fibonacci().drop(2).take(5)) {
// ์ฒซ ๋ ๊ฐ์ ์์๋ฅผ ๋ฒ๋ฆฌ๊ณ , ๋ค์ 5๊ฐ๋ฅผ ์ทจํฉ๋๋ค
console.log(n);
}
// ๋ก๊ทธ:
// 2
// 3
// 5
// 8
// 13
for (const n of fibonacci().take(5).drop(2)) {
// ์ฒ์ 5๊ฐ๋ฅผ ์ทจํ๊ณ , ์ฒ์ 2๊ฐ๋ฅผ ๋ฒ๋ฆฝ๋๋ค
console.log(n);
}
// ๋ก๊ทธ:
// 2
// 3
// 5
take ๊ฐฏ์์ ์๋จ๊ณผ ํ๋จ
limit
๊ฐ ์์๊ฑฐ๋ NaN
์ผ ๊ฒฝ์ฐ RangeError
๊ฐ ๋ฐ์ํฉ๋๋ค.
fibonacci().take(-1); // RangeError: -1 must be positive
fibonacci().take(undefined); // RangeError: undefined must be positive
limit
๊ฐ ๋ฐ๋ณต์๊ฐ ์์ฑํ ์ ์๋ ์ด ์์ ์๋ณด๋ค ํฐ ๊ฒฝ์ฐ(Infinity
์ ๊ฐ์ด), ๋ฐํ๋ ๋ฐ๋ณต์ ํฌํผ๋ ๊ธฐ๋ณธ์ ์ผ๋ก ์๋ ๋ฐ๋ณต์์ ๊ฐ์ด ํ๋ํฉ๋๋ค.
for (const n of new Set([1, 2, 3]).values().take(Infinity)) {
console.log(n);
}
// ๋ก๊ทธ:
// 1
// 2
// 3
๋ช ์ธ์
Specification |
---|
ECMAScriptยฎ 2026 Language Specification # sec-iterator.prototype.take |
๋ธ๋ผ์ฐ์ ํธํ์ฑ
Loadingโฆ