Sub topic 7
Skipping Values with drop
This chapter assumes you can create an iterator with .values() or a generator function, and that you have seen map, filter, and take in earlier chapters. You should also know that toArray() collects whatever a pipeline produces into an array.
drop(limit) returns a new iterator that skips the first limit values of the source and then passes every remaining value through unchanged. It is the counterpart of take. take keeps a prefix, and drop discards one.
The Basic Behavior
const rest = [10, 20, 30, 40, 50].values().drop(2).toArray();
console.log(rest); // [30, 40, 50]The array iterator yields five values. drop(2) throws away 10 and 20, then forwards 30, 40, and 50 to toArray().
If the source has fewer values than you ask to skip, the result is empty. No error is thrown:
console.log([1, 2].values().drop(5).toArray()); // []
console.log([1, 2].values().drop(0).toArray()); // [1, 2]drop(0) is valid and skips nothing. That is useful when the skip count comes from a variable that can be zero.
When the Skipping Actually Happens
Like the other helpers, drop is lazy. Calling drop(3) does not touch the source at all. The skipping happens inside the first next() call on the helper. That call pulls and discards limit values, then pulls one more and returns it.
function* source() {
for (let i = 1; i <= 5; i++) {
console.log('produce', i);
yield i;
}
}
const rest = source().drop(3);
console.log('created');
console.log(rest.next());
console.log(rest.next());
// created
// produce 1
// produce 2
// produce 3
// produce 4
// { value: 4, done: false }
// produce 5
// { value: 5, done: false }The first next() does four pulls on the generator. Every later next() does exactly one. Once the skip count has been used up, drop behaves like a plain pass-through.
Dropped Values Are Still Produced
Skipping a value does not avoid computing it. The source still runs once for each dropped item, along with every helper placed before drop in the chain. drop has no way to jump ahead. All it can do is ask for values and ignore them.
That means the position of drop in a pipeline affects how much work runs:
let calls = 0;
const a = [1, 2, 3, 4, 5].values()
.map((x) => { calls++; return x * 10; })
.drop(3)
.toArray();
console.log(a, calls); // [40, 50] 5
calls = 0;
const b = [1, 2, 3, 4, 5].values()
.drop(3)
.map((x) => { calls++; return x * 10; })
.toArray();
console.log(b, calls); // [40, 50] 2Both pipelines give the same output. In the first one, map runs on all five values, including the three that drop then throws away. In the second, map only runs on the two values that survive. When the skip count refers to positions in the original source, put drop as early as possible.
The order also changes the meaning when filter is involved. filter(f).drop(2) skips the first two values that pass the filter. drop(2).filter(f) skips the first two source values and then filters what remains. Choose the order based on which count you mean.
const isEven = (n) => n % 2 === 0;
const nums = () => [1, 2, 3, 4, 5, 6, 7, 8].values();
console.log(nums().filter(isEven).drop(2).toArray()); // [6, 8]
console.log(nums().drop(2).filter(isEven).toArray()); // [4, 6, 8]Common Uses
Skipping a Header
A common case is ignoring the first line or lines of some input:
const csv = 'name,age\nAda,36\nAlan,41';
const rows = csv
.split('\n')
.values()
.drop(1)
.map((line) => line.split(','))
.toArray();
console.log(rows); // [['Ada', '36'], ['Alan', '41']]Paging with drop and take
Combining drop and take gives you a window into a sequence. This works even when the sequence is infinite, because take stops the pull once the page is full:
function* naturals() {
let n = 0;
while (true) yield n++;
}
function page(iter, pageIndex, pageSize) {
return iter.drop(pageIndex * pageSize).take(pageSize).toArray();
}
console.log(page(naturals(), 2, 5)); // [10, 11, 12, 13, 14]The earlier items are never stored in an array. They are still generated, though. Reading page 1000 walks through 5000 values first. A generator that does expensive work per value, such as a network request, pays that cost for every skipped item. If your source supports a real offset (a database OFFSET, an array index, a cursor), use it instead of drop for deep pages.
How the Limit Is Interpreted
drop converts its argument to a number and truncates it to an integer before checking it. That check runs as soon as you call drop, not when values are pulled. The chapter on argument validation covers this in more detail. The table shows the practical results:
| Call | Effective skip | Result |
|---|---|---|
| `drop(0)` | 0 | Passes everything through |
| `drop(2.9)` | 2 | Fractions are truncated toward zero |
| `drop('3')` | 3 | Numeric strings are converted |
| `drop(Infinity)` | all | Skips every value |
| `drop(-1)` | none | Throws `RangeError` immediately |
| `drop()` or `drop(NaN)` | none | Throws `RangeError` immediately |
try {
[1, 2, 3].values().drop();
} catch (e) {
console.log(e instanceof RangeError); // true
}Calling drop() with no argument is an error. It does not default to 0. If a missing count should mean "skip nothing", write drop(count ?? 0).
Closing Behavior
If the source runs out while drop is still skipping, the helper simply reports done: true. When a consumer stops early, for example with break in a for...of loop or because a later take reached its limit, the helper forwards return() to the source. A generator's finally block therefore still runs. The chapter on early termination covers this in detail.
function* source() {
try {
yield* [1, 2, 3, 4, 5];
} finally {
console.log('cleanup');
}
}
for (const x of source().drop(2)) {
console.log(x);
if (x === 3) break;
}
// 3
// cleanupSummary
drop(n)skips the firstnvalues and passes the rest through unchanged.- The skipping runs during the first
next()call, not whendropis called. - Skipped values are still produced by the source and by any helpers before
drop, so placedropearly when you can. droptogether withtakegives you windows and pages, but deep pages cost time proportional to the offset.- Negative,
NaN, or missing limits throwRangeErrorright away.Infinityskips everything.
Exercise
What does this code print, and how many times does the map callback run? [5, 6, 7, 8, 9].values().map((x) => x + 1).drop(2).take(2).toArray()
Show answer
It prints [8, 9]. The map callback runs 4 times: twice for the values drop discards (5 and 6, which become 6 and 7) and twice for the values take keeps (7 and 8, which become 8 and 9). After take reaches its limit, it closes the pipeline, so 9 is never mapped.
Exercise
Given const isOdd = (n) => n % 2 === 1;, what do [1, 2, 3, 4, 5, 6, 7].values().filter(isOdd).drop(1).toArray() and [1, 2, 3, 4, 5, 6, 7].values().drop(1).filter(isOdd).toArray() return?
Show answer
The first returns [3, 5, 7], because the filter keeps [1, 3, 5, 7] and drop then skips 1. The second returns [3, 5, 7] as well. drop removes the source value 1, leaving [2, 3, 4, 5, 6, 7], and the filter keeps [3, 5, 7]. The two results match only because the first source value happens to be odd. With drop(2) they differ: [5, 7] versus [3, 5, 7].
Exercise
A function calls naturals().drop(limit) where limit comes from user input and may be undefined. What goes wrong, and how do you fix it?
Show answer
drop(undefined) converts the argument to NaN and throws a RangeError as soon as drop is called. Use drop(limit ?? 0) to treat a missing value as "skip nothing", and validate that limit is a finite, non-negative number. Otherwise drop(Infinity) on the infinite naturals() generator would hang on the first next() call.