Bind only second argument to javascript function

var add = function(a, b) {

    return a + b;
}
var addOne =add.bind(null,1);
var result = addOne(4);
console.log(result);

      

Here the associated value of a is 1 and b is 4.

How to assign an anchor value ie) 1 to the second argument of a function without using the spread operator (...)

+3


source to share


4 answers


You can take the swap function with the linkage to the last function.



var add = function (a, b) { console.log(a, b); return a + b; },
    swap = function (a, b) { return this(b, a); },
    addOne = swap.bind(add, 1),
    result = addOne(4);

console.log(result);
      

Run codeHide result


With a decorator as suggested by georg .



var add = function (a, b) { console.log(a, b); return a + b; },
    swap = function (f) { return function (b, a) { return f.call(this, a, b) }; },
    addOne = swap(add).bind(null, 1),
    result = addOne(4);

console.log(result);
      

Run codeHide result


You can use an object arguments

to reorder parameters.



var add = function (a, b, c, d, e) {
        console.log(a, b, c, d, e);
        return a + b + c + d + e;
    },
    swap = function (f) {
        return function () { 
            var arg = Array.apply(null, arguments);
            return f.apply(this, [arg.pop()].concat(arg));
        };
    },
    four = swap(add).bind(null, 2, 3, 4, 5),
    result = four(1);

console.log(result);
      

Run codeHide result


+3


source


You can use the following way

var add = function(x){
    return function(y){
        return x+y;
    }
}

add(2)(3); // gives 5
var add5 = add(5);
add5(10); // gives 15

      



here add5 () will set x = 5 for the function

0


source


This will help you with what you need.

var add = function(a) {
    return function(b) {
        return a + b;
    };
}
var addOne = add(1);
var result = addOne(4);
console.log(result);

      

0


source


You can try this

function add (n) {
    var func = function (x) {
        if(typeof x==="undefined"){
           x=0;
        }
        return add (n + x);
    };

    func.valueOf = func.toString = function () {
        return n;
    };

    return func;
}
console.log(+add(1)(2));
console.log(+add(1)(2)(3));
console.log(+add(1)(2)(5)(8));
      

Run codeHide result


0


source







All Articles