For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/proposal-iterator-sequencing.md.
  • 简体中文
  • Iterator Sequencing S4

    中文标题:迭代器序列化

    提案概览
    提案速览

    该提案添加了一个静态的 Iterator.concat 方法,用于将多个可迭代对象按顺序组合成一个迭代器。它解决了手动使用生成器或辅助库进行拼接在人体工程学上的不足。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    迭代器序列化

    一个 TC39 提案,通过按顺序连接现有迭代器来创建新迭代器。

    阶段: 4

    规范: https://tc39.es/proposal-iterator-sequencing/

    向委员会做的演示

    动机

    通常你有两个或更多迭代器,你希望按顺序消费它们的值,就像它们是单个迭代器一样。迭代器库(以及其他语言的标准库)通常有一个名为 concatchain 的函数来实现这一点。在今天的 JavaScript 中,你可以用生成器(generators)来实现:

    let lows = Iterator.from([0, 1, 2, 3]);
    let highs = Iterator.from([6, 7, 8, 9]);
    
    let lowsAndHighs = function* () {
      yield* lows;
      yield* highs;
    }();
    
    Array.from(lowsAndHighs); // [0, 1, 2, 3, 6, 7, 8, 9]

    能够在迭代器之间插入立即值也是有用的,就像使用生成器方法时用 yield 那样。

    let digits = function* () {
      yield* lows;
      yield 4;
      yield 5;
      yield* highs;
    }();
    
    Array.from(digits); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    我们应该探索如何使这更符合人体工程学且更函数式。

    选定方案

    let digits = Iterator.concat(lows, [4, 5], highs);

    对于(罕见的)无限迭代器的迭代器,使用 Iterator.prototype.flatMap 并辅助以恒等函数。

    function* selfCountingSequenceHelper() {
      for (let n = 1;; ++n) {
        yield Array(n).fill(n);
      }
    }
    let selfCountingSequence = selfCountingSequenceHelper().flatMap(x => x)

    已有的实现

    其他语言

    语言数据类型恰好两个任意数量
    Clojurelazy seqconcat
    ElmListappend/++concat
    HaskellSemigroup<>mconcat
    OCamlSeqappendconcat
    Pythoniteratorchain
    RubyEnumerablechain
    RustIteratorchainflatten
    ScalaIteratorconcat/++
    SwiftLazySequencejoined

    JS 库

    恰好两个任意数量
    @softwareventures/iteratorprependOnce/appendOnceconcatOnce
    extra-iterableconcat
    immutable.jsSeq::concat
    iterablefuconcatenate
    itertools-tschain
    lodashflatten
    ramdaconcatunnest
    sequencyplus
    wuchain