It would be convenient to be able to go next()
or prev()
on an iterator (or some similar construct, if not an iterator).
For example, to do this with a Set
, we currently have to convert it into an Array
, then use index math.
It would be nice to be able to (somehow?) be able to go forward or backward on a Set
. This could avoid alternatives like linked lists (including circular). For example,
const set = new Set([1, 2, 3, 4])
set.prev() // go to last item so first next() call hits first item (or maybe this is default, or something)
console.log(set.next()) // 1
console.log(set.next()) // 2
console.log(set.next()) // 3
console.log(set.prev()) // 2
console.log(set.next()) // 3
console.log(set.next()) // 4
console.log(set.next()) // 1
That illustrates the idea, but maybe its not a good API, because it is not inherently iterable by our standards. Would it be plausible to add this to iterators somehow? For example:
const iter = set.values()
console.log(iter.nextItem()) // 1
console.log(iter.prevItem()) // 4
and a way to control the order of automatic iteration, f.e.
set.forward = false // or something
for (const val of set) console.log(val) // 4, 3, 2, 1
set.forward = true
for (const val of set) console.log(val) // 1, 2, 3, 4
or (just to throw in alternative ideas):
for (const val of set.reverse()) console.log(val) // 4, 3, 2, 1
for (const val of set) console.log(val) // 1, 2, 3, 4
for (const val of set.startAt(1)) console.log(val) // 2, 3, 4, 1
Or something.
Basically just wondering if this is possible to add, because it may be convenient to use a Set
for certain reasons compared to a linked list, namely when order doesn't matter.