for.at meta property

This is a mid-programming rant! But I've just had to add some pointless book-keeping to an iterator loop because I needed the index. This is exactly the sort of thing which ought to be automated by the language; it adds nothing but obscuring foliage to the code. So can we not have a meta property for.at that returns the iteration count of a loop? For example:

function findIndex( iterable, predicate )  {
   for ( const item of iterable )  {
       if ( predicate( item ) ) {
          return for.at;
       }
   }
   return -1;
}

As syntactic sugar for:

function findIndex( iterable, predicate )  {
    let at = 0;
    for ( const item of iterable )  {
        if ( predicate( item ) ) {
          return at;
        }
        ++at;
    }
    return -1;
}

(Bike shed the name. for.index might be another possibility.)

Adding syntax to avoid two trivial lines of code seems like a lot of cost for very little benefit.

Also, this is already rolled into the iterator-helpers proposal:

function findIndex( iterable, predicate )  {
   for ( const [i, item] of Iterator.from(iterable).asIndexedPairs() )  {
       if ( predicate( item ) ) {
          return i;
       }
   }
   return -1;
}
3 Likes

If you're working with a simple array today, you can use array.entries() as well.

> for (const [i, x] of ['a', 'b', 'c'].entries()) console.log(i, x)
0 a
1 b
2 c