Ability to specify an iterator in for...of

# JD Isaacks (9 years ago)

I think it would be pretty useful to be able to set an iterator to use in the context of a for...of statement.

Consider this code:


function* keyValIterator () {
  for (let prop in this) {
    yield [ prop, this[prop] ];
  }
}

var address = {
  street: '420 Paper St.',
  city: 'Wilmington',
  state: 'Delaware'
};

for (let [ key, val ] of address using keyValIterator) {
  console.log(key, val);
}

This would allow an object to be iterated without needing to assign it's @@iterator property. It would also allow the same object to be iterated in different ways for different needs without having to duplicate the object and assign a different @@iterator for each one.

The example above would only work if the iterator function specified gets bound to the object being iterated. Not positive if that should be the case or not. If not bound, it could easily be bound in the for statement using something like address::keyValIterator.

# Edwin Reynoso (9 years ago)

No need, just replace this with the passed parameter:

function* keyValIterator (address) {
  for (let prop in address) {
    yield [ prop, address[prop] ];
  }
}

var address = {
  street: '420 Paper St.',
  city: 'Wilmington',
  state: 'Delaware'
};

for (let [ key, val ] of keyValIterator(address)) {
  console.log(key, val);
}
# Caitlin Potter (9 years ago)

I don’t know that a new syntax is really needed for this.

For the basic cases, you could just install the generator on the prototype

String.prototype.entries = function*() { yield* Array.prototype.entries.call(this.valueOf()); }
for (var entry of “str”.entries()) {
  // ...
}

That bind operator proposal would allow doing a similar thing without installing anything on the prototype, as well.

# JD Isaacks (9 years ago)

No need, just replace this with the passed parameter:

Edwin, ahh, that is great! I had not considered that, thank you!