惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
V
Visual Studio Blog
T
Tor Project blog
量子位
Jina AI
Jina AI
Hugging Face - Blog
Hugging Face - Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
有赞技术团队
有赞技术团队
博客园 - 司徒正美
博客园_首页
罗磊的独立博客
美团技术团队
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
C
Check Point Blog
博客园 - 聂微东
爱范儿
爱范儿
Schneier on Security
Schneier on Security
T
Threat Research - Cisco Blogs
T
Tailwind CSS Blog
L
LINUX DO - 热门话题
大猫的无限游戏
大猫的无限游戏
V
Vulnerabilities – Threatpost
C
Cisco Blogs
GbyAI
GbyAI
Spread Privacy
Spread Privacy
博客园 - 叶小钗
博客园 - 【当耐特】
T
Tenable Blog
雷峰网
雷峰网
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
J
Java Code Geeks
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
宝玉的分享
宝玉的分享
Microsoft Azure Blog
Microsoft Azure Blog
Simon Willison's Weblog
Simon Willison's Weblog
N
Netflix TechBlog - Medium
T
The Exploit Database - CXSecurity.com
腾讯CDC
C
CERT Recently Published Vulnerability Notes
P
Proofpoint News Feed
阮一峰的网络日志
阮一峰的网络日志
Scott Helme
Scott Helme
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Martin Fowler
Martin Fowler

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Native Iterator Helpers Just Shipped. Here's What You Stop Doing
Gabriel Anha · 2026-05-03 · via DEV Community

You have a list of 50,000 users. You want the names of the first 10 active ones. You write the line you have written a hundred times:

const names = users
  .filter(u => u.active)
  .map(u => u.name)
  .slice(0, 10);

Enter fullscreen mode Exit fullscreen mode

Three array allocations. filter walks all 50,000 entries and builds a new array of, say, 32,000 active users. map then walks those 32,000 and builds a new array of 32,000 names. slice keeps the first 10 and builds the final array. You needed 10 strings. You materialized about 64,000 of them on the way, and the chain visited roughly 82,000 elements to do it.

Until last year, that was the price of Array.prototype chaining. There were two ways out: write an imperative for loop, or pull in lodash/fp, ramda, or iter-tools for lazy versions. Both of those answers are now stale.

TC39's iterator helpers proposal reached Stage 4 at the October 2024 plenary and was merged into ECMA-262 as part of ES2025. The methods are lazy by default. They run in Node 22 LTS and Node 24, in Bun 1.1.31 and later, in Deno 2, and in every current Chrome, Firefox, and Safari (Baseline Newly available, March 31 2025). TypeScript 5.6 added the type story with lib.es2025.iterator.d.ts and the IteratorObject interface.

So the line above stops being idiomatic. The replacement:

const names = users.values()
  .filter(u => u.active)
  .map(u => u.name)
  .take(10)
  .toArray();

Enter fullscreen mode Exit fullscreen mode

.values() returns an iterator over the array. .filter, .map, and .take return iterator helpers — they do not materialize anything. .toArray is the only step that allocates, and it allocates exactly 10 strings. The runtime walks the source array until 10 active users have been seen and then stops. On a list of 50,000 users where the first 10 actives appear in the first 200, the loop visits 200 elements. The original chain visited around 82,000.

This is what you stop doing.

What actually shipped

The proposal adds methods to a single object: Iterator.prototype. Anything whose prototype chain ends in Iterator.prototype picks up the full set: the iterator returned by Array.prototype.values(), Set.prototype.values(), Map.prototype.entries(), String.prototype[Symbol.iterator](), every generator function, and the result of Iterator.from(anyIterable).

The lazy methods, the ones that return another iterator helper:

  • .map(fn) — yields fn(value) for each value
  • .filter(fn) — yields values where fn(value) is truthy
  • .take(n) — yields at most n values, then stops
  • .drop(n) — skips the first n values, then yields the rest
  • .flatMap(fn) — yields each item from the iterables fn returns

The eager methods, the ones that consume the iterator and return a final value:

  • .toArray() — collects everything into an Array
  • .reduce(fn, init?) — same shape as Array.prototype.reduce
  • .forEach(fn) — runs fn for side effects, returns undefined
  • .some(fn), .every(fn), .find(fn) — short-circuit predicates

Plus one static helper:

  • Iterator.from(value) — wraps any iterable (or iterator-like object) so you can chain helpers on it.

That is the full ES2025 surface. The async counterparts (AsyncIterator.prototype.map and friends) are a separate proposal still moving through TC39. Synchronous helpers shipped. Async helpers are coming.

Lazy versus eager: when it matters

The Array chain is eager. Every method allocates a fresh array and walks the whole input. The work is N + N + N + … where N is the input size.

An iterator chain is lazy. .filter, .map, and .take return immediately with an iterator object. Nothing happens until something pulls — a for…of, a .toArray(), a .reduce(), a .forEach(), or a [...spread]. The terminal call asks for the next value, the chain pulls one source element, threads it through every step, and yields one result.

