Iterator Helpers Map Filter Take Lazily

Chain iterator helpers on generators and iterables: map, filter, and take build a lazy plan, toArray pulls, and every short-circuits on the first miss.

JavascriptData Integrity

Code

javascriptsnippet
25 lines
// 迭代器辅助方法(ES2025):map/filter/take 直接挂在迭代器上,惰性求值
function* logLines() {
  yield 'INFO boot ok';
  yield 'DEBUG cache hit';
  yield 'ERROR disk full';
  yield 'INFO ready';
  yield 'ERROR timeout';
}

// 链式构建描述的是「取数计划」,此刻一个元素都没消费
const plan = logLines()
  .filter((line) => line.startsWith('ERROR'))
  .map((line) => line.slice(6))
  .take(1);

console.log('lazy  : plan built, nothing pulled');

// toArray 触发拉取:take(1) 拿到第一条后停止推进生成器
console.log('first :', plan.toArray());

// flatMap 展开子迭代;every/some 短路判断
const flat = Iterator.from(['a,b', 'c,d']).flatMap((row) => row.split(',')).toArray();
console.log('flat  :', flat);

console.log('every :', logLines().every((line) => line.startsWith('INFO')));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

lazy  : plan built, nothing pulled
first : [ 'disk full' ]
flat  : [ 'a', 'b', 'c', 'd' ]
every : false

Inside the snippet

The file’s state is a handful of top-level bindings: plan, flat.

Using it

Running the file prints labeled results such as lazy : plan built, nothing pulled, first :, flat : — each operation’s effect is visible in the output.

Key statements

const flat = Iterator.from(['a,b', 'c,d']).flatMap((row) => row.split(',')).toArray();
yield 'DEBUG cache hit';
yield 'ERROR disk full';

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Its state lives in module-level bindings: `plan`, `flat`.