0

I have so far:

function func(f,x) {
alert(f(x));
}

func(function(x) {return x*x;},2);

This works, but i am thinking that passing function(x) {return x*x;}, is excessive and I could just pass x*x, as the idea is that I can supply (pretty much) any function.

I have tried:

function func(f,y) {
g=function() {return f;};
alert(g(y));
}

func(x*x,2);

amongst others, but I can't get it to work. Perhaps if I passed 'x*x' as a string..?

1
  • you can use Function("x", "return " + "x*x" ) for that. i would cache the output because it's (relatively) expensive to create functions this way, but the generated functions themselves run very fast (no closure). Commented Jan 8, 2015 at 13:55

4 Answers 4

4

You're correct that the syntax is excessive, but for ES5 and before, that's just how it is.

However, in ES6 you can use the new "arrow function" lambda syntax:

func(x => x * x, 2);

See http://www.es6fiddle.net/i4o5uj2l/

FWIW, the above func isn't great since it only supports unary functions, i.e. those taking a single parameter. You could expand func to use ES6 "spread arguments":

function func(f, ...args) {
  console.log(f.apply(this, args));
}

func((x, y) => x * y, 3, 7);
> 21
Sign up to request clarification or add additional context in comments.

Comments

1

Well I have a way to do that using eval here http://jsfiddle.net/q5ayoszy/

function func(f,y) {

g=function()
{ x=y;
    return eval(f);
};
alert(g(y));
}

func('x*x',2);

Note : I pass the expression as a string and then use it inside the function.

You just need to assign the value of y to the variable x inside the function so the eval evaluates correctly

Comments

0

The only way to do that with a string is by using the infamous eval: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

var x = 2;

var y = eval("x * x"); //y = 4

But using eval is almost always a very bad idea.

1 Comment

Function() works better/faster/safer than eval() if you don't need closure.
0

You could use currying to break down the process into smaller functions:

function multiply(x) {
    return function() {
      return x*x;
    }
}

var bytwo = multiply(2);

bytwo(); // 4

1 Comment

I think the OP's problem is more to do with passing function references at all, rather than strictly to do with currying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.