-
Notifications
You must be signed in to change notification settings - Fork 161
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
"for of" iteration support. #262
Comments
example: function seq(n) {
var i = 0;
return {
[Symbol.iterator]() {
return {
next() {
if (i == n) {
return { done: true };
}
return { value: i++ };
}
};
}
}
}
for (var x of seq(10)) {
console.log(x);
} |
Here's some PoC: https://gist.github.com/VBart/ce0bad1f15a337eff49f1336311d8381
|
Hi! Actually, there is a huge difference between function collatz(n) {
var seq = [n];
for (var x of seq) {
if (x == 1) {
return seq;
}
seq.push(x & 1 ? 3 * x + 1 : x >> 1);
}
}
console.log(collatz(42)); |
Please take a look. Practically useless, because iteration will generate O(n) temporary objects. But by introducing some new vmcodes, the O(1) $ cat collatz.js
function collatz2(n) {
var seq = [n];
var it = seq.values();
for (var x = it.next(); !x.done; x = it.next()) {
if (x.value == 1) {
return seq;
}
seq.push(x.value & 1 ? 3 * x.value + 1 : x.value >> 1);
}
}
console.log(collatz2(42));
$ build/njs collatz.js
[42,21,64,32,16,8,4,2,1] |
you are suggesting to hide the returned value right and operate on njs_value_iterator_t? for (var x of iterable) { }
So, making the real object, may be avoided. |
Yes. To avoid useless https://tc39.es/ecma262/#sec-createiterresultobject when it is possible. I plan to do something like this:
But abusing var a = [1,2,3];
var x;
for (x of a) {}
console.log(x); // x should point to the last valid value
3 Also, we can't operate directly on the iterator state: var a = [1,2,3,4,5,6];
var it = a.values();
for (var x of it) { it.next(); console.log(x); }
1
3
5 BTW, I'm just trying to figure out how the VM works. Patch updated, added String.prototype[Symbol.iterator] |
Thanks, committed. |
This is the feature is miss the most now because its proper transpilation brings a significant overhead. Most of the time I iterate just over Arrays, so it can be transpiled into a simple and efficient for loop over indexes, but Babel transpiler cannot know that. There’s an option |
No description provided.
The text was updated successfully, but these errors were encountered: