I'm relatively new to generator functions and was wondering if there is a way to get the previous value yielded from the generator function. I know I can use .next()
to proceed to the next yield
, but I'm wondering if it would be possible to do something like .prev()
, which would essentially go back a step.
I was hoping .prev()
would work, however, it unfortunately doesn't:
const array = ['a', 'b', 'c'];
function* f(array) {
let i = 0;
while(true) {
yield array[i];
i = (i+1) % array.length;
}
}
const seq = f(array);
console.log(seq.next().value); // a
console.log(seq.next().value); // b
console.log(seq.next().value); // c
console.log(seq.next().value); // a
// console.log(seq.prev().value); // c <-- expect 'c'
As I mentioned, I'm inexperienced with generators, and if there is a better data-structure/method to progressively get values (previous and next) I'm open to hearing about those suggestions