Iterator.prototype.take()
The take()
method of Iterator
instances returns a new iterator helper that yields the given number of elements in this iterator and then terminates.
Parameters
-
limit
-
The number of elements to take from the start of the iteration.
Return value
A new iterator helper. The returned iterator helper yields the elements in the original iterator one-by-one, and then completes (the next()
method produces { value: undefined, done: true }
) once limit
elements have been yielded, or when the original iterator is exhausted, whichever comes first.
Using take()
The following example creates an iterator that yields terms in the Fibonacci sequence, and then logs the first three terms:
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);
console.log(seq.next().value);
console.log(seq.next().value);
console.log(seq.next().value);
Using take() with a for...of loop
take()
is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a for...of
loop:
for (const n of fibonacci().take(5)) {
console.log(n);
}
Because fibonacci()
is an infinite iterator, you can't use a for
loop to iterate it directly.
Combining drop() with take()
You can combine drop()
with Iterator.prototype.take()
to get a slice of an iterator:
for (const n of fibonacci().drop(2).take(5)) {
console.log(n);
}
for (const n of fibonacci().take(5).drop(2)) {
console.log(n);
}
Lower and upper bounds of take count
When the limit
is negative or NaN
, a RangeError
is thrown:
fibonacci().take(-1);
fibonacci().take(undefined);
When the limit
is larger than the total number of elements the iterator can produce (such as Infinity
), the returned iterator helper has essentially the same behavior as the original iterator:
for (const n of new Set([1, 2, 3]).values().take(Infinity)) {
console.log(n);
}
Specifications
Browser compatibility
|
Desktop |
Mobile |
Server |
|
Chrome |
Edge |
Firefox |
Opera |
Safari |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
WebView Android |
Deno |
Node.js |
take |
117 |
117 |
No |
103 |
No |
117 |
No |
78 |
No |
No |
117 |
No |
No |