首页 > 解决方案 > 我怎样才能批量消费一个迭代(同样大小的块)?

问题描述

我经常batch()在 Python 中使用。自 ES6 以来,JavaScript 中是否有一些替代方案,它具有迭代器和生成器函数?

标签: javascriptecmascript-6generator

解决方案


我必须为自己写一个,我在这里分享给我和其他人,以便在这里轻松找到:

// subsequently yield iterators of given `size`
// these have to be fully consumed
function* batches(iterable, size) {
  const it = iterable[Symbol.iterator]();
  while (true) {
    // this is for the case when batch ends at the end of iterable
    // (we don't want to yield empty batch)
    let {value, done} = it.next();
    if (done) return value;

    yield function*() {
      yield value;
      for (let curr = 1; curr < size; curr++) {
        ({value, done} = it.next());
        if (done) return;

        yield value;
      }
    }();
    if (done) return value;
  }
}

它产生生成器,而不是Arrays 例如。next()在再次调用之前,您必须完全消耗每个批次。


推荐阅读