Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: always pass the nth argument in a function as fixed value by default

the function takes 3 parameters like

function p(x,y,z){
 console.log(arguments);
}

so when we call it like p(12,21,32)

a fourth argument should pass as say 56

so effectively the call should be p(12,21,32,56)

How to do this?

Condition We cannot change the function definition. I need to partially bind the fourth argument as 56 something like

p=p.bind(this,'','','',56); or use lodash

and then call p later like

p(12,21,32);

such that 56 should pass by default

like image 678
Shishir Arora Avatar asked Mar 29 '26 15:03

Shishir Arora


2 Answers

You can use _.partialRight() to create a new function that appends arguments to the end of the original function:

function p(a, b, c)
{
  alert([].join.call(arguments, ','));
}

p = _.partialRight(p, 56);
p(1,2,3); // 1,2,3,56
<script src="https://raw.githubusercontent.com/lodash/lodash/3.9.3/lodash.js"></script>

To exactly specify the position of the extra argument(s) you can use placeholders:

p = _.partialRight(p, _, _, _, _, _, _, 56); // add 56 as 7th arg
p(1,2,3); // 1,2,3,,,,56
like image 172
Ja͢ck Avatar answered Mar 31 '26 04:03

Ja͢ck


p = (function() {
    var old_p = p;
    return function(a, b, c) {
        return old_p(a, b, c, 56);
    };
})();

We remember the old version of p under the name old_p so we can invoke it even after we've redefined p. We do this inside the IIFE so that old_p does not pollute the global scope. Then, we return a function (which is assigned to p) which returns the result of calling old_p with the extra argument.

We can make this more general, to create "bound" functions which add extra arguments to any function call. Below I use ES6 syntax, especially the spread ... operator. However, you can accomplish the same thing by manipulating the arguments object and using apply:

function bind_with_arguments_at_end(f, ...extra_args) {
    return function(...args) {
        return f(...args, ...extra_args);
    }
}

Where the function involved is a method on an object, it makes sense to "pass through" this, so the new function can be called as this.bound_func and things continue to work. Do do this, we can use call:

function bind_with_arguments_at_end(f, ...extra_args) {
    return function(...args) {
        return f.call(this, ...args, ...extra_args);
               ^^^^^^^^^^^
    }
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!