javascript - Conventions for ES6 iterables? -
i'm author of graph datastructure library javascript. i'm es6-ifying library.
i want make more usable es6 programmers, means implementing iterable protocol. graph has multiple things iterate over, , multiple ways iterate on them (vertices, edges, successors, predecessors, vertices in topological order, etc.)
i have idea of how design interface, i'd follow existing conventions if exist. here's example of how might 'vertices' part:
class jsgraph { // ... vertices() { return { _graph: this, length() { return this._graph._vertexcount }, *[symbol.iterator]() { var keys = object.keys(this._graph._vertices); (let = 0; < keys.length; ++i) { yield [keys[i], this._graph._vertices[keys[i]]]; } } }; } // ... }
if there existng convention should following (or problems code), feedback appreciated.
you might inspiration map
, set
es6 data structures. provide multiple methods different iterators: .values()
, .keys()
, , .entries()
. @@iterator
method defaults entries
or values
respectively.
i don't know of other existing conventions, guess these have form yet.
any problems code
first, i'm not sure whether getter vertices
returns such object idea. i'd rather do
get vertexcount() { … } vertices*() { … }
but that'll come down preference. current code not efficient because creates 2 functions @ every .vertices
access, improve using prototypes if see need (class vertexiterator {…}
?).
second, iterators on mutable data hazzle implement, may change while being looped over. should aware of , choose strategy (making structures immutable out of question). example, mapiterator's next
method specified "redetermine number of elements each time evaluated.". similarly, object enumerations (for in
) there rule deleted properties must never appear (if not enumerated before deleted), , of course no property may enumerated twice. however, explicitly allowed inconsistent keys added during execution, no guarantees given on whether appear in enumeration or not.
Comments
Post a Comment