String.prototype.entries()

We have the following:

  1. Array.prototype.entries()
  2. Map.prototype.entries()
  3. Set.prototype.entries()
  4. TypedArray.prototype.entries()

We don't yet have String.prototype.entries().

With Array.prototype.entries() I can write:

for (const [y, row] of grid.entries()) {
  for (const [x, value] of row.entries()) {
    /* handle x, y, value tuple in a "2D" array */
  }
}

If instead I have an array of strings then I'd like to be able to write the same code as for an array of arrays but where the inner for loop iterates over the code points of the string (consistent with String.prototype[Symbol.iterator]()) along with the index.

That would mean the index doesn’t line up with the code units of the string (since it’d be iterating code points), which might be confusing. What’s the use case?

Who says the index needs to increase by 1 each time?

True, but then the index isn't matching up to each iteration.

I'm still interested in the use case, especially considering iterator helpers now allows you to do Iterator.from(string).map((codePoint, count) => {}).

The .entries() contract doesn't guarantee that - see Object.entries. What it does guarantee is that every key returned can be used to access the associated value on the original object.

And I'd say that iterator helper - which, as your choice of parameter naming shows, returns the count of values and not their index - is a perfect reason to have String.prototype.entries() return something else. Maybe I want to iterate through the characters of a string to find the start of the substring I'm looking for, then slice() the string from that point? I need the code unit index for that.

1 Like

Yeah, this is definitely a missing feature.

2 Likes

What might be good next steps here? I've read/seen various TC39 proposals over the years but I've never authored one… I'm concerned that might be a lot of work but I suppose in order to get anything added folks need to champion them.

Hi @mfulton26!

Yep, a TC39 member is required to champion the proposal: ecma262/CONTRIBUTING.md at 5d8f62d6ab761960206c3f6ddf4992534fe9726f · tc39/ecma262 · GitHub