Three places where the difference flips a program from "fine" to "fast":

  1. Early exit. .take(n) or .find() stops the source walk as soon as the answer is known. The Array version walks everything first.
  2. Infinite sequences. A generator can yield forever. With iterator helpers, .take(n) bounds the chain.
  3. One-pass sources. A response stream, an async generator, a database cursor — these cannot be re-walked. Iterator helpers consume them once.

The cost of laziness is per-element protocol overhead — each step is a method call returning an { value, done } object. For a tight chain over a small array of plain numbers, the Array version is sometimes faster on a microbenchmark. The win shows up the moment the input grows, you can short-circuit, or the source is not a fully-materialized array.

Five places iterator helpers replace something verbose

1. Pagination over a cursor API

The "fetch all pages and map them" loop used to need either a while with a mutable accumulator or a for await plus a manual push ladder. With Iterator.from and .flatMap, the shape collapses.

function* paginate(start: string | null) {
  let cursor: string | null = start;
  while (cursor !== null) {
    const page = fetchPageSync(cursor); // sync example
    yield page.items;
    cursor = page.nextCursor;
  }
}

const firstHundredIds = Iterator.from(paginate(null))
  .flatMap(page => page.values())
  .map(item => item.id)
  .take(100)
  .toArray();

Enter fullscreen mode Exit fullscreen mode

The generator yields one page at a time. .flatMap(page => page.values()) walks each page lazily. .take(100) stops the generator the moment 100 IDs are out. If the first hundred IDs live in the first two pages, the third page is never fetched.

2. Streaming JSON via NDJSON

Newline-delimited JSON is the format you hit when a server cannot afford a buffered array response. The classic shape is "read lines, parse, filter, collect." Iterator helpers compress it to a chain.

import { readFileSync } from "node:fs";

function* lines(text: string) {
  let from = 0;
  for (let i = 0; i < text.length; i++) {
    if (text.charCodeAt(i) === 10) {
      yield text.slice(from, i);
      from = i + 1;
    }
  }
  if (from < text.length) yield text.slice(from);
}

interface Event {
  type: string;
  user: string;
  ts: number;
}

const recentLogins = Iterator.from(lines(readFileSync("events.ndjson", "utf8")))
  .filter(line => line.length > 0)
  .map(line => JSON.parse(line) as Event)
  .filter(ev => ev.type === "login")
  .drop(10) // skip the first 10
  .take(50)
  .toArray();

Enter fullscreen mode Exit fullscreen mode

Same chain works on any character stream that you can wrap as an iterator — a ReadableStream's reader, a node:readline interface (its async version), a websocket frame loop. The shape stays "split, parse, filter, slice, collect."

3. Infinite sequences without an upper bound in the source

Array.from({ length: N }, …) forces you to know N upfront. A generator does not.

