是否可以像普通函数一样组合生成器函数

Is it possible to compose generator functions like you would normal functions

问题: 是否可以像使用 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
}

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

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);
}

您的 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);
}