You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否为自定义迭代器应用filter方法?JavaScript生成器实践

Generator-Based Iterable Utilities

When working with JavaScript Generators, you quickly notice that while they return iterable objects, these iterables don’t come with the handy array methods like filter(), map(), forEach(), or reduce() built-in. That’s why implementing generator-powered versions of these utilities makes perfect sense—they let you work with iterables (including those from generators) in a familiar, functional way without converting everything to an array first.

Here’s a complete set of these utilities, along with a sample range generator to demonstrate usage:

Complete Code

'use strict';

// Sample generator to create an iterable range of numbers
function* range(n) {
  for (let i = 1; i <= n; i++) {
    yield i;
  }
}

// Generator-based filter: yields items that pass the predicate check
function* filter(iterable, predicate) {
  for (const item of iterable) {
    if (predicate(item)) {
      yield item;
    }
  }
}

// Generator-based map: yields transformed items using the callback
function* map(iterable, transformer) {
  for (const item of iterable) {
    yield transformer(item);
  }
}

// Generator-compatible reduce: accumulates a value from the iterable
function reduce(iterable, reducer, initialValue) {
  let accumulator = initialValue;
  for (const item of iterable) {
    accumulator = reducer(accumulator, item);
  }
  return accumulator;
}

// Generator-compatible forEach: executes a callback for each item
function forEach(iterable, callback) {
  for (const item of iterable) {
    callback(item);
  }
}

Usage Examples

Let’s see these utilities in action with the range generator:

Filter even numbers from 1 to 10

const evenNumbers = filter(range(10), num => num % 2 === 0);
for (const num of evenNumbers) {
  console.log(num); // Logs 2, 4, 6, 8, 10
}

Map numbers to their squares

const squaredNumbers = map(range(5), num => num * num);
console.log([...squaredNumbers]); // [1, 4, 9, 16, 25]

Reduce to sum all numbers in the range

const sum = reduce(range(10), (acc, num) => acc + num, 0);
console.log(sum); // 55

ForEach to log each item

forEach(range(3), num => console.log(`Number: ${num}`));
// Logs "Number: 1", "Number: 2", "Number: 3"

Key Notes

  • These utilities work with any iterable, not just generator outputs—so you can use them with arrays too, though arrays already have their own optimized methods.
  • Generator-based filter and map are lazy-evaluated, meaning they only process items as you iterate over them. This is ideal for large or infinite iterables since it doesn’t load everything into memory at once.
  • reduce and forEach are eager operations, as they need to process all items to complete their tasks.

内容的提问来源于stack exchange,提问作者shu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:42:48