avl icon indicating copy to clipboard operation
avl copied to clipboard

feature proposal: iterable interfaces

Open derhuerst opened this issue 7 years ago • 10 comments
trafficstars

Using iterables to walk over a large amount of items/data has two advantages:

  • In contrast to computing a full array all items, items can be read from the tree on the fly. This prevents unnecessary graph walks.
  • Iterables are well-supported within ECMAScript and libs: String, Array, Map, Set etc. are iterable.

Examples of how iterables would be useful for this lib:

for (const key of tree.keys()) {
  await userRequestedAKey()
  console.log(key)
}

for (const node of tree.range('A', 'O')) {
  console.log(node.data)
}

derhuerst avatar Sep 09 '18 18:09 derhuerst

I'd be happy to submit a PR with this!

derhuerst avatar Sep 09 '18 18:09 derhuerst

Please do! Would that still be es5 compatible?

w8r avatar Sep 13 '18 15:09 w8r

Would that still be es5 compatible?

Nope, Symbol.iterator is ES2015/ES6, so not supported in IE11.

But I think you can implement it in a backwards-compatible way:

if (Symbol && Symbol.iterator) {
  AVLTree.prototype[Symbol.iterator] = function (...) {...}
}

derhuerst avatar Sep 14 '18 10:09 derhuerst

That would be cool!

w8r avatar Sep 14 '18 14:09 w8r

What API do you prefer?

  1. tree is not iterable
  2. tree[Symbol.iterator] returns a keys iterable?
  3. tree[Symbol.iterator] returns an entries ([key, value]) iterable?

  1. tree.keys() stays an array as before, add tree.keysIterable().
  2. Change tree.keys() from an array to an iterable. (breaking)

same for tree.values()

derhuerst avatar Sep 14 '18 14:09 derhuerst

  1. tree[Symbol.iterator] returns an entries ([key, value]) iterable?

  1. tree.keys() stays an array, as before, add tree.keysIterable()

right?

w8r avatar Sep 14 '18 14:09 w8r

Okay, will implement this. A tree.valuesIterable() also makes sense, right?

derhuerst avatar Sep 14 '18 15:09 derhuerst

yes, let's do it like that. Maybe I will change the API later. I will also add your changes to the splay-tree repo then

w8r avatar Sep 14 '18 15:09 w8r

I have implemented this at derhuerst/avl#iterables, but using ES6 generators. They are not supported in IE11, so we have two choices now:

  1. implement the iterators by hand using only ES5 syntax,
  2. or use Babel for transpiling or get bublé to transpile generators.

What do you prefer?

derhuerst avatar Sep 16 '18 08:09 derhuerst

Opted for 1.

derhuerst avatar Sep 16 '18 09:09 derhuerst