17 February 2014

While reading through Highland Streams, I noticed how many of the functional bits ES6 will help–as soon as we get them. One function I rather liked, ncurry follows the basic curry syntax but solves the “function.length problem” by passing n, the length, as the first parameter.

The important part internally works just like leave (see Take or Leave Functional Programming). I rewrote the functions needed using ES6 notation; making heavy use of rest and spread operators. This included an ES6-style rewrite of leave.

I see one possible downside to this implementation. We can’t use this when applying leave’s function. We have to use null unless we add a receiver parameter to the signature somewhere.

Try it in the repl

var slice_ = _part_.create_( Array.prototype.slice );

var take_ = slice_.bind( null, 0 );

var leave = ( n )
=> ( fn, ...a )
=> ( ...b )
=> fn.apply( null, take_( n )( [...a, ...b] ) );

var ncurry = ( n, fn, ...a ) => {
if ( a.length >= n ) {
return leave( n )( fn )( ...a );
}
return ( ...b ) => {
var ab = [...a, ...b];
return ab.length < n ? ncurry( n, fn, ...ab ) : leave( n )( fn )( ...ab );
};
};

var max = ncurry( 3, Math.max );
max( 1, 2 )( 3, 4 ); //3

Try it in the repl



Discussion:

blog comments powered by Disqus