javascript - How to use an iterator as is in the ECMA6 proposal? -
i'm trying figure out how intended utilize iterators defined in current ecma6 draft.
the iterator proposed follows:
function makeiterator(array){ var nextindex = 0; homecoming { next: function(){ homecoming nextindex < array.length ? {value: array[nextindex++], done: false} : {done: true}; } } }
i sense i'm missing out something, because mean have utilize in fashion:
var = makeiterator(somearray); var current = it.next(); while (current.done !== true){ console.log(current.value); current = it.next(); }
because, of course, skip values:
var = makeiterator(somearray); while (it.next().done !== true){ console.log(it.next().value); }
coming java world i'm confused why did not include hasnext
function. because allow next usage:
function makebetteriterator(array){ var nextindex = 0; homecoming { next: function(){ homecoming nextindex < array.length ? {value: array[nextindex++], done: false} : {done: true}; }, hasnext: function(){ if(nextindex < array.length){ homecoming true; }else{ homecoming false; } } } } var somearray = ["one", "two", "three", "four", "five"]; var = makebetteriterator(somearray) while (it.hasnext() === true){ console.log(it.next().value); }
is there simpler way utilize iterators or how it's supposed done? if there no simpler way, why iterators proposed when there's improve solution?
to avoid duplication before while
loop, simple this:
var = makeiterator(somearray); while (true) { var current = it.next(); if (current.done) break; console.log(current.value); }
but really, in es6, you'd doing this:
for (var val of makeiterator(somearray)) { console.log(val); }
the es6 iterator protocol simple in iterator iterface requires single method (next
) returns iteratorresult containing done
, optionally value
. 1 time protocol becomes standard, implementing of benefits of language-level statements back upwards (like for...of
).
javascript iterator ecmascript-6
No comments:
Post a Comment