Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you reverse an iterator's flow?

Is it possible to access the previous value of an iterator, for example:

function* gen () {
   yield* [0,1,2,3]
}

var it = gen();

it.next().value // 0
it.next().value // 1
it.last().value // would be awesome if this was 0

This is strictly a curiosity question. I've been playing with generators lately and was wondering if anyone uses generators/iterators in this manner?

If so, I would love to see your solution. (Doesn't need to follow the above syntax) -Thanks

like image 447
Joseph Barnes Avatar asked Oct 26 '25 16:10

Joseph Barnes


1 Answers

JS iterators only know one direction: forwards. Meaning, if you would want to use your custom iterator with a for-loop or the like, it would ignore your custom properties. You could however create your own custom iterator for your own use only:

const obj = {
   values: [0,1,2,3],
   [Symbol.iterator]() {
     const values = this.values;
     const min = 0;
     const max = values.length - 1;

     let index = -1;

     return {
       next() {
        index = Math.min(index + 1, max);
        return { value: values[index], done: index >= max };
       },
       prev() {
        index = Math.max(index - 1, min);
        return { value: values[index], done: index <= min };
       }
     }
   }
}

var it = obj[Symbol.iterator]();

console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.prev().value); // would be awesome if this was 0
console.log(it.prev().value); // would be awesome if this was 0
console.log(it.prev().value); // would be awesome if this was 0
console.log(it.next().value); // would be awesome if this was 1
like image 69
nils Avatar answered Oct 29 '25 06:10

nils