admin管理员组

文章数量:1289517

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

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);
Share Improve this question asked Dec 30, 2016 at 23:56 user776686user776686 8,67517 gold badges78 silver badges137 bronze badges 1
  • You need to have a loop in your generator code. – trincot Commented Dec 30, 2016 at 23:59
Add a ment  | 

1 Answer 1

Reset to default 12

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

本文标签: javascriptHow do I implement a cyclethrough array with a generator functionStack Overflow