How do I implement a cycle-through array with a generator function

元气小坏坏 提交于 2019-12-12 17:07:21

问题


Today I was wondering what would be the swiftest method to provide a cycle-through array in TypeScript, as in:

['one', 'two', 'three'] 

where the next value after three would be one, and I thought that it's a good candidate for a generator function. However it does not seem to work for me. What's wrong with the following code?

function* stepGen(){
  const steps = ['one', 'two', 'three'];

  let index = 0;

  if(index < steps.length - 1){
   index++;
  } else {
   index = 0;
  }
  yield steps[index];
}

let gen = stepGen();
console.log(gen.next().value); 
console.log(gen.next().value);
console.log(gen.next().value); // should be 'three'
console.log(gen.next().value); // should be 'one'
console.log(gen.next().value);

回答1:


You need a loop in your generator code, otherwise there is only one yield happening:

function* stepGen(steps){
  let index = 0;
  while (true) {
    yield steps[index];
    index = (index+1)%steps.length;
  }
}

let gen = stepGen(['one', 'two', 'three']); // pass array to make it more reusable
console.log(gen.next().value); 
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);

Alternatively you can also use yield* which yields values from an iterable, one by one:

function* stepGen(steps){
  while (true) yield* steps;
}

let gen = stepGen(['one', 'two', 'three']);
console.log(gen.next().value); 
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);


来源:https://stackoverflow.com/questions/41404182/how-do-i-implement-a-cycle-through-array-with-a-generator-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!