max pleaner max pleaner - 1 year ago 67
Javascript Question

invoking curried function without passing another argument

I have a simple function that takes one argument

fn = function(argument) {console.log(argument)}

, I want to call the function and pass an external variable:

argument = 1

I realize that I could do it with a higher-order function, i.e.

fn = function(argument) {
function () {
argument = 1
setInterval(fn(argument), 1000)

And this does work, but I want to know if it can be done with

I've tried:

fn = _.curry(fn)("foo")
// since the function takes only one argument,
// here it is invoked and no longer can be
// passed as a function to setInterval

fn = _.curry(fn, 2)("foo")
// setting the arity to 2 makes it so the function
// isn't invoked. But setInterval does not pass
// the additional argument and so it never ends
// up getting invoked.

I feel like there is something I'm missing with these curry examples. Am I, or will curry not help here?

Answer Source

Indeed lodash _.curry seems not suitable for your use-case.

But you can use the vanilla JavaScript bind for this:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.


fun.bind(thisArg[, arg1[, arg2[, ...]]])

In your case your code would look like this:

fn = function(argument) {console.log(argument)}

var argument = 1
setInterval(fn.bind(this, argument), 1000)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download