在JavaScript中映射生成器上的函数

时间:2017-08-31 14:25:04

标签: javascript functional-programming generator

我在JavaScript中有一个名为generateNumbers的生成器和另一个生成器generateLargerNumbers,它生成generateNumbers生成的每个值并对其应用函数addOne,如下所示:< / p>

function addOne(value) {
  return value + 1
}

function* generateNumbers() {
  yield 1
  yield 2
  yield 3
}

function* generateLargerNumbers() {
  for (const number of generateNumbers()) {
    yield addOne(number)
  }
}

如果没有从生成的值中构建数组,是否有任何更简单的方法可以做到这一点?我想的是:

function* generateLargerNumbers() {
  yield* generateNumbers().map(addOne) // obviously doesn't work
}

4 个答案:

答案 0 :(得分:6)

没有内置的方法来映射Generator个对象,但您可以自己动手:

const Generator = Object.getPrototypeOf(function* () {});
Generator.prototype.map = function* (mapper, thisArg) {
  for (const val of this) {
    yield mapper.call(thisArg, val);
  }
};

现在你可以做到:

function generateLargerNumbers() {
  return generateNumbers().map(addOne);
}

const Generator = Object.getPrototypeOf(function* () {});
Generator.prototype.map = function* (mapper, thisArg) {
  for (const val of this) {
    yield mapper.call(thisArg, val);
  }
};

function addOne(value) {
  return value + 1
}

function* generateNumbers() {
  yield 1
  yield 2
  yield 3
}

function generateLargerNumbers() {
  return generateNumbers().map(addOne)
}

console.log(...generateLargerNumbers())

答案 1 :(得分:6)

高阶生成器

您可以选择自己操纵生成器功能

const Generator =
  {
    map: (f,g) => function* (...args)
      {
        for (const x of g (...args))
          yield f (x)
      },
    filter: (f,g) => function* (...args)
      {
        for (const x of g (...args))
          if (f (x))
            yield x
      }
  }

// some functions !
const square = x =>
  x * x

const isEven = x =>
  (x & 1) === 0
  
// a generator !
const range = function* (x = 0, y = 1)
  {
    while (x < y)
      yield x++
  }

// higher order generator !
for (const x of Generator.map (square, Generator.filter (isEven, range)) (0,10))
  console.log('evens squared', x)

高阶迭代器

或者你可以选择操纵迭代器

const Iterator =
  {
    map: (f, it) => function* ()
      {
        for (const x of it)
          yield f (x)
      } (),
    filter: (f, it) => function* ()
      {
        for (const x of it)
          if (f (x))
            yield x
      } ()
  }

// some functions !
const square = x =>
  x * x
  
const isEven = x =>
  (x & 1) === 0

// a generator !
const range = function* (x = 0, y = 1)
  {
    while (x < y)
      yield x++
  }
  
// higher-order iterators !
for (const x of Iterator.map (square, Iterator.filter (isEven, range (0, 10))))
  console.log('evens squared', x)

<强>建议

在大多数情况下,我认为操纵迭代器更实际,因为它定义明确(尽管是kludgy)接口。它允许你做类似

的事情
Iterator.map (square, Iterator.filter (isEven, [10,11,12,13]))

而另一种方法是

Generator.map (square, Generator.filter (isEven, Array.from)) ([10,11,12,13])

两者都有一个用例,但我发现前者比后者好得多

持久性迭代器

JavaScript的有状态迭代器让我烦恼 - 每次对.next的调用都会不可逆转地改变内部状态。

但是!没有什么可以阻止你制作自己的迭代器,然后创建一个适配器来插入JavaScript的堆栈安全生成器机制

如果您对此感兴趣,可能会想要在此处找到的其他一些示例:Loop to a filesystem structure in my object to get all the files

唯一的好处不是我们可以重用持久性迭代器,而是通过这种实现,随后的读取比第一次更快更快因为记忆 - 得分:JavaScript 0 ,持久性迭代器 2

// -------------------------------------------------------------------
const Memo = (f, memo) => () =>
  memo === undefined
    ? (memo = f (), memo)
    : memo

// -------------------------------------------------------------------
const Yield = (value, next = Return) =>
  ({ done: false, value, next: Memo (next) })
  
const Return = value =>
  ({ done: true, value })
  
// -------------------------------------------------------------------
const MappedIterator = (f, it = Return ()) =>
  it.done
    ? Return ()
    : Yield (f (it.value), () => MappedIterator (f, it.next ()))
    
const FilteredIterator = (f, it = Return ()) =>
  it.done
    ? Return ()
    : f (it.value)
      ? Yield (it.value, () => FilteredIterator (f, it.next ()))
      : FilteredIterator (f, it.next ())

// -------------------------------------------------------------------
const Generator = function* (it = Return ())
  {
    while (it.done === false)
      (yield it.value, it = it.next ())
    return it.value
  }

// -------------------------------------------------------------------  
const Range = (x = 0, y = 1) =>
  x < y
    ? Yield (x, () => Range (x + 1, y))
    : Return ()

const square = x =>
  x * x

const isEven = x =>
  (x & 1) === 0

// -------------------------------------------------------------------
for (const x of Generator (MappedIterator (square, FilteredIterator (isEven, Range (0,10)))))
  console.log ('evens squared', x)

答案 2 :(得分:0)

如何组成迭代器对象,而不是使用嵌套的生成器?

function* generateNumbers(){
 yield 1;   
 yield 2;
 yield 3;
}

function generateGreaterNumbers(){
 return { next(){ var r = this.gen.next(); r.value+=1; return r; }, gen: generateNumbers() };`
}

答案 3 :(得分:0)

如果您需要实际将值传递给生成器,则不能使用... of,必须将每个值传递给

  const mapGenerator = (generatorFunc, mapper) =>
    function*(...args) {
      let gen = generatorFunc(...args),
        i = 0,
        value;
      while (true) {
        const it = gen.next(value);
        if (it.done) return mapper(it.value, i);
        value = yield mapper(it.value, i);
        i++;
      }
    };

function* generator() {
  console.log('generator received', yield 1);
  console.log('generator received', yield 2);
  console.log('generator received', yield 3);
  return 4;
}

const mapGenerator = (generatorFunc, mapper) =>
  function*(...args) {
    let gen = generatorFunc(...args),
      i = 0,
      value;
    while (true) {
      const it = gen.next(value);
      if (it.done) return mapper(it.value, i);
      value = yield mapper(it.value, i);
      i++;
    }
  };

const otherGenerator = mapGenerator(generator, x => x + 1)

const it = otherGenerator();
console.log(
  it.next().value,
  it.next('a').value, 
  it.next('b').value,
  it.next('c').value
);