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
1 Answer
Reset to default 12You 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
版权声明:本文标题:javascript - How do I implement a cycle-through array with a generator function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741473570a2380749.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论