back to Overview

_.partial()

Creates a new function that calls the given function with some arguments pre-filled.
Util module only.

Syntax Variants

_.partial(f, beforeArgs)
_.partial(f, beforeArgs, afterArgs)

Parameters

f
the function to bind
beforeArgs
either a list of values to insert in front of the arguments, or a single non-list value to put in front. If null or not set, there won't be any arguments inserted. If you need to insert a null, undefined or a list, just wrap them in an array (e.g. [null]).
afterArgs (optional)
either a list of values to append to the end of the arguments, or a single non-list value to append. If null or not set, there won't be any arguments appended. If you need to append a null, undefined or a list, just wrap them in an array (e.g. [null]).
(return value)
the resulting string

Description

Creates a new function that calls the given function with some arguments pre-filled. You can specify one or more arguments to be put in front of the arguments list as well as arguments that will be appended to the argument list.

See also _.bind(), if you want to set 'this' as well. partial() calls the wrapped function with the 'this' the wrapper has been called with.

Example

Create functions that divide:

function div(a, b) { return a / b; }
var div5 = _.partial(add, 5);         // like function(a) { return 5 / a; }
var divBy5 = _.partial(add, null, 5); // like function(a) { return a / 5; }

Example

Create functions that remove characters from the beginning and/or end of a string:

// This function multiplies the first count items of the list by factor
function multiply(list, count, factor) {
    return list.map(function(v, index) {
        return index < count ? factor * v : v;
    });
}

var mul3by2 = _.partial(multiply, null, [3, 2]);
var r1 = mul10by2(_(1, 2, 3, 4, 5));   // returns _(2, 4, 6, 4, 5)

var mul123 = _.partial(multiply, [_(1, 2, 3)]);                // array wrapper required to pass a list!
var r2 = mul123(2, 5);                 // returns _(5, 10, 3)

var mul12345By2 = _.partial(multiply, [_(1, 2, 3, 4, 5)], 2);  // array wrapper required!
var r3 = mul12345By2(3);               // returns _(2, 4, 6, 4, 5)

See also..

  • _.bind() is similar to partial(), but allows you to set 'this'.

Comments

comments powered by Disqus

back to Overview

Functions