【问题标题】:Is it possible to compose generator functions like you would normal functions是否可以像普通函数一样组合生成器函数
【发布时间】:2019-11-28 01:11:59
【问题描述】:

问题: 是否可以像 compose 那样将两个生成器组合成一个生成器?

function* type(vals) {
  for(const v of vals) {
    yield v;
  }
}

const bool = type([true, false]);
const str = type([
  '',
  undefined,
  'Lorem',
  'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
  '????????????????'
]);

const composeGenerator = () => {/*???*/};  
const input = composeGenerator(bool,str);
console.log(input, 'yes');

for (const i of bool) {
  console.log(i); // true, false
}

for (const i of str) {
  console.log(i); // '',  undefined,  'Lorem',  'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',  '????????????????'
}

for (const i of input) {
  console.log(i); // '',  undefined,  'Lorem',  'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',  '????????????????', true, false
}

【问题讨论】:

  • 您的预期输出也按照[...str, ...bool] 的顺序排列,但您的参数按照bool, str 的顺序排列。这是故意的吗?
  • @PatrickRoberts 任何一个顺序都可以……有时候,撰写是正确的。但我无动于衷
  • 在函数组合中,您将一个函数的结果作为参数传递给另一个函数。您的生成器函数不接受任何参数,所以这没有任何意义吗?您想要的输出(input 可迭代)看起来更像是一个简单的连接
  • 您可以简单地将生成器或任何可迭代对象与iter-ops library 连接起来;)

标签: javascript ecmascript-6 generator iterable


【解决方案1】:

首先,您的type 函数实际上可以缩短。其次,这是您的composeGenerator 从左到右的一种可能实现:

function * type (iterable) {
  yield * iterable;
}

const bool = type([true, false]);
const str = type([
  '',
  undefined,
  'Lorem',
  'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
  '????'
]);

function * composeGenerator (...iterables) {
  for (const iterable of iterables) yield * iterable;
}

const input = composeGenerator(str, bool);

for (const i of input) {
  console.log(i);
}

【讨论】:

  • 如果你创建了像 const bool = () => type ([true, false]) 这样的 bool 和 str 函数,它们可以再次被执行,对吧?
  • @MatthewHarwood 不,这是不对的。如果您想不接受我的回答,请继续,但这样做并非易事。您必须修改您接受作为输入的对象,这可能会导致复杂和意外的行为。
  • gist.github.com/matthewharwood/b722988116afc8eb79a8321a3e940eee 不,它确实有效,但也许我没有解释它@PatrickRoberts
  • @MatthewHarwood 实际上我认为我误读了您的第一条评论。我应该编辑我的答案以解决您如何重用您的柯里化函数吗?
  • 是的,让我们这样做吧!如果你的第 2 轮在这里stackoverflow.com/questions/57105848/…
【解决方案2】:

我们遍历所有生成器,直到它们产生一个值

function* type(vals) {
  for(const v of vals) {
    yield v;
  }
}

const bool = type([true, false]);
const str = type([
  '',
  undefined,
  'Lorem',
  'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
  '????'
]);

function *composeGenerator(...iterators) {
  for (const iterator of iterators) {
    for (const value of iterator ) {
      yield value;
    }
  }
}

const input = composeGenerator(bool,str);

for (const i of input) {
  console.log(i);
}

【讨论】:

  • 问题显示 boolstr 在迭代 input 之前被迭代。这在提供的示例代码中不起作用。
  • 我认为这只是为了演示目的。
  • 如果他们想再次迭代迭代器,就必须重置迭代器 (stackoverflow.com/questions/23848113/…)(这里的问题是关于组合的)
猜你喜欢
  • 1970-01-01
  • 2016-02-29
  • 2018-11-30
  • 2014-04-08
  • 2013-10-05
  • 2013-07-15
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
相关资源
最近更新 更多