Open utterances-bot opened 4 years ago
So is there a way to use an iterator twice without manually resetting it?
Normally you use an iterator per loop, and if you mark its functions as inline
there is no instance at runtime. If there is no instance, there is also no need to recycle it.
If you take the example and add inline
to it, it will look like this:
class MyStringIterator {
var s:String;
var i:Int;
public inline function new(s:String) {
this.s = s;
i = 0;
}
public inline function hasNext() return i < s.length;
public inline function next() return s.charAt(i++);
}
class Test {
static public function main() {
var label = Math.random() > 0.5 ? "apple" : "pear";
for (chr in new MyStringIterator(label)) {
trace(chr);
}
}
}
It will be compiled like this:
// Generated by Haxe 4.1.4
(function ($global) { "use strict";
class Main {
static main() {
let _g_s = Math.random() > 0.5 ? "apple" : "pear";
let _g_i = 0;
while(_g_i < _g_s.length) console.log(_g_s.charAt(_g_i++));
}
}
Main.main();
})({});
For most purposes you can probably get away with resetting in hasNext() itself.
public function hasNext():Bool {
if(this.data.length <= this.currentIdx){
this.currentIdx = 0;
return false;
}
return true;
}
I haven't been able to find a case where that doesn't work.
Iterators - Haxe - The Cross-platform Toolkit
Haxe is an open source toolkit based on a modern, high level, strictly typed programming language.
https://haxe.org/manual/lf-iterators.html