Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Slicing and Sampling

Take portions of your data stream.

take()

Take first N items:

import { enumerate } from "jsr:@j50n/proc@0.23.3";

const first3 = await enumerate([1, 2, 3, 4, 5])
  .take(3)
  .collect();
// [1, 2, 3]

Early Exit

Stops reading after N items:

// Only reads first 10 lines
const preview = await read("huge-file.txt")
  .lines
  .take(10)
  .collect();

With Filter

// First 5 errors
const errors = await read("app.log")
  .lines
  .filter(line => line.includes("ERROR"))
  .take(5)
  .collect();

drop()

Skip first N items:

const rest = await enumerate([1, 2, 3, 4, 5])
  .drop(2)
  .collect();
// [3, 4, 5]

Skip Header

const data = await read("data.csv")
  .lines
  .drop(1)  // Skip header row
  .collect();

Combining drop() and take()

Get a range of items by combining drop and take:

const middle = await enumerate([1, 2, 3, 4, 5])
  .drop(1)
  .take(3)
  .collect();
// [2, 3, 4]

Pagination

const page = 2;
const pageSize = 10;

const items = await enumerate(allItems)
  .drop(page * pageSize)
  .take(pageSize)
  .collect();

first

Get first item:

const first = await enumerate([1, 2, 3]).first;
// 1

With Pipeline

const result = await run("ls", "-la")
  .lines
  .first;

last

Get last item:

const last = await enumerate([1, 2, 3]).last;
// 3

Note: Reads entire stream to find last item.

nth()

Get item at index:

const third = await enumerate([1, 2, 3, 4, 5]).nth(2);
// 3 (zero-indexed)

Real-World Examples

Preview File

console.log("First 10 lines:");
await read("file.txt")
  .lines
  .take(10)
  .forEach(line => console.log(line));

Skip and Take

// Lines 11-20
const batch = await read("file.txt")
  .lines
  .drop(10)
  .take(10)
  .collect();

Sample Data

// Every 10th item
const sample = await enumerate(data)
  .filter((_, i) => i % 10 === 0)
  .collect();

Find Nth Match

// 5th error
const fifthError = await read("app.log")
  .lines
  .filter(line => line.includes("ERROR"))
  .nth(4);  // Zero-indexed

Performance Tips

Use take() for Limits

// ✅ Stops early
const first100 = await enumerate(huge)
  .take(100)
  .collect();

// ❌ Reads everything
const all = await enumerate(huge).collect();
const first100 = all.slice(0, 100);  // Array slice, not Enumerable

Combine with Filter

// Efficient: stops after 10 matches
const matches = await enumerate(data)
  .filter(predicate)
  .take(10)
  .collect();

Next Steps