proposal-deiter icon indicating copy to clipboard operation
proposal-deiter copied to clipboard

Can `next()`/`prev()` als be included?

Open trusktr opened this issue 1 year ago • 2 comments

I would like to iterate a Set, for example, in either direction, and change direction during iteration. This could, for example, replace a (maybe circular) linked list.

More thoughts here:

https://es.discourse.group/t/next-prev-for-non-async-iterators/2224

Motivating example:

This example is obviously not very well thought out (next() returns {value: ___, ...}), but it shows what the end-user desire is:

const set = new Set(...) // maybe this comes from somewhere else (imported, component prop, etc)

const vals = set.values()
let selected = vals.next()

// ... some reactive framework template ...
return <div>
  <p>name: {selected.name}</p>
  <button onclick={() => selected = vals.next()}>next</button>
  <button onclick={() => selected = vals.prev()}>prev</button>
</div>

trusktr avatar Nov 21 '24 21:11 trusktr

While this definitely works for an iterator over a finite collection (Set, Map, Array, String), in general it wouldn't work - in particular for most things that use generators or custom iterators. would you test for the presence of a prev method to distinguish?

ljharb avatar Nov 21 '24 22:11 ljharb

@trusktr see faq:

...bidirectional is not compatible with JavaScript iterator protocol, because JavaScript iterators are one-shot consumption, and produce {done: true} if all values are consumed, and it is required that next() always returns {done: true} after that, but previous() actually require to restore to previous, undone state.

hax avatar Feb 10 '25 03:02 hax