function* fibonacci() {
  let [a, b] = [0n, 1n];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const bigFibs = fibonacci()
  .filter(n => n > 1_000_000n)
  .take(5)
  .toArray();

// [1346269n, 2178309n, 3524578n, 5702887n, 9227465n]

Enter fullscreen mode Exit fullscreen mode

The generator is infinite. .filter is infinite. The chain still terminates because .take(5) pulls exactly 5 satisfying values and then closes the upstream iterator. Without iterator helpers, you write the same logic with a while (results.length < 5) loop and a manual array, and you end up writing the bounding condition twice.

4. Early-exit predicate chains

Anywhere you previously wrote arr.some(x => predicate(transform(x))) and felt mildly guilty about the implicit double pass, the iterator-helper version is cheaper and reads cleaner.

interface Order {
  id: string;
  total: number;
  customer: { country: string };
}

function hasLargeEUOrder(orders: readonly Order[]): boolean {
  return orders.values()
    .filter(o => o.customer.country.startsWith("EU-"))
    .map(o => o.total)
    .some(total => total > 10_000);
}

Enter fullscreen mode Exit fullscreen mode

.some short-circuits on the first true. The lazy chain in front of it only runs as far as needed. The Array version would .filter first, allocating a new array of every EU order, and then .some over it. Same answer; one extra pass and one extra allocation.

5. Composable transforms over a Map or Set

Map.prototype.values() and Set.prototype.values() already returned iterators. Until 2024 you could not chain anything on them without spreading into an Array first. Now they get the full helper surface for free.

const eventCounts = new Map<string, number>([
  ["login", 1240],
  ["signup", 180],
  ["click", 90_400],
  ["purchase", 320],
]);

const topThree = eventCounts.entries()
  .filter(([, count]) => count >= 100)
  .map(([type, count]) => ({ type, count }))
  .toArray()
  .sort((a, b) => b.count - a.count)
  .slice(0, 3);

Enter fullscreen mode Exit fullscreen mode

Note the shape: lazy iterator chain up to .toArray(), then standard Array operations for ordering. Iterator helpers do not include .sort because sorting is inherently eager — you cannot sort a stream without seeing all of it. The boundary is honest about that.

Where iterator helpers do not help

Five places to keep using Array methods or a plain for loop.

Small fixed-size arrays. A list of 8 menu items does not benefit from laziness. The Array chain is shorter to type and the per-element overhead of the iterator protocol is real, even if small. If your input has tens of items and there is no early exit, .filter().map() on the array is fine. Reach for iterator helpers when the input is large, the source is a stream, or the chain ends in .take / .find / .some.

You need to sort or reverse. No .toSorted, .toReversed, or .sort on iterators. You cannot order a stream you have not finished reading. Materialize with .toArray() and sort the array.

You need random access. Iterators are linear. If you need arr[i] mid-pipeline, stay on Array.

You need to walk the source twice. Most iterators are single-use. The result of arr.values() happens to be re-iterable in some cases, but generators and Iterator.from(generator) are not. If your pipeline forks ("count them and also collect them"), either materialize once with .toArray and walk twice, or use .reduce to do both in a single pass.

You are mid-async. The synchronous helpers do not work on async generators. ES2025 only shipped the sync set. The async iterator helpers proposal is at Stage 2.7 as of April 2026, and it is the natural completion of this work. Until it lands, async pipelines still use libraries (it-pipe, iter-tools, custom utilities) or hand-rolled for await loops.

The TypeScript 5.6 type story

If you tried iterator helpers between September and December 2024 and got blanket any returns or "Property 'map' does not exist on type 'IterableIterator<…>'" errors, the type story has cleaned up.

TypeScript 5.6 introduced IteratorObject<T, TReturn, TNext> and the new lib.es2025.iterator.d.ts. The shipped libs were updated so that Array.prototype.values(), Map.prototype.entries(), Set.prototype.values(), generator return types, and friends all return IteratorObject subtypes (ArrayIterator, MapIterator, SetIterator, GeneratorIterator) rather than the old IterableIterator. Those IteratorObject subtypes carry the helper methods.

The minimal tsconfig to use them:

{
  "compilerOptions": {
    "target": "ES2024",
    "lib": ["ES2024", "ES2025.Iterator", "WebWorker"],
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true
  }
}

Enter fullscreen mode Exit fullscreen mode

"ES2025.Iterator" pulls in the helper signatures without dragging in the rest of ES2025 (which, depending on the TypeScript version you are on, may include things you do not want yet). If you are already on "lib": ["ESNext", …] you have it.

A typed pipeline:

interface User {
  id: string;
  name: string;
  active: boolean;
}

function activeNames(users: readonly User[]): string[] {
  return users.values()
    .filter(u => u.active)
    .map(u => u.name)
    .toArray();
}

Enter fullscreen mode Exit fullscreen mode

The return type of users.values() is ArrayIterator<User>. .filter(predicate) narrows nothing by default — there is a known TypeScript limitation where the filter callback does not become a type predicate without an explicit annotation. If you want narrowing across the chain, write the predicate as one:

type ActiveUser = User & { active: true };

function activeNames(users: readonly User[]): string[] {
  return users.values()
    .filter((u): u is ActiveUser => u.active)
    .map(u => u.name)
    .toArray();
}

Enter fullscreen mode Exit fullscreen mode

The other gotcha is BuiltinIteratorReturn. TypeScript 5.6 also added --strictBuiltinIteratorReturn, which (under --strict) makes the TReturn of every built-in iterator default to undefined instead of any. That is what you want — the return value of an iterator's done: true step is normally undefined and treating it as any was lying. If a generator you wrote returns a non-undefined value, annotate it.

Closing

Iterator helpers are not new thinking. Every language with first-class sequences has been chaining over iterators for fifteen years. They are now the platform default in JavaScript too, on every runtime your code lands on, with no library to import and no polyfill to drop. The synchronous side alone is enough to retire a generation of utility code; the first .filter().map().slice(0, …) chain you convert will produce a smaller diff than you expect, and the runtime will visit 200 elements where the array version visited 82,000.


If this was useful

TypeScript Essentials is the entry point of The TypeScript Library, a 5-book collection that covers the language from "I write some TS at work" to "I ship libraries that run on every JS runtime." The iterator-helper story sits in the daily-driver chapter — the same chapter that walks through narrowing, async, and the shape of a modern tsconfig. Start with Essentials for the language, jump to Type System for the deep-dive, take the Kotlin/Java or PHP bridge if those are your home languages, finish with In Production when you are shipping libraries.

  • TypeScript Essentials — entry point. Types, narrowing, modules, async, daily-driver tooling: Amazon
  • The TypeScript Type System — deep dive. Generics, mapped/conditional types, infer, template literals, branded types: Amazon
  • Kotlin and Java to TypeScript — bridge for JVM developers. Variance, null safety, sealed-to-unions, coroutines-to-async/await: Amazon
  • PHP to TypeScript — bridge for modern PHP 8+ developers. Sync-to-async paradigm, generics, discriminated unions: Amazon
  • TypeScript in Production — production layer. tsconfig, build tools, monorepos, library authoring, dual ESM/CJS, JSR: Amazon
  • Hermes IDE — an IDE for developers who ship with Claude Code and other AI coding tools: hermes-ide.com
  • Me: xgabriel.com | GitHub

All five books ship in ebook, paperback, and hardcover.

The TypeScript Library — the 5-book collection