pass index to forEach #144

Closed
ghost opened this Issue Jun 24, 2012 · 8 comments

Projects

None yet

5 participants

@ghost
ghost commented Jun 24, 2012

You have missed to pass the index for an element to forEach's iterator function.

Instead of:

iterator(item, cb)

it should be:

iterator(value, index, cb)

Better:

iterator(value, index, iterable, cb)

I need the index of the value in order to perform various operations.

@caolan
Owner
caolan commented Jun 25, 2012

I'd prefer not to require all four arguments on every iterator, it's verbose and would break backwards compatibility. That said, there's no doubt these values are useful. One option would be to use the iterator arity to determine the number of arguments to pass, but this might be unpredictable in some circumstances (eg, fs.readFile).

This means that making this change can only be done in the next major version. I'm not against the API change, but I'm afraid you may have to wait a while.

@ghost
ghost commented Jun 25, 2012

I totally agree.

Meanwhile I have solved this by setting up my own counter.

@sebicas
sebicas commented Oct 21, 2012

+1 for this.

@mratzloff

Why not just add a forEachWithIndex method? That's how Ruby handles it.

http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_with_index

@pierrevalade

Nice suggestion @mratzloff.

@brianmaissy
Contributor

@mratzloff, I also think that makes a lot of sense. If @caolan likes the idea too, I'll implement it and submit a pull request.

And then in the next version, if one were to want to unify the two methods, forEachWithIndex can be deprecated or removed altogether in favor of an expanded forEach, or alternatively it can be preserved and an arity-sensitive forEach can delegate to it as syntactic sugar.

I have one question about the suggestion, though. Could @wingy or anyone else explain to me what the iterable argument is and what it is used for? The entire array which was passed to forEachWithIndex? Some other sort of object which is used to access elements of that array?

@mratzloff

And then in the next version, if one were to want to unify the two methods, forEachWithIndex can be deprecated or removed altogether in favor of an expanded forEach, or alternatively it can be preserved and an arity-sensitive forEach can delegate to it as syntactic sugar.

@brianmaissy, exactly.

@brianmaissy
Contributor

This is going to be implemented as the more general forEachOf, see #168. This issue should be closed.

@caolan caolan closed this Feb 7, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment