Array method ranges

# Peter van der Zee (13 years ago)

What about adding specific range arguments to the es5 array methods (forEach, map, etc)? Currently the start (inclusive) and stop (exclusive) is always 0 ... length, but what if you only want to map over a sub range of the array? Or maybe I want to traverse the array in reverse? I'd either have to slice it or .reverse it, neither are something I would want. So I fall back to for or while loops.

As for the context parameter, I believe undefined won't change the context opposed to omitting it, right?

arr.forEach(function(){ ...}); // same as arr.forEach(function(){ ...}, undefined, 0, arr.length);

arr.slice(10,10).forEach... arr.slice(80,20).reverse().forEach... =>

arr.forEach(function(){ ...}, undefined, 10, 20); arr.forEach(function(){ ...}, undefined, 100, 80); // run from 100 to 80, backwards

Negative numbers could behave the same as in slice (offsets from the last item, rather than the first).

arr.forEach(function(){ ...}, undefined, -20); // run from length-20 to length arr.forEach(function(){ ...}, undefined, -20, -10); // run from length-20 to length-10 (so, forward) arr.forEach(function(){ ...}, undefined, -20, -30); // run from length-20 to length-30 (so, backwards)

Of course, it would still skip the holes in sparse arrays.

# François REMY (13 years ago)

Good idea. However, I don't like the fact "arr.forEach(f,null,-1,0)" doesn't walk the array backwards properly. Not sure it's worth to have it built-in though.

# Erik Arvidsson (13 years ago)

At this point I think we are better of moving towards iterator methods. For example if we had an islice like the one in Python's itertools [*] we can do:

for (let v of islice(arr, start, stop)) { ... }

this would be equivalent to your proposed

arr.forEach((v) => { ... }, undefined, start, stop)

with the benefit that it composes much better.

[*] docs.python.org/2/library/itertools.html#itertools.islice

# Brendan Eich (13 years ago)

Yes, this was the plan. I don't see a strawman, yet. Cc'ing jorendorff.

# Brandon Benvie (13 years ago)

It looks like the beginnings of an outline were added to the standard modules list living under '@iter' with zip and unzip so far: harmony:modules_standard. But no separate strawman yet.