6

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 to have a loop in your generator code.
    – trincot
    Dec 30, 2016 at 23:59

1 Answer 1

11

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

4
  • Also if you take the array as an argument, it's an immediately usable block for OP Dec 31, 2016 at 0:03
  • @BalázsÉdes, thanks, I incorporated that improvement idea.
    – trincot
    Dec 31, 2016 at 0:10
  • True, @BalázsÉdes is right - I too am discovering the power of new stuff, like Map, Set or generators. Wasn't quite sure I'd ever need a generator, but with syntax possible as this one, it's just a dream. Wondering though, why jsfiddle.net spits out errors when trying to run this code under JavaScript 1.7 or TypeScript. Had to resort to regular JavaScript option in the fiddle.
    – user776686
    Dec 31, 2016 at 10:49
  • Seems to work with Javascript 1.7, but the TypeScript version in jsfiddle does not support yield. I suppose it is not version 1.6.
    – trincot
    Dec 31, 2016 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.