Array.forEach() et al with additional parameters

Gary Guo nbdd0121 at hotmail.com
Sat Dec 20 04:47:28 PST 2014


I think extending standard libraries/functions is not the most elegant approach. I think what you suggest is basically trying to bind some parameter that isn't the first few continuous parameter (in this case, it is the 4th parameter) while keeping the first few parameter unbound. I believe there should be a way created to bind any parameter we want instead of extending the standard library we have.

For example, in your case,```
[1,2,3].forEach(myCallback.bindParameter(3, 'additionalFoo')) might be a better solution,```
btw, use the arrow function, it can be written as```
[1,2,3].forEach((element, count, array) => myCallback(element, count, array, 'additionalFoo'));```
which isn't too complicated, and at least to me, it is acceptable.
bindParameter function is not very hard to implement:```Function.prototype.bindParameter=function(idx, val){    var func=this;    return function(){        var arg=Array.prototype.slice.call(arguments);        arg[idx]=val;        func.apply(this, arg);    }}```


> Date: Sat, 20 Dec 2014 13:12:28 +0100
> From: mail at ChristianMayer.de
> To: es-discuss at mozilla.org
> Subject: Array.forEach() et al with additional parameters
> 
> I'm just stumbling over a little improvement (syntactic sugar) that
> could help to make code a bit smaller (-> less to debug, read,
> understand, etc. pp.)
> 
> When you want to pass additional parameters to the Array.forEach()
> callback function you currently must work with an additional (anonymous)
> function that is just wrapping stuff. (And for heavily recursive stuff
> cutting the useable call stack in half...)
> 
> Currently:
> ----------
> 
> function myCallback( element, count, array, additionalFoo )
> {
> console.log( 'Callback &' + count + ': ' + element, additionalFoo );
> }
> 
> [1,2,3].forEach( function( element, count, array ){
> myCallback( element, count, array, 'additionalFoo' );
> });
> 
> New:
> ----
> 
> [1,2,3].forEach( myCallback, undefined, 'additionalFoo' );
> 
> It could be discussed whether the additions parameter is only one (and
> thus the programmer has to pass multiple information in a Array or
> Object) or if all additional parameters will be passed on to the
> callback function.
> 
> The same holds for the similar functions "map", "every" and "some".
> 
> What do you think?
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20141220/92a96402/attachment.html>


More information about the es-discuss mailing list