Skip to content

Latest commit

 

History

History

curry

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

curry

Transform a function into a sequence of functions each accepting a single argument.

Usage

var curry = require( '@stdlib/utils/curry' );

curry( fcn[, arity][, thisArg] )

Transforms a function into a sequence of functions each accepting a single argument.

function add( x, y ) {
    return x + y;
}

var fcn = curry( add );

var sum = fcn( 2 )( 3 );
// returns 5

By default, arity is equal to fcn.length. For functions without explicit parameters, provide an arity argument.

function add() {
    return arguments[ 0 ] + arguments[ 1 ];
}

var fcn = curry( add, 2 );

var sum = fcn( 2 )( 3 );
// returns 5

To specify the curried function execution context, provide a thisArg argument.

var obj = {
    'name': 'Ada',
    'greet': function greet( word1, word2 ) {
        return word1 + ' ' + word2 + ', ' + this.name + '!'
    }
};

var fcn = curry( obj.greet, obj );

var str = fcn( 'Hello' )( 'there' );
// returns 'Hello there, Ada!'

The function supports providing both an arity and execution context.

var obj = {
    'name': 'Ada',
    'greet': function greet() {
        return arguments[ 0 ] + ' ' + arguments[ 1 ] + ', ' + this.name + '!'
    }
};

var fcn = curry( obj.greet, 2, obj );

var str = fcn( 'Hello' )( 'there' );
// returns 'Hello there, Ada!'

Notes

  • Once providing a curried function with all expected arguments, the curried function returns the curried function result for all future invocations.

    function add( x, y, z ) {
        return x + y + z;
    }
    
    var fcn = curry( add );
    
    var sum = fcn( 5 )( 4 )( 3 );
    // returns 12
    
    sum = fcn( 6 );
    // returns 12
    
    sum = fcn( 1e3 );
    // returns 12

Examples

var curry = require( '@stdlib/utils/curry' );

var fcn;
var out;
var i;

function add( x, y, z, w, t, s ) {
    return x + y + z + w + t + s;
}

fcn = curry( add );

for ( i = 0; i < 10; i++ ) {
    out = fcn( i*10 );
    if ( typeof out === 'number' ) {
        console.log( out );
    }